From 94296f9dd1235e5b624fa52488fc6d317abb4e99 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Wed, 30 Oct 2024 23:45:30 -0600 Subject: [PATCH 01/34] FISH-8925: starting changes to use epicyro --- appserver/connectors/work-management/pom.xml | 7 +- .../context/ConnectorCallbackHandler.java | 8 +- .../deployment/runtime/RuntimeDescriptor.java | 4 +- .../glassfish/ejb/startup/EjbDeployer.java | 2 +- .../appclient/AppClientSecurityInfoImpl.java | 6 +- .../security/appclient/ConfigXMLParser.java | 49 +- appserver/security/core-ee/pom.xml | 6 +- .../security/ee/JavaEESecurityLifecycle.java | 89 +- .../ee/auth/login/DigestLoginModule.java | 6 +- .../jakarta/AuthMessagePolicy.java | 238 +++++ .../jakarta}/ConfigDomainParser.java | 44 +- .../jakarta}/WebServicesDelegate.java | 6 +- .../security/ee/authorize}/PolicyLoader.java | 3 +- .../jacc/JaccWebAuthorizationManager.java | 3 +- .../security/jacc/package-info.java | 4 +- .../security/jaspic/AuthMessagePolicy.java | 334 ------ ...essageSecurityConfigEventListenerImpl.java | 76 +- .../security/jaspic/config/ConfigParser.java | 101 -- .../jaspic/config/GFAuthConfigFactory.java | 126 --- .../jaspic/config/GFServerConfigProvider.java | 981 ------------------ ...rvices.java => PayaraEpicyroServices.java} | 8 +- ...java => PayaraEpicyroServletServices.java} | 17 +- .../enterprise/security/jauth/ConfigFile.java | 619 ----------- .../PrincipalGroupFactoryImpl.java | 10 +- .../jaspic-provider-framework/osgi.bundle | 4 +- .../jaspic-provider-framework/pom.xml | 6 +- .../config/factory/AuthConfigFileFactory.java | 89 -- .../config/factory/BaseAuthConfigFactory.java | 728 ------------- .../config/factory/RegStoreFileParser.java | 454 -------- .../AuthConfigRegistrationWrapper.java | 180 ---- .../com/sun/jaspic/services/ConfigData.java | 83 -- .../sun/jaspic/services/JaspicServices.java | 237 ----- .../services/RegistrationWrapperRemover.java | 53 - .../com/sun/jaspic/config/FactoryTest.java | 5 +- .../sun/jaspic/config/RuntimeSurrogate.java | 4 +- .../security/realmadapter/JaspicRealm.java | 10 +- .../security/webservices.security/pom.xml | 12 +- .../jaspic/provider/config/PipeHelper.java | 61 +- .../webservices/ClientPipeCloser.java | 4 +- .../webservices/ClientPipeCreator.java | 4 +- .../webservices/WebServicesDelegateImpl.java | 6 +- core/core-parent/pom.xml | 2 + core/pom.xml | 6 + .../common/DynamicAttributesDescriptor.java | 6 +- nucleus/security/core/pom.xml | 6 +- .../security/BasePasswordLoginModule.java | 12 +- .../security/PrincipalGroupFactory.java | 6 +- .../security/audit/BaseAuditManager.java | 4 +- .../common/ClientSecurityContext.java | 7 +- 49 files changed, 527 insertions(+), 4209 deletions(-) create mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic/config => ee/authentication/jakarta}/ConfigDomainParser.java (86%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic => ee/authentication/jakarta}/WebServicesDelegate.java (95%) rename {nucleus/security/core/src/main/java/com/sun/enterprise/security => appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize}/PolicyLoader.java (99%) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/{PayaraJaspicServices.java => PayaraEpicyroServices.java} (91%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/{PayaraJaspicServletServices.java => PayaraEpicyroServletServices.java} (86%) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java diff --git a/appserver/connectors/work-management/pom.xml b/appserver/connectors/work-management/pom.xml index 46e6dcf36fc..cb32093acb2 100644 --- a/appserver/connectors/work-management/pom.xml +++ b/appserver/connectors/work-management/pom.xml @@ -39,7 +39,7 @@ holder. --> - + 4.0.0 @@ -148,5 +148,10 @@ logging-annotation-processor true + + + org.glassfish.epicyro + epicyro + diff --git a/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java b/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java index a259af6a339..fcd5da07d55 100644 --- a/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java +++ b/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.connectors.work.context; import com.sun.enterprise.security.SecurityContext; @@ -45,7 +45,7 @@ import org.glassfish.logging.annotation.LogMessageInfo; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.epicyro.config.helper.CallerPrincipal; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -276,12 +276,12 @@ public Callback handleCallerPrincipalCallbackWithMapping(CallerPrincipalCallback private Principal getMappedPrincipal(Principal eisPrincipal, String eisName) { Principal asPrincipal = null; if (eisPrincipal != null) { - asPrincipal = (PrincipalImpl) securityMap.get(eisPrincipal); + asPrincipal = (CallerPrincipal) securityMap.get(eisPrincipal); if(logger.isLoggable(Level.FINEST)){ logger.finest("got mapped principal as [" + asPrincipal + "] for eis-group [" + eisPrincipal.getName() + "]"); } } else if (eisName != null) { - asPrincipal = ((PrincipalImpl) securityMap.get(new PrincipalImpl(eisName))); + asPrincipal = ((CallerPrincipal) securityMap.get(new CallerPrincipal(eisName))); if(logger.isLoggable(Level.FINEST)){ logger.finest("got mapped principal as [" + asPrincipal + "] for eis-group [" + eisName + "]"); } diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java index 7b89d2bc908..1be283f8542 100644 --- a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2020] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.deployment.runtime; @@ -121,7 +121,7 @@ public void setValue(String name, Object value) { /** * @return a property value */ - public Object getValue(String name) { + public T getValue(String name) { return getExtraAttribute(name); } diff --git a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java index 46326ada624..207f4258b46 100644 --- a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java +++ b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java @@ -89,7 +89,7 @@ import com.sun.enterprise.deployment.Application; import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.module.bootstrap.StartupContext; -import com.sun.enterprise.security.PolicyLoader; +import com.sun.enterprise.security.ee.authorize.PolicyLoader; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.util.IASSecurityException; import com.sun.enterprise.util.LocalStringManagerImpl; diff --git a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java index 7cc9ff43c2c..e5fd188d81e 100644 --- a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java +++ b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2022] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.appclient; import com.sun.enterprise.security.SecurityServicesUtil; @@ -50,7 +50,6 @@ import com.sun.enterprise.security.common.Util; import com.sun.enterprise.security.ee.J2EESecurityManager; import com.sun.enterprise.security.integration.AppClientSSL; -import com.sun.enterprise.security.jaspic.config.GFAuthConfigFactory; import com.sun.enterprise.security.ssl.SSLUtils; import com.sun.logging.LogDomains; import jakarta.inject.Inject; @@ -60,6 +59,7 @@ import org.glassfish.appclient.client.acc.config.Ssl; import org.glassfish.appclient.client.acc.config.TargetServer; import org.glassfish.enterprise.iiop.api.IIOPSSLUtil; +import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; import org.jvnet.hk2.annotations.Service; import javax.security.auth.Subject; @@ -147,7 +147,7 @@ public void initializeSecurity( if (defaultFactory == null) { java.security.Security.setProperty (AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY, - GFAuthConfigFactory.class.getName()); + AuthConfigFileFactory.class.getName()); } } catch (Exception e) { diff --git a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java index ec0352c1261..197b75e9db2 100644 --- a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java +++ b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java @@ -37,15 +37,12 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright 2019-2022 Payara Foundation and/or its affiliates +// Portions Copyright 2019-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.security.appclient; import com.sun.enterprise.security.common.Util; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; -import com.sun.enterprise.security.jaspic.config.ConfigParser; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; import com.sun.logging.LogDomains; import jakarta.security.auth.message.MessagePolicy; import jakarta.xml.bind.JAXBContext; @@ -57,6 +54,10 @@ import org.glassfish.appclient.client.acc.config.ProviderConfig; import org.glassfish.appclient.client.acc.config.RequestPolicy; import org.glassfish.appclient.client.acc.config.ResponsePolicy; +import org.glassfish.epicyro.config.factory.ConfigParser; +import org.glassfish.epicyro.config.helper.AuthMessagePolicy; +import org.glassfish.epicyro.data.AuthModuleConfig; +import org.glassfish.epicyro.data.AuthModulesLayerConfig; import org.glassfish.internal.api.Globals; import java.io.FileInputStream; @@ -83,22 +84,22 @@ public class ConfigXMLParser implements ConfigParser { private static Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{\\{(.*?)}}|\\$\\{(.*?)}"); // configuration info - private Map configMap = new HashMap(); + private final Map authModuleLayers = new HashMap<>(); private Set layersWithDefault = new HashSet(); private List msgSecConfigs = null; private static final String ACC_XML = "glassfish-acc.xml.url"; - public ConfigXMLParser() throws IOException { + public ConfigXMLParser() { } public void initialize(List msgConfigs) throws IOException { this.msgSecConfigs = msgConfigs; if (this.msgSecConfigs != null) { - processClientConfigContext(configMap); + processClientConfigContext(authModuleLayers); } } - private void processClientConfigContext(Map newConfig) throws IOException { + private void processClientConfigContext(Map newConfig) throws IOException { // auth-layer String intercept = null; @@ -113,16 +114,12 @@ private void processClientConfigContext(Map newConfig) throws IOException { } } - - public Map getConfigMap() { - return configMap; - } - + public Set getLayersWithDefault() { return layersWithDefault; } - private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { + private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { String intercept = null; String defaultServerID = null; String defaultClientID = null; @@ -140,19 +137,19 @@ private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfi layersWithDefault.add(intercept); } - GFServerConfigProvider.InterceptEntry intEntry = (GFServerConfigProvider.InterceptEntry) newConfig.get(intercept); + AuthModulesLayerConfig intEntry = newConfig.get(intercept); if (intEntry != null) { throw new IOException("found multiple MessageSecurityConfig " + "entries with the same auth-layer"); } // create new intercept entry - intEntry = new GFServerConfigProvider.InterceptEntry(defaultClientID, defaultServerID, null); + intEntry = new AuthModulesLayerConfig(defaultClientID, defaultServerID, null); newConfig.put(intercept, intEntry); return intercept; } // duplicate implementation for clientbeans config - private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercept) throws IOException { + private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercept) throws IOException { String id = pConfig.getProviderId(); String type = pConfig.getProviderType(); String moduleClass = pConfig.getClassName(); @@ -183,20 +180,21 @@ private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercep // create ID entry - GFServerConfigProvider.IDEntry idEntry = new GFServerConfigProvider.IDEntry(type, moduleClass, requestPolicy, - responsePolicy, options); + //GFServerConfigProvider.IDEntry idEntry = new GFServerConfigProvider.IDEntry(type, moduleClass, requestPolicy, + // responsePolicy, options); + AuthModuleConfig idEntry = new AuthModuleConfig(type, moduleClass, requestPolicy, responsePolicy, options); - GFServerConfigProvider.InterceptEntry intEntry = (GFServerConfigProvider.InterceptEntry) newConfig.get(intercept); + AuthModulesLayerConfig intEntry = newConfig.get(intercept); if (intEntry == null) { throw new IOException("intercept entry for " + intercept + " must be specified before ID entries"); } - if (intEntry.getIdMap() == null) { - intEntry.setIdMap(new HashMap()); + if (intEntry.getAuthModules() == null) { + intEntry.setIdMap(new HashMap<>()); } // map id to Intercept - intEntry.getIdMap().put(id, idEntry); + intEntry.getAuthModules().put(id, idEntry); } private String expand(String rawProperty) { @@ -270,4 +268,9 @@ public void initialize(Object config) throws IOException { this.initialize(msgconfigs); } + + @Override + public Map getAuthModuleLayers() { + return this.authModuleLayers; + } } diff --git a/appserver/security/core-ee/pom.xml b/appserver/security/core-ee/pom.xml index a160f535178..67ab2223696 100644 --- a/appserver/security/core-ee/pom.xml +++ b/appserver/security/core-ee/pom.xml @@ -41,7 +41,7 @@ --> - + 4.0.0 @@ -282,5 +282,9 @@ org.glassfish.exousia exousia + + org.glassfish.epicyro + epicyro + diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java index 6a33dc32c3e..fb41dad5358 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java @@ -37,26 +37,39 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.ee; import com.sun.enterprise.security.ContainerSecurityLifecycle; -import com.sun.enterprise.security.jaspic.config.GFAuthConfigFactory; +import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; +import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; +import com.sun.enterprise.security.ee.authorize.PolicyLoader; import com.sun.logging.LogDomains; +import jakarta.inject.Inject; +import jakarta.security.auth.message.MessageInfo; +import jakarta.security.auth.message.MessagePolicy; +import java.security.Provider; import java.security.Security; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; import java.util.logging.Logger; import jakarta.inject.Singleton; import org.glassfish.common.util.Constants; +import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import org.glassfish.hk2.api.PostConstruct; import org.glassfish.hk2.api.Rank; +import org.glassfish.internal.api.Globals; import org.glassfish.internal.api.InitRunLevel; import org.jvnet.hk2.annotations.Service; -import static java.util.logging.Level.WARNING; import static jakarta.security.auth.message.config.AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY; +import static org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory.DEFAULT_FACTORY_DEFAULT_PROVIDERS; /** @@ -71,42 +84,62 @@ public class JavaEESecurityLifecycle implements ContainerSecurityLifecycle, Post private static final Logger LOG = LogDomains.getLogger(JavaEESecurityLifecycle.class, LogDomains.SECURITY_LOGGER); + @Inject + PolicyLoader policyLoader; + @Override public void postConstruct() { onInitialization(); } - @Override public void onInitialization() { - LOG.finest(() -> "Initializing " + getClass()); - - // TODO: Need some way to not override the security manager if the EmbeddedServer was - // run with a different non-default security manager. - // - // Right now there seems no way to find out if the security manager is the VM's default security manager. - final SecurityManager systemSecurityManager = System.getSecurityManager(); - if (systemSecurityManager != null && !(J2EESecurityManager.class.equals(systemSecurityManager.getClass()))) { - J2EESecurityManager eeSecurityManager = new J2EESecurityManager(); - try { - System.setSecurityManager(eeSecurityManager); - LOG.config(() -> "System security manager has been set to " + eeSecurityManager); - } catch (SecurityException ex) { - LOG.log(WARNING, "security.secmgr.could.not.override", ex); - } - } - initializeJASPIC(); + initializeJakartaAuthentication(); + initializeJakartaAuthorization(); } - private void initializeJASPIC() { + private void initializeJakartaAuthentication() { + // Define default factory if it is not already defined. - // The factory will be constructed on the first getFactory call. - final String defaultFactory = Security.getProperty(DEFAULT_FACTORY_SECURITY_PROPERTY); + // The factory will be constructed on first getFactory call. + + String defaultFactory = Security.getProperty(DEFAULT_FACTORY_SECURITY_PROPERTY); if (defaultFactory == null) { - final String defaultAuthConfigProvideFactoryClassName = GFAuthConfigFactory.class.getName(); - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, defaultAuthConfigProvideFactoryClassName); - LOG.config(() -> String.format("System JVM option '%s' has been set to '%s'", - DEFAULT_FACTORY_SECURITY_PROPERTY, defaultAuthConfigProvideFactoryClassName)); + Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, AuthConfigFileFactory.class.getName()); + } + + String defaultProvidersString = null; + WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); + if (delegate == null) { + defaultProvidersString = GFServerConfigProvider.class.getName(); + } else { + // NOTE: Order matters here. Providers for the same auth layer (HttpServlet or SOAP) will be overwritten + // by ones that appear later in this string without warning. + defaultProvidersString = delegate.getDefaultWebServicesProvider() + " " + GFServerConfigProvider.class.getName(); } + + Security.setProperty(DEFAULT_FACTORY_DEFAULT_PROVIDERS, defaultProvidersString); + + Function authContextIdGenerator = + e -> Globals.get(WebServicesDelegate.class).getAuthContextID(e); + + BiFunction, MessagePolicy[]> soapPolicyGenerator = + (authContextId, properties) -> AuthMessagePolicy.getSOAPPolicies( + AuthMessagePolicy.getMessageSecurityBinding("SOAP", properties), + authContextId, true); + + Provider provider = new Provider("EleosProvider", "1.0", "") { + private static final long serialVersionUID = 1L; + }; + provider.put("authContextIdGenerator", authContextIdGenerator); + provider.put("soapPolicyGenerator", soapPolicyGenerator); + + Security.addProvider(provider); + + System.setProperty("config.parser", ConfigDomainParser.class.getName()); + } + + private void initializeJakartaAuthorization() { + policyLoader.loadPolicy(); } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java index 558144aaa21..3fe8835a307 100755 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.ee.auth.login; import static com.sun.logging.LogDomains.SECURITY_LOGGER; @@ -58,7 +58,7 @@ import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.epicyro.config.helper.CallerPrincipal; import com.sun.enterprise.security.PrincipalGroupFactory; import com.sun.enterprise.security.auth.digest.api.DigestAlgorithmParameter; @@ -76,7 +76,7 @@ public abstract class DigestLoginModule implements LoginModule { protected boolean _succeeded; protected boolean _commitSucceeded; - protected PrincipalImpl _userPrincipal; + protected CallerPrincipal _userPrincipal; private DigestCredentials digestCredentials; private Subject subject; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java new file mode 100644 index 00000000000..fc2dc352ab3 --- /dev/null +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ +package com.sun.enterprise.security.ee.authentication.jakarta; + +import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; +import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; +import static org.glassfish.epicyro.config.helper.HttpServletConstants.SOAP; + +import com.sun.enterprise.deployment.ServiceReferenceDescriptor; +import com.sun.enterprise.deployment.WebBundleDescriptor; +import com.sun.enterprise.deployment.WebServiceEndpoint; +import com.sun.enterprise.deployment.runtime.common.MessageDescriptor; +import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; +import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; +import com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor; +import com.sun.enterprise.deployment.runtime.web.SunWebApp; +import jakarta.security.auth.message.MessagePolicy; +import java.util.List; +import java.util.Map; +import javax.security.auth.callback.CallbackHandler; +import org.glassfish.internal.api.Globals; + +/** + * Utility class for Jakarta Authentication appserver implementation. + */ +public class AuthMessagePolicy { + + public static final String WEB_BUNDLE = "WEB_BUNDLE"; + + private static final String HANDLER_CLASS_PROPERTY = "security.jmac.config.ConfigHelper.CallbackHandler"; + private static final String DEFAULT_HANDLER_CLASS = "com.sun.enterprise.security.ee.authentication.jakarta.callback.ContainerCallbackHandler"; + + private static String handlerClassName; + + private AuthMessagePolicy() { + } + + public static MessageSecurityBindingDescriptor getMessageSecurityBinding(String layer, Map properties) { + if (properties == null) { + return null; + } + + MessageSecurityBindingDescriptor binding = null; + + WebServiceEndpoint webServiceEndpoint = (WebServiceEndpoint) properties.get("SERVICE_ENDPOINT"); + + if (webServiceEndpoint != null) { + binding = webServiceEndpoint.getMessageSecurityBinding(); + } else { + ServiceReferenceDescriptor serviceReferenceDescriptor = (ServiceReferenceDescriptor) properties.get("SERVICE_REF"); + if (serviceReferenceDescriptor != null) { + WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); + if (delegate != null) { + binding = delegate.getBinding(serviceReferenceDescriptor, properties); + } + } + } + + if (binding != null) { + String bindingLayer = (String) binding.getValue(AUTH_LAYER); + if (bindingLayer == null || layer.equals(bindingLayer)) { + return binding; + } + } + + return null; + } + + public static MessagePolicy getMessagePolicy(ProtectionDescriptor protectionDescriptor) { + MessagePolicy messagePolicy = null; + if (protectionDescriptor != null) { + String source = protectionDescriptor.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); + String recipient = protectionDescriptor.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); + messagePolicy = org.glassfish.epicyro.config.helper.AuthMessagePolicy.getMessagePolicy(source, recipient); + } + + return messagePolicy; + } + + public static String getProviderID(MessageSecurityBindingDescriptor binding) { + if (binding == null) { + return null; + } + + if (!SOAP.equals(binding.getValue(AUTH_LAYER))) { + return null; + } + + return binding.getValue(PROVIDER_ID); + } + + public static MessagePolicy[] getSOAPPolicies(MessageSecurityBindingDescriptor binding, String operation, boolean onePolicy) { + MessagePolicy requestPolicy = null; + MessagePolicy responsePolicy = null; + + if (binding != null) { + List messageSecurityDescriptors = null; + String layer = binding.getValue(AUTH_LAYER); + if (SOAP.equals(layer)) { + messageSecurityDescriptors = binding.getMessageSecurityDescriptors(); + } + + if (messageSecurityDescriptors != null) { + if (onePolicy) { + if (messageSecurityDescriptors.size() > 0) { + MessageSecurityDescriptor messageSecurityDescriptor = messageSecurityDescriptors.get(0); + requestPolicy = getMessagePolicy(messageSecurityDescriptor.getRequestProtectionDescriptor()); + responsePolicy = getMessagePolicy(messageSecurityDescriptor.getResponseProtectionDescriptor()); + } + } else { // try to match + MessageSecurityDescriptor matchMsd = null; + for (int i = 0; i < messageSecurityDescriptors.size(); i++) { + MessageSecurityDescriptor msd = messageSecurityDescriptors.get(i); + List msgDescs = msd.getMessageDescriptors(); + for (int j = i + 1; j < msgDescs.size(); j++) { + // XXX don't know how to get JavaMethod from operation + MessageDescriptor msgDesc = msgDescs.get(j); + String opName = msgDesc.getOperationName(); + if (opName == null && matchMsd == null) { + matchMsd = msd; + } else if (opName != null && opName.equals(operation)) { + matchMsd = msd; + break; + } + } + + if (matchMsd != null) { + requestPolicy = getMessagePolicy(matchMsd.getRequestProtectionDescriptor()); + responsePolicy = getMessagePolicy(matchMsd.getResponseProtectionDescriptor()); + } + } + } + } + } + + return new MessagePolicy[] { requestPolicy, responsePolicy }; + } + + public static boolean oneSOAPPolicy(MessageSecurityBindingDescriptor binding) { + + boolean onePolicy = true; + List msgSecDescs = null; + if (binding != null) { + String layer = binding.getAttributeValue(AUTH_LAYER); + if (SOAP.equals(layer)) { + msgSecDescs = binding.getMessageSecurityDescriptors(); + } + } + + if (msgSecDescs == null) { + return true; + } + + for (int i = 0; i < msgSecDescs.size(); i++) { + + MessageSecurityDescriptor msd = msgSecDescs.get(i); + + // Determine if all the different messageSecurityDesriptors have the + // same policy which will help us interpret the effective policy if + // we cannot determine the opcode of a request at runtime. + for (int j = 0; j < msgSecDescs.size(); j++) { + if (j != i && !policiesAreEqual(msd, msgSecDescs.get(j))) { + onePolicy = false; + } + } + } + + return onePolicy; + } + + public static SunWebApp getSunWebApp(Map properties) { + if (properties == null) { + return null; + } + + WebBundleDescriptor webBundle = (WebBundleDescriptor) properties.get(WEB_BUNDLE); + return webBundle.getSunDescriptor(); + } + + public static String getProviderID(SunWebApp sunWebApp) { + if (sunWebApp == null) { + return null; + } + + return sunWebApp.getAttributeValue(SunWebApp.HTTPSERVLET_SECURITY_PROVIDER); + } + + + public static CallbackHandler getDefaultCallbackHandler() { + try { + if (handlerClassName == null) { + handlerClassName = System.getProperty(HANDLER_CLASS_PROPERTY, DEFAULT_HANDLER_CLASS); + } + + return (CallbackHandler) + Class.forName(handlerClassName, true, Thread.currentThread().getContextClassLoader()) + .getDeclaredConstructor() + .newInstance(); + + } catch (ReflectiveOperationException pae) { + throw new RuntimeException(pae); + } + } + + private static boolean policiesAreEqual(MessageSecurityDescriptor reference, MessageSecurityDescriptor other) { + return protectionDescriptorsAreEqual(reference.getRequestProtectionDescriptor(), other.getRequestProtectionDescriptor()) + && protectionDescriptorsAreEqual(reference.getResponseProtectionDescriptor(), other.getResponseProtectionDescriptor()); + } + + private static boolean protectionDescriptorsAreEqual(ProtectionDescriptor pd1, ProtectionDescriptor pd2) { + String authSource1 = pd1.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); + String authRecipient1 = pd1.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); + + String authSource2 = pd2.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); + String authRecipient2 = pd2.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); + + boolean sameAuthSource = authSource1 == null && authSource2 == null || authSource1 != null && authSource1.equals(authSource2); + boolean sameAuthRecipient = authRecipient1 == null && authRecipient2 == null + || authRecipient1 != null && authRecipient1.equals(authRecipient2); + + return sameAuthSource && sameAuthRecipient; + } +} + diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigDomainParser.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/ConfigDomainParser.java similarity index 86% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigDomainParser.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/ConfigDomainParser.java index c978289d313..f93a305683e 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigDomainParser.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/ConfigDomainParser.java @@ -37,18 +37,21 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright 2019-2022 Payara Foundation and/or its affiliates +// Portions Copyright 2019-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license -package com.sun.enterprise.security.jaspic.config; +package com.sun.enterprise.security.ee.authentication.jakarta; import com.sun.enterprise.config.serverbeans.MessageSecurityConfig; import com.sun.enterprise.config.serverbeans.ProviderConfig; import com.sun.enterprise.config.serverbeans.RequestPolicy; import com.sun.enterprise.config.serverbeans.ResponsePolicy; import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; import com.sun.logging.LogDomains; import jakarta.security.auth.message.MessagePolicy; +import org.glassfish.epicyro.config.factory.ConfigParser; +import org.glassfish.epicyro.config.helper.AuthMessagePolicy; +import org.glassfish.epicyro.data.AuthModuleConfig; +import org.glassfish.epicyro.data.AuthModulesLayerConfig; import org.glassfish.internal.api.Globals; import org.jvnet.hk2.config.types.Property; @@ -78,10 +81,10 @@ public class ConfigDomainParser implements ConfigParser { private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{\\{(.*?)}}|\\$\\{(.*?)}"); // configuration info - private Map configMap = new HashMap<>(); + private Map configMap = new HashMap<>(); private Set layersWithDefault = new HashSet(); - public ConfigDomainParser() throws IOException { + public ConfigDomainParser() { } public void initialize(Object service) throws IOException { @@ -94,7 +97,12 @@ public void initialize(Object service) throws IOException { } } - private void processServerConfig(SecurityService service, Map newConfig) throws IOException { + @Override + public Map getAuthModuleLayers() { + return configMap; + } + + private void processServerConfig(SecurityService service, Map newConfig) throws IOException { List configList = service.getMessageSecurityConfig(); if (configList != null) { @@ -119,7 +127,7 @@ private void processServerConfig(SecurityService service, Map getConfigMap() { + public Map getConfigMap() { return configMap; } @@ -127,7 +135,7 @@ public Set getLayersWithDefault() { return layersWithDefault; } - private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { + private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { String intercept = null; String defaultServerID = null; String defaultClientID = null; @@ -145,19 +153,19 @@ private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig, String intercept) throws IOException { + private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercept) throws IOException { String id = pConfig.getProviderId(); String type = pConfig.getProviderType(); @@ -194,20 +202,20 @@ private void parseIDEntry(ProviderConfig pConfig, Map(); + if (intEntry.getAuthModules() == null) { + intEntry.setIdMap(new HashMap()); } // map id to Intercept - intEntry.idMap.put(id, idEntry); + intEntry.getAuthModules().put(id, idEntry); } private String expand(String rawProperty) { diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/WebServicesDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java similarity index 95% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/WebServicesDelegate.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java index 2241ca072f6..7951de32a2f 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/WebServicesDelegate.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java @@ -37,8 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic; +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authentication.jakarta; import java.util.Map; @@ -50,7 +50,7 @@ import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; import com.sun.enterprise.security.jauth.AuthParam; -import com.sun.jaspic.services.RegistrationWrapperRemover; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; /** * A Delegate interface for handling WebServices specific security and JASPIC (JSR 196) providers. diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java similarity index 99% rename from nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java index 4071525d44d..10612bf5fdc 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java @@ -38,10 +38,11 @@ * holder. */ // Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security; +package com.sun.enterprise.security.ee.authorize; import com.sun.enterprise.config.serverbeans.JaccProvider; import com.sun.enterprise.config.serverbeans.SecurityService; +import com.sun.enterprise.security.SecurityLoggerInfo; import com.sun.enterprise.util.i18n.StringManager; import jakarta.inject.Inject; import jakarta.inject.Named; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java index ca9558ac5e2..84bec4504fd 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java @@ -49,7 +49,7 @@ import com.sun.enterprise.deployment.runtime.common.wls.SecurityRoleAssignment; import com.sun.enterprise.deployment.runtime.web.SunWebApp; import com.sun.enterprise.deployment.web.LoginConfiguration; -import com.sun.enterprise.security.PolicyLoader; +import com.sun.enterprise.security.ee.authorize.PolicyLoader; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityRoleMapperFactoryGen; import com.sun.enterprise.security.SecurityServicesUtil; @@ -80,7 +80,6 @@ import jakarta.servlet.http.HttpServletRequest; import org.glassfish.deployment.common.SecurityRoleMapperFactory; import org.glassfish.exousia.AuthorizationService; -import org.glassfish.exousia.mapping.DefaultPrincipalMapper; import org.glassfish.internal.api.ServerContext; import org.glassfish.security.common.Group; import org.glassfish.security.common.PrincipalImpl; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java index d3455e78ed6..96c34b3ef69 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java @@ -38,7 +38,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] /** * This package contains much of the implementation code for JACC. * @@ -59,7 +59,7 @@ * *

* The pluggable JACC components are loaded by a class in nucleus: - * {@link com.sun.enterprise.security.PolicyLoader} + * {@link com.sun.enterprise.security.ee.authorize.PolicyLoader} * */ package com.sun.enterprise.security.jacc; \ No newline at end of file diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java deleted file mode 100644 index c2f723f3b91..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic; - -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; -import static com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor.AUTH_RECIPIENT; -import static com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor.AUTH_SOURCE; -import static com.sun.enterprise.deployment.runtime.web.SunWebApp.HTTPSERVLET_SECURITY_PROVIDER; -import static com.sun.enterprise.security.common.AppservAccessController.doPrivileged; -import static com.sun.enterprise.security.jaspic.config.GFServerConfigProvider.SOAP; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.WEB_BUNDLE; -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_CONTENT; -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_RECIPIENT; -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_SENDER; - -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.MessagePolicy.TargetPolicy; - -import org.glassfish.internal.api.Globals; - -import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.enterprise.deployment.WebBundleDescriptor; -import com.sun.enterprise.deployment.WebServiceEndpoint; -import com.sun.enterprise.deployment.runtime.common.MessageDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; -import com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor; -import com.sun.enterprise.deployment.runtime.web.SunWebApp; - -/** - * Utility class for JASPIC appserver implementation. - */ -public class AuthMessagePolicy { - - private static final String SENDER = "sender"; - private static final String CONTENT = "content"; - private static final String BEFORE_CONTENT = "before-content"; - private static final String HANDLER_CLASS_PROPERTY = "security.jaspic.config.ConfigHelper.CallbackHandler"; - private static final String DEFAULT_HANDLER_CLASS = "com.sun.enterprise.security.jaspic.callback.ContainerCallbackHandler"; - - // for HttpServlet profile - private static final MessagePolicy MANDATORY_POLICY = getMessagePolicy(SENDER, null, true); - private static final MessagePolicy OPTIONAL_POLICY = getMessagePolicy(SENDER, null, false); - - private static String handlerClassName; - - private AuthMessagePolicy() { - } - - public static MessageSecurityBindingDescriptor getMessageSecurityBinding(String layer, Map properties) { - if (properties == null) { - return null; - } - - MessageSecurityBindingDescriptor messageSecurityBinding = null; - - WebServiceEndpoint webServiceEndpoint = (WebServiceEndpoint) properties.get("SERVICE_ENDPOINT"); - - if (webServiceEndpoint != null) { - messageSecurityBinding = webServiceEndpoint.getMessageSecurityBinding(); - } else { - ServiceReferenceDescriptor serviceReference = (ServiceReferenceDescriptor) properties.get("SERVICE_REF"); - if (serviceReference != null) { - WebServicesDelegate webServicesDelegate = Globals.get(WebServicesDelegate.class); - if (webServicesDelegate != null) { - messageSecurityBinding = webServicesDelegate.getBinding(serviceReference, properties); - } - } - } - - if (messageSecurityBinding != null) { - String bindingLayer = messageSecurityBinding.getAttributeValue(AUTH_LAYER); - if (bindingLayer == null || layer.equals(bindingLayer)) { - return messageSecurityBinding; - } - } - - return null; - } - - public static MessagePolicy getMessagePolicy(String authSource, String authRecipient) { - boolean sourceSender = SENDER.equals(authSource); - boolean sourceContent = CONTENT.equals(authSource); - boolean recipientAuth = authRecipient != null; - boolean mandatory = (sourceSender || sourceContent) || recipientAuth; - - return getMessagePolicy(authSource, authRecipient, mandatory); - } - - public static MessagePolicy getMessagePolicy(String authSource, String authRecipient, boolean mandatory) { - boolean sourceSender = SENDER.equals(authSource); - boolean sourceContent = CONTENT.equals(authSource); - boolean recipientAuth = authRecipient != null; - boolean beforeContent = BEFORE_CONTENT.equals(authRecipient); - - List targetPolicies = new ArrayList(); - - if (recipientAuth && beforeContent) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_RECIPIENT)); - - if (sourceSender) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_SENDER)); - } else if (sourceContent) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_CONTENT)); - } - } else { - if (sourceSender) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_SENDER)); - } else if (sourceContent) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_CONTENT)); - } - - if (recipientAuth) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_RECIPIENT)); - } - } - - return new MessagePolicy(targetPolicies.toArray(new TargetPolicy[targetPolicies.size()]), mandatory); - } - - public static MessagePolicy getMessagePolicy(ProtectionDescriptor protectionDescriptor) { - if (protectionDescriptor == null) { - return null; - } - - String source = protectionDescriptor.getAttributeValue(AUTH_SOURCE); - String recipient = protectionDescriptor.getAttributeValue(AUTH_RECIPIENT); - - return getMessagePolicy(source, recipient); - } - - public static String getProviderID(MessageSecurityBindingDescriptor binding) { - String providerID = null; - if (binding != null) { - String layer = binding.getAttributeValue(AUTH_LAYER); - if (SOAP.equals(layer)) { - providerID = binding.getAttributeValue(PROVIDER_ID); - } - } - - return providerID; - } - - public static MessagePolicy[] getSOAPPolicies(MessageSecurityBindingDescriptor binding, String operation, boolean onePolicy) { - - MessagePolicy requestPolicy = null; - MessagePolicy responsePolicy = null; - - if (binding != null) { - List messageSecurityDescriptors = null; - String layer = binding.getAttributeValue(AUTH_LAYER); - if (SOAP.equals(layer)) { - messageSecurityDescriptors = binding.getMessageSecurityDescriptors(); - } - - if (messageSecurityDescriptors != null) { - if (onePolicy) { - if (messageSecurityDescriptors.size() > 0) { - MessageSecurityDescriptor msd = messageSecurityDescriptors.get(0); - requestPolicy = getMessagePolicy(msd.getRequestProtectionDescriptor()); - responsePolicy = getMessagePolicy(msd.getResponseProtectionDescriptor()); - } - } else { // try to match - MessageSecurityDescriptor matchMsd = null; - for (int i = 0; i < messageSecurityDescriptors.size(); i++) { - MessageSecurityDescriptor msd = messageSecurityDescriptors.get(i); - List msgDescs = msd.getMessageDescriptors(); - for (int j = i + 1; j < msgDescs.size(); j++) { - // XXX don't know how to get JavaMethod from operation - MessageDescriptor msgDesc = (MessageDescriptor) msgDescs.get(j); - String opName = msgDesc.getOperationName(); - if ((opName == null && matchMsd == null)) { - matchMsd = msd; - } else if (opName != null && opName.equals(operation)) { - matchMsd = msd; - break; - } - } - - if (matchMsd != null) { - requestPolicy = getMessagePolicy(matchMsd.getRequestProtectionDescriptor()); - responsePolicy = getMessagePolicy(matchMsd.getResponseProtectionDescriptor()); - } - } - } - } - } - - return new MessagePolicy[] { requestPolicy, responsePolicy }; - } - - public static boolean oneSOAPPolicy(MessageSecurityBindingDescriptor binding) { - boolean onePolicy = true; - List messageSecurityDescriptor = null; - - if (binding != null) { - if (SOAP.equals(binding.getAttributeValue(AUTH_LAYER))) { - messageSecurityDescriptor = binding.getMessageSecurityDescriptors(); - } - } - - if (messageSecurityDescriptor == null) { - return true; - } - - for (int i = 0; i < messageSecurityDescriptor.size(); i++) { - - MessageSecurityDescriptor msd = messageSecurityDescriptor.get(i); - - // Determine if all the different messageSecurityDesriptors have the - // same policy which will help us interpret the effective policy if - // we cannot determine the opcode of a request at runtime. - - for (int j = 0; j < messageSecurityDescriptor.size(); j++) { - if (j != i && !policiesAreEqual(msd, messageSecurityDescriptor.get(j))) { - onePolicy = false; - } - } - } - - return onePolicy; - } - - public static SunWebApp getSunWebApp(Map properties) { - if (properties == null) { - return null; - } - - return ((WebBundleDescriptor) properties.get(WEB_BUNDLE)).getSunDescriptor(); - } - - public static String getProviderID(SunWebApp sunWebApp) { - String providerID = null; - if (sunWebApp != null) { - providerID = sunWebApp.getAttributeValue(HTTPSERVLET_SECURITY_PROVIDER); - } - - return providerID; - } - - public static MessagePolicy[] getHttpServletPolicies(String authContextID) { - if (Boolean.valueOf(authContextID)) { - return new MessagePolicy[] { MANDATORY_POLICY, null }; - } - - return new MessagePolicy[] { OPTIONAL_POLICY, null }; - } - - public static CallbackHandler getDefaultCallbackHandler() { - // Get the default handler class - try { - return (CallbackHandler) doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (handlerClassName == null) { - handlerClassName = System.getProperty(HANDLER_CLASS_PROPERTY, DEFAULT_HANDLER_CLASS); - } - - return Class.forName(handlerClassName, true, loader) - .newInstance(); - } - }); - - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); - } - } - - private static boolean policiesAreEqual(MessageSecurityDescriptor reference, MessageSecurityDescriptor other) { - return (protectionDescriptorsAreEqual(reference.getRequestProtectionDescriptor(), other.getRequestProtectionDescriptor()) - && protectionDescriptorsAreEqual(reference.getResponseProtectionDescriptor(), other.getResponseProtectionDescriptor())); - } - - private static boolean protectionDescriptorsAreEqual(ProtectionDescriptor pd1, ProtectionDescriptor pd2) { - String authSource1 = pd1.getAttributeValue(AUTH_SOURCE); - String authRecipient1 = pd1.getAttributeValue(AUTH_RECIPIENT); - - String authSource2 = pd2.getAttributeValue(AUTH_SOURCE); - String authRecipient2 = pd2.getAttributeValue(AUTH_RECIPIENT); - - boolean sameAuthSource = (authSource1 == null && authSource2 == null) || (authSource1 != null && authSource1.equals(authSource2)); - boolean sameAuthRecipient = (authRecipient1 == null && authRecipient2 == null) - || (authRecipient1 != null && authRecipient1.equals(authRecipient2)); - - return sameAuthSource && sameAuthRecipient; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java index 369753c1155..c74d027dec1 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java @@ -37,12 +37,13 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation] +// Portions Copyright [2016-2024] [Payara Foundation] package com.sun.enterprise.security.jaspic; import static com.sun.logging.LogDomains.SECURITY_LOGGER; +import jakarta.security.auth.message.config.AuthConfigFactory; import java.beans.PropertyChangeEvent; import java.util.logging.Logger; @@ -62,7 +63,6 @@ import com.sun.enterprise.config.serverbeans.MessageSecurityConfig; import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; import com.sun.logging.LogDomains; /** @@ -80,59 +80,7 @@ public class MessageSecurityConfigEventListenerImpl implements ConfigListener { @Inject @Named(ServerEnvironment.DEFAULT_INSTANCE_NAME) private SecurityService service; - - /** - * @param event - Event to be processed. - * @throws AdminEventListenerException when the listener is unable to process the event. - */ - public NotProcessed handleUpdate(T instance) { - NotProcessed notProcessed = null; - logger.fine("MessageSecurityConfigEventListenerImpl - handleUpdate called"); - - // Handle only the MessageSecurityConfig. - if (instance instanceof MessageSecurityConfig) { - GFServerConfigProvider.loadConfigContext(service); - } else { - notProcessed = new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); - } - - return notProcessed; - } - - /** - * @param event Event to be processed. - * @throws AdminEventListenerException when the listener is unable to process the event. - */ - public NotProcessed handleDelete(T instance) { - NotProcessed notProcessed = null; - logger.fine("MessageSecurityConfigEventListenerImpl - handleDelete called"); - - if (instance instanceof MessageSecurityConfig) { - GFServerConfigProvider.loadConfigContext(service); - } else { - notProcessed = new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); - } - - return notProcessed; - } - - /** - * @param event Event to be processed. - * @throws AdminEventListenerException when the listener is unable to process the event. - */ - public NotProcessed handleCreate(T instance) { - NotProcessed notProcessed = null; - logger.fine("MessageSecurityConfigEventListenerImpl - handleCreate called"); - - if (instance instanceof MessageSecurityConfig) { - GFServerConfigProvider.loadConfigContext(service); - } else { - notProcessed = new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); - } - - return notProcessed; - } - + @Override public UnprocessedChangeEvents changed(PropertyChangeEvent[] events) { ConfigSupport.sortAndDispatch(events, new Changed() { @@ -151,15 +99,15 @@ public NotProcessed changed(TYPE type, Class chan switch (type) { case ADD: logger.fine("A new " + changedType.getName() + " was added : " + " " + changedInstance); - notProcessed = handleCreate(changedInstance); + notProcessed = handle(changedInstance); break; case CHANGE: logger.fine("A " + changedType.getName() + " was changed : " + changedInstance); - notProcessed = handleUpdate(changedInstance); + notProcessed = handle(changedInstance); break; case REMOVE: logger.fine("A " + changedType.getName() + " was removed : " + changedInstance); - notProcessed = handleDelete(changedInstance); + notProcessed = handle(changedInstance); break; } @@ -169,4 +117,16 @@ public NotProcessed changed(TYPE type, Class chan return null; } + + private NotProcessed handle(T instance) { + if (instance instanceof MessageSecurityConfig) { + AuthConfigFactory factory = AuthConfigFactory.getFactory(); + if (factory != null) { + factory.refresh(); + } + return null; + } + + return new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); + } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java deleted file mode 100644 index dd0c2a12440..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import java.io.IOException; -import java.util.Map; -import java.util.Set; - - -/** - * AuthConfigImpl relies on a ConfigParser to read - * the module configuration. - * - *

The ConfigParser is expected to parse that information - * into the HashMap described below. - * - * @version %I%, %G% - */ -public interface ConfigParser { - - /** - * Initialize the parser. - * Passing null as argument means the parser is to find - * configuration object as necessary. - */ - public void initialize(Object config) throws IOException; - - /** - * Get the module configuration information. - * The information is returned as a HashMap. - * - *

The key is an intercept: - *

    - *
  • SOAP - *
  • HttpServlet - *
- * - *

The value is a AuthConfigImpl.InterceptEntry, which contains: - *

    - *
  • default provider ID - *
  • default type (client or server) - *
  • HashMap, where - * key = provider ID - * value = BaseAuthConfigImpl.IDEntry - *
- * - *

An IDEntry contains: - *

    - *
  • type (client or server) - *
  • moduleClassName - *
  • default requestPolicy - *
  • default responsePolicy - *
  • options - *
  • - *
- */ - public Map getConfigMap(); - - /** - * Get the name of layers with default set in domain.xml. - */ - public Set getLayersWithDefault(); -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java deleted file mode 100644 index 23cdb90706f..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import static java.util.Arrays.asList; - -import java.util.List; - -import com.sun.enterprise.security.SecurityServicesUtil; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; -import com.sun.jaspic.config.factory.BaseAuthConfigFactory; -import com.sun.jaspic.config.factory.EntryInfo; -import com.sun.jaspic.config.factory.RegStoreFileParser; - -/** - * This class implements methods in the abstract class AuthConfigFactory. - * - * @author Shing Wai Chan - */ -public class GFAuthConfigFactory extends BaseAuthConfigFactory { - - // MUST "hide" regStore in derived class. - private static RegStoreFileParser regStore; - - /** - * To specialize the defaultEntries passed to the RegStoreFileParser constructor, create another subclass of - * BaseAuthconfigFactory, that is basically a copy of this class, with a change to the third argument of the call to new - * ResSToreFileParser. to ensure runtime use of the the associated regStore, make sure that the new subclass also - * contains an implementation of the getRegStore method. - * - *

- * As done within this class, use the locks defined in - * BaseAuthConfigFactory to serialize access to the regStore (both within the class constructor, and within getRegStore) - * - *

- * All EntyInfo OBJECTS PASSED as defaultEntries MUST HAVE BEEN CONSTRUCTED USING THE FOLLOWING CONSTRUCTOR: - * - * EntryInfo(String className, Map properties); - * - */ - public GFAuthConfigFactory() { - if (doReadLocked(() -> regStore != null)) { - return; - } - - String userDir = System.getProperty("user.dir"); - - doWriteLocked(() -> { - if (regStore == null) { - initializeRegStore(userDir); - _loadFactory(); - } - }); - } - - /** - * @param userDir - */ - private static void initializeRegStore(String userDir) { - regStore = new RegStoreFileParser(userDir, CONF_FILE_NAME, getDefaultProviders()); - } - - @Override - protected RegStoreFileParser getRegStore() { - return doReadLocked(() -> regStore); - } - - /** - * Contains the default providers used when none are configured in a factory configuration file. - */ - private static List getDefaultProviders() { - WebServicesDelegate delegate = null; - SecurityServicesUtil securityServicesUtil = SecurityServicesUtil.getInstance(); - - if (securityServicesUtil != null) { - delegate = securityServicesUtil.getHabitat().getService(WebServicesDelegate.class); - } - - if (delegate != null) { - return asList( - new EntryInfo(delegate.getDefaultWebServicesProvider()), - new EntryInfo(GFServerConfigProvider.class.getName())); - } - - return asList(new EntryInfo(GFServerConfigProvider.class.getName())); - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java deleted file mode 100644 index 465f2d874c7..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java +++ /dev/null @@ -1,981 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getHttpServletPolicies; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getMessageSecurityBinding; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getProviderID; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getSOAPPolicies; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getSunWebApp; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.oneSOAPPolicy; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.IS_MANDATORY; -import static java.security.AccessController.doPrivileged; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; - -import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.logging.Logger; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -// jsr 196 interface types -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.config.AuthConfig; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ClientAuthModule; -import jakarta.security.auth.message.module.ServerAuthModule; - -import org.glassfish.internal.api.Globals; - -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.web.SunWebApp; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; -import com.sun.logging.LogDomains; - -/** - * This class implements the interface AuthConfigProvider. - * - * @author Shing Wai Chan - * @author Ronald Monzillo - */ -public class GFServerConfigProvider implements AuthConfigProvider { - - private static final Logger logger = LogDomains.getLogger(GFServerConfigProvider.class, LogDomains.SECURITY_LOGGER); - - public static final String SOAP = "SOAP"; - public static final String HTTPSERVLET = "HttpServlet"; - - protected static final String CLIENT = "client"; - protected static final String SERVER = "server"; - protected static final String MANAGES_SESSIONS_OPTION = "managessessions"; - - private static final String DEFAULT_PARSER_CLASS = "com.sun.enterprise.security.jaspic.config.ConfigDomainParser"; - - // since old api does not have subject in PasswordValdiationCallback, - // this is for old modules to pass group info back to subject - private static final ThreadLocal subjectLocal = new ThreadLocal(); - - protected static final ReadWriteLock rwLock = new ReentrantReadWriteLock(); - protected static final Map layerDefaultRegisIDMap = new HashMap(); - - // Mutable statics should be kept package private to eliminate - // the ability for subclasses to access them - static int epoch; - static String parserClassName; - static ConfigParser parser; - static boolean parserInitialized; - static AuthConfigFactory slaveFactory; - - // keep the slave from being visible outside - static AuthConfigProvider slaveProvider; - - protected AuthConfigFactory factory; - private WebServicesDelegate wsdelegate; - - public GFServerConfigProvider(Map properties, AuthConfigFactory factory) { - this.factory = factory; - initializeParser(); - - if (factory != null) { - boolean hasSlaveFactory = false; - try { - rwLock.readLock().lock(); - hasSlaveFactory = (slaveFactory != null); - } finally { - rwLock.readLock().unlock(); - } - - if (!hasSlaveFactory) { - try { - rwLock.writeLock().lock(); - if (slaveFactory == null) { - slaveFactory = factory; - } - } finally { - rwLock.writeLock().unlock(); - } - } - } - - boolean hasSlaveProvider = false; - try { - rwLock.readLock().lock(); - hasSlaveProvider = slaveProvider != null; - } finally { - rwLock.readLock().unlock(); - } - - if (!hasSlaveProvider) { - try { - rwLock.writeLock().lock(); - if (slaveProvider == null) { - slaveProvider = this; - } - } finally { - rwLock.writeLock().unlock(); - } - } - wsdelegate = Globals.get(WebServicesDelegate.class); - } - - private void initializeParser() { - try { - rwLock.readLock().lock(); - if (parserInitialized) { - return; - } - } finally { - rwLock.readLock().unlock(); - } - - try { - rwLock.writeLock().lock(); - if (!parserInitialized) { - parserClassName = System.getProperty("config.parser", DEFAULT_PARSER_CLASS); - loadParser(this, factory, null); - parserInitialized = true; - } - } finally { - rwLock.writeLock().unlock(); - } - } - - /** - * Instantiate and initialize module class - */ - static ModuleInfo createModuleInfo(Entry entry, CallbackHandler handler, String type, Map properties) throws AuthException { - try { - // Instantiate module using no-arg constructor - Object newModule = entry.newInstance(); - - Map map = properties; - Map entryOptions = entry.getOptions(); - - if (entryOptions != null) { - if (map == null) { - map = new HashMap<>(); - } else { - map = new HashMap<>(map); - } - map.putAll(entryOptions); - } - - // Initialize Module - if (SERVER.equals(type)) { - ServerAuthModule sam = (ServerAuthModule) newModule; - sam.initialize(entry.getRequestPolicy(), entry.getResponsePolicy(), handler, map); - } else { // CLIENT - ClientAuthModule cam = (ClientAuthModule) newModule; - cam.initialize(entry.getRequestPolicy(), entry.getResponsePolicy(), handler, map); - } - - return new ModuleInfo(newModule, map); - } catch (Exception e) { - if (e instanceof AuthException) { - throw (AuthException) e; - } - - throw (AuthException) new AuthException().initCause(e); - } - } - - /** - * Create an object of a given class. - * - * @param className - * - */ - private static Object createObject(String className) { - ClassLoader loader = getClassLoader(); - - if (System.getSecurityManager() != null) { - try { - return doPrivileged((PrivilegedExceptionAction) - () -> Class.forName(className, true, loader).newInstance()); - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); - } - } - - try { - return Class.forName(className, true, loader).newInstance(); - } catch (Throwable t) { - throw new RuntimeException(t); - } - } - - Entry getEntry(String intercept, String id, MessagePolicy requestPolicy, MessagePolicy responsePolicy, String type) { - - // get the parsed module config and DD information - - Map configMap; - - try { - rwLock.readLock().lock(); - configMap = parser.getConfigMap(); - } finally { - rwLock.readLock().unlock(); - } - - if (configMap == null) { - return null; - } - - // get the module config info for this intercept - - InterceptEntry intEntry = configMap.get(intercept); - if (intEntry == null || intEntry.idMap == null) { - if (logger.isLoggable(FINE)) { - logger.fine("module config has no IDs configured for [" + intercept + "]"); - } - - return null; - } - - // look up the DD's provider ID in the module config - - IDEntry idEntry = null; - if (id == null || (idEntry = (IDEntry) intEntry.idMap.get(id)) == null) { - - // either the DD did not specify a provider ID, - // or the DD-specified provider ID was not found - // in the module config. - // - // in either case, look for a default ID in the module config - - if (logger.isLoggable(FINE)) { - logger.fine("DD did not specify ID, " + "or DD-specified ID for [" + intercept + "] not found in config -- " - + "attempting to look for default ID"); - } - - String defaultID; - if (CLIENT.equals(type)) { - defaultID = intEntry.defaultClientID; - } else { - defaultID = intEntry.defaultServerID; - } - - idEntry = (IDEntry) intEntry.idMap.get(defaultID); - if (idEntry == null) { - - // did not find a default provider ID - - if (logger.isLoggable(FINE)) { - logger.fine("no default config ID for [" + intercept + "]"); - } - - return null; - } - } - - // We found the DD provider ID in the module config - // or we found a default module config - - // check provider-type - if (idEntry.type.indexOf(type) < 0) { - if (logger.isLoggable(FINE)) { - logger.fine("request type [" + type + "] does not match config type [" + idEntry.type + "]"); - } - - return null; - } - - // check whether a policy is set - MessagePolicy reqP = requestPolicy != null || responsePolicy != null ? requestPolicy : idEntry.requestPolicy; // default; - - MessagePolicy respP = requestPolicy != null || responsePolicy != null ? responsePolicy : idEntry.responsePolicy; // default; - - // optimization: if policy was not set, return null - if (reqP == null && respP == null) { - if (logger.isLoggable(FINE)) { - logger.fine("no policy applies"); - } - return null; - } - - // return the configured modules with the correct policies - - Entry entry = new Entry(idEntry.moduleClassName, reqP, respP, idEntry.options); - - if (logger.isLoggable(FINE)) { - logger.fine("getEntry for: " + intercept + " -- " + id + "\n module class: " + entry.moduleClassName + "\n options: " - + entry.options + "\n request policy: " + entry.requestPolicy + "\n response policy: " + entry.responsePolicy); - } - - return entry; - } - - /** - * Class representing a single AuthModule entry configured for an ID, interception point, and stack. - * - *

- * This class also provides a way for a caller to obtain an instance of the module listed in the entry by invoking the - * newInstance method. - */ - static class Entry { - - // For loading modules - private static final Class[] PARAMS = {}; - private static final Object[] ARGS = {}; - - private String moduleClassName; - private MessagePolicy requestPolicy; - private MessagePolicy responsePolicy; - private Map options; - - /** - * Construct a ConfigFile entry. - * - *

- * An entry encapsulates a single module and its related information. - * - * @param moduleClassName - * the module class name - * @param requestPolicy - * the request policy assigned to the module listed in this entry, which may be null. - * - * @param responsePolicy - * the response policy assigned to the module listed in this entry, which may be null. - * - * @param options - * the options configured for this module. - */ - Entry(String moduleClassName, MessagePolicy requestPolicy, MessagePolicy responsePolicy, Map options) { - this.moduleClassName = moduleClassName; - this.requestPolicy = requestPolicy; - this.responsePolicy = responsePolicy; - this.options = options; - } - - /** - * Return the request policy assigned to this module. - * - * @return the policy, which may be null. - */ - MessagePolicy getRequestPolicy() { - return requestPolicy; - } - - /** - * Return the response policy assigned to this module. - * - * @return the policy, which may be null. - */ - MessagePolicy getResponsePolicy() { - return responsePolicy; - } - - String getModuleClassName() { - return moduleClassName; - } - - Map getOptions() { - return options; - } - - /** - * Return a new instance of the module contained in this entry. - * - *

- * The default implementation of this method attempts to invoke the default no-args constructor of the module class. - * This method may be overridden if a different constructor should be invoked. - * - * @return a new instance of the module contained in this entry. - * - * @exception AuthException - * if the instantiation failed. - */ - Object newInstance() throws AuthException { - try { - return Class.forName(moduleClassName, true, getClassLoader()) - .getConstructor(PARAMS) - .newInstance(ARGS); - } catch (Exception e) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.provider_unable_to_load_authmodule", new String[] { moduleClassName, e.toString() }); - } - - AuthException ae = new AuthException(); - ae.initCause(e); - throw ae; - } - } - } - - public static class InterceptEntry { - String defaultClientID; - String defaultServerID; - Map idMap; - - public InterceptEntry(String defaultClientID, String defaultServerID, Map idMap) { - this.defaultClientID = defaultClientID; - this.defaultServerID = defaultServerID; - this.idMap = idMap; - } - - public Map getIdMap() { - return idMap; - } - - public void setIdMap(Map map) { - idMap = map; - } - - public String getDefaultClientID() { - return defaultClientID; - } - - public String getDefaultServerID() { - return defaultServerID; - } - } - - /** - * Get an instance of ClientAuthConfig from this provider. - * - *

- * The implementation of this method returns a ClientAuthConfig instance that describes the configuration of - * ClientAuthModules at a given message layer, and for use in an identified application context. - * - * @param layer - * a String identifying the message layer for the returned ClientAuthConfig object. This argument must not be - * null. - * - * @param appContext - * a String that identifies the messaging context for the returned ClientAuthConfig object. This argument - * must not be null. - * - * @param handler - * a CallbackHandler to be passed to the ClientAuthModules encapsulated by ClientAuthContext objects derived - * from the returned ClientAuthConfig. This argument may be null, in which case the implementation may assign - * a default handler to the configuration. - * - * @return a ClientAuthConfig Object that describes the configuration of ClientAuthModules at the message layer and - * messaging context identified by the layer and appContext arguments. This method does not return null. - * - * @exception AuthException - * if this provider does not support the assignment of a default CallbackHandler to the returned - * ClientAuthConfig. - * - * @exception SecurityException - * if the caller does not have permission to retrieve the configuration. - * - * The CallbackHandler assigned to the configuration must support the Callback objects required to be - * supported by the profile of this specification being followed by the messaging runtime. The - * CallbackHandler instance must be initialized with any application context needed to process the - * required callbacks on behalf of the corresponding application. - */ - public ClientAuthConfig getClientAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException { - return new GFClientAuthConfig(this, layer, appContext, handler); - } - - /** - * Get an instance of ServerAuthConfig from this provider. - * - *

- * The implementation of this method returns a ServerAuthConfig instance that describes the configuration of - * ServerAuthModules at a given message layer, and for a particular application context. - * - * @param layer - * a String identifying the message layer for the returned ServerAuthConfig object. This argument must not be - * null. - * - * @param appContext - * a String that identifies the messaging context for the returned ServerAuthConfig object. This argument - * must not be null. - * - * @param handler - * a CallbackHandler to be passed to the ServerAuthModules encapsulated by ServerAuthContext objects derived - * from thr returned ServerAuthConfig. This argument may be null, in which case the implementation may assign - * a default handler to the configuration. - * - * @return a ServerAuthConfig Object that describes the configuration of ServerAuthModules at a given message layer, and - * for a particular application context. This method does not return null. - * - * @exception AuthException - * if this provider does not support the assignment of a default CallbackHandler to the returned - * ServerAuthConfig. - * - * @exception SecurityException - * if the caller does not have permission to retrieve the configuration. - *

- * The CallbackHandler assigned to the configuration must support the Callback objects required to be - * supported by the profile of this specification being followed by the messaging runtime. The - * CallbackHandler instance must be initialized with any application context needed to process the - * required callbacks on behalf of the corresponding application. - */ - public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException { - return new GFServerAuthConfig(this, layer, appContext, handler); - } - - /** - * Causes a dynamic configuration provider to update its internal state such that any resulting change to its state is - * reflected in the corresponding authentication context configuration objects previously created by the provider within - * the current process context. - * - * @exception AuthException - * if an error occured during the refresh. - * - * @exception SecurityException - * if the caller does not have permission to refresh the provider. - */ - - public void refresh() { - loadParser(this, factory, null); - } - - /** - * this method is intended to be called by the admin configuration system when the corresponding config object has - * changed. It relies on the slaves, since it is a static method. - * - * @param config - * a config object of type understood by the parser. NOTE: there appears to be a thread saftey problem, and - * this method will fail if a slaveProvider has not been established prior to its call. - */ - public static void loadConfigContext(Object config) { - - boolean hasSlaveFactory = false; - rwLock.readLock().lock(); - try { - hasSlaveFactory = (slaveFactory != null); - } finally { - rwLock.readLock().unlock(); - } - - if (slaveProvider == null) { - if (logger.isLoggable(SEVERE)) { - logger.severe("unableToLoad.noSlaveProvider"); - } - return; - } - - if (!hasSlaveFactory) { - rwLock.writeLock().lock(); - try { - if (slaveFactory == null) { - slaveFactory = AuthConfigFactory.getFactory(); - } - } finally { - rwLock.writeLock().unlock(); - } - } - - loadParser(slaveProvider, slaveFactory, config); - } - - protected static void loadParser(AuthConfigProvider aProvider, AuthConfigFactory aFactory, Object config) { - rwLock.writeLock().lock(); - try { - ConfigParser nextParser; - int next = epoch + 1; - nextParser = (ConfigParser) createObject(parserClassName); - nextParser.initialize(config); - - if (aFactory != null && aProvider != null) { - Set layerSet = nextParser.getLayersWithDefault(); - for (String layer : layerDefaultRegisIDMap.keySet()) { - if (!layerSet.contains(layer)) { - String regisID = layerDefaultRegisIDMap.remove(layer); - aFactory.removeRegistration(regisID); - } - } - - for (String layer : layerSet) { - if (!layerDefaultRegisIDMap.containsKey(layer)) { - String regisID = aFactory.registerConfigProvider(aProvider, layer, null, - "GFServerConfigProvider: self registration"); - layerDefaultRegisIDMap.put(layer, regisID); - } - } - } - epoch = (next == 0 ? 1 : next); - parser = nextParser; - } catch (IOException ex) { - throw new RuntimeException(ex); - } finally { - rwLock.writeLock().unlock(); - } - } - - protected static ClassLoader getClassLoader() { - if (System.getSecurityManager() == null) { - return Thread.currentThread().getContextClassLoader(); - } - - return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - return Thread.currentThread().getContextClassLoader(); - } - }); - } - - // for old API - public static void setValidateRequestSubject(Subject subject) { - subjectLocal.set(subject); - } - - class GFAuthConfig implements AuthConfig { - - protected AuthConfigProvider provider; - protected String layer; - protected String appContext; - protected CallbackHandler handler; - protected String type; - protected String providerID; - protected boolean init; - protected boolean onePolicy; - protected MessageSecurityBindingDescriptor binding; - protected SunWebApp sunWebApp; - - protected GFAuthConfig(AuthConfigProvider provider, String layer, String appContext, CallbackHandler handler, String type) { - this.provider = provider; - this.layer = layer; - this.appContext = appContext; - this.handler = handler != null ? handler : AuthMessagePolicy.getDefaultCallbackHandler(); - this.type = type; - } - - /** - * Get the message layer name of this authentication context configuration object. - * - * @return the message layer name of this configuration object, or null if the configuration object pertains to an - * unspecified message layer. - */ - public String getMessageLayer() { - return layer; - } - - /** - * Get the application context identifier of this authentication context configuration object. - * - * @return the String identifying the application context of this configuration object or null if the configuration - * object pertains to an unspecified application context. - */ - public String getAppContext() { - return appContext; - } - - /** - * Get the authentication context identifier corresponding to the request and response objects encapsulated in - * messageInfo. - * - * See method AuthMessagePolicy. getHttpServletPolicies() for more details on why this method returns the String's - * "true" or "false" for AuthContextID. - * - * @param messageInfo - * a contextual Object that encapsulates the client request and server response objects. - * - * @return the authentication context identifier corresponding to the encapsulated request and response objects, or - * null. - * - * - * @throws IllegalArgumentException - * if the type of the message objects incorporated in messageInfo are not compatible with the message types - * supported by this authentication context configuration object. - */ - public String getAuthContextID(MessageInfo messageInfo) { - if (HTTPSERVLET.equals(layer)) { - return Boolean.valueOf((String) messageInfo.getMap().get(IS_MANDATORY)).toString(); - } - - if (SOAP.equals(layer) && wsdelegate != null) { - return wsdelegate.getAuthContextID(messageInfo); - } - - return null; - } - - // we should be able to replace the following with a method on packet - - /** - * Causes a dynamic anthentication context configuration object to update the internal state that it uses to process - * calls to its getAuthContext method. - * - * @exception AuthException - * if an error occured during the update. - * - * @exception SecurityException - * if the caller does not have permission to refresh the configuration object. - */ - public void refresh() { - loadParser(provider, factory, null); - } - - /** - * Used to determine whether or not the getAuthContext method of the authentication context configuration - * will return null for all possible values of authentication context identifier. - * - * @return false when getAuthContext will return null for all possible values of authentication context - * identifier. Otherwise, this method returns true. - */ - public boolean isProtected() { - // XXX TBD - return true; - } - - - CallbackHandler getCallbackHandler() { - return handler; - } - - protected ModuleInfo getModuleInfo(String authContextID, Map properties) throws AuthException { - if (!init) { - initialize(properties); - } - - MessagePolicy[] policies = null; - - if (HTTPSERVLET.equals(layer)) { - policies = getHttpServletPolicies(authContextID); - } else { - policies = getSOAPPolicies(binding, authContextID, onePolicy); - } - - MessagePolicy requestPolicy = policies[0]; - MessagePolicy responsePolicy = policies[1]; - - Entry entry = getEntry(layer, providerID, requestPolicy, responsePolicy, type); - - return entry != null ? createModuleInfo(entry, handler, type, properties) : null; - } - - // Lazy initialize this as SunWebApp is not available in RealmAdapter creation - private void initialize(Map properties) { - if (!init) { - if (HTTPSERVLET.equals(layer)) { - sunWebApp = getSunWebApp(properties); - providerID = getProviderID(sunWebApp); - onePolicy = true; - } else { - binding = getMessageSecurityBinding(layer, properties); - providerID = getProviderID(binding); - onePolicy = oneSOAPPolicy(binding); - } - - // HandlerContext need to be explicitly set by caller - init = true; - } - } - } - - class GFServerAuthConfig extends GFAuthConfig implements ServerAuthConfig { - - protected GFServerAuthConfig(AuthConfigProvider provider, String layer, String appContext, CallbackHandler handler) { - super(provider, layer, appContext, handler, SERVER); - } - - public ServerAuthContext getAuthContext(String authContextID, Subject serviceSubject, @SuppressWarnings("rawtypes") Map properties) throws AuthException { - @SuppressWarnings("unchecked") - ModuleInfo moduleInfo = getModuleInfo(authContextID, (Map) properties); - - if (moduleInfo != null && moduleInfo.getModule() != null) { - return new GFServerAuthContext(moduleInfo.getModule()); - } - - return null; - } - } - - class GFClientAuthConfig extends GFAuthConfig implements ClientAuthConfig { - - protected GFClientAuthConfig(AuthConfigProvider provider, String layer, String appContext, CallbackHandler handler) { - super(provider, layer, appContext, handler, CLIENT); - } - - public ClientAuthContext getAuthContext(String authContextID, Subject clientSubject, @SuppressWarnings("rawtypes") Map properties) throws AuthException { - @SuppressWarnings("unchecked") - ModuleInfo moduleInfo = getModuleInfo(authContextID, (Map) properties); - - if (moduleInfo != null && moduleInfo.getModule() != null) { - return new GFClientAuthContext(moduleInfo.getModule()); - } - - return null; - } - } - - static protected class GFServerAuthContext implements ServerAuthContext { - - private final ServerAuthModule module; - - GFServerAuthContext(ServerAuthModule module) { - this.module = module; - } - - public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.validateRequest(messageInfo, clientSubject, serviceSubject); - } - - public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.secureResponse(messageInfo, serviceSubject); - } - - public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - module.cleanSubject(messageInfo, subject); - } - } - - static protected class GFClientAuthContext implements ClientAuthContext { - - private final ClientAuthModule module; - - GFClientAuthContext(ClientAuthModule module) { - this.module = module; - } - - public AuthStatus secureRequest(MessageInfo messageInfo, Subject clientSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.secureRequest(messageInfo, clientSubject); - } - - public AuthStatus validateResponse(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.validateResponse(messageInfo, clientSubject, serviceSubject); - } - - public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - module.cleanSubject(messageInfo, subject); - } - } - - /** - * parsed ID entry - */ - public static class IDEntry { - private String type; // provider type (client, server, client-server) - private String moduleClassName; - private MessagePolicy requestPolicy; - private MessagePolicy responsePolicy; - private Map options; - - public IDEntry(String type, String moduleClassName, MessagePolicy requestPolicy, MessagePolicy responsePolicy, Map options) { - this.type = type; - this.moduleClassName = moduleClassName; - this.requestPolicy = requestPolicy; - this.responsePolicy = responsePolicy; - this.options = options; - } - - public String getModuleClassName() { - return moduleClassName; - } - - public Map getOptions() { - return options; - } - - public MessagePolicy getRequestPolicy() { - return requestPolicy; - } - - public MessagePolicy getResponsePolicy() { - return responsePolicy; - } - - public String getType() { - return type; - } - } - - /** - * A data object contains module object and the corresponding map. - */ - protected static class ModuleInfo { - - private final Object module; - private final Map map; - - ModuleInfo(Object module, Map map) { - this.module = module; - this.map = map; - } - - @SuppressWarnings("unchecked") - T getModule() { - return (T) module; - } - - Map getMap() { - return map; - } - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java similarity index 91% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServices.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java index 4386c028fcd..dd401546776 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServices.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java @@ -37,20 +37,20 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jaspic.config; import java.util.Map; import javax.security.auth.callback.CallbackHandler; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; -import com.sun.jaspic.services.JaspicServices; +import org.glassfish.epicyro.config.helper.AuthMessagePolicy; +import org.glassfish.epicyro.services.BaseAuthenticationService; /** * This is based Helper class for 196 Configuration. */ -public abstract class PayaraJaspicServices extends JaspicServices { +public abstract class PayaraEpicyroServices extends BaseAuthenticationService { /** * Get the default callback handler diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServletServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java similarity index 86% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServletServices.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java index 8b4d5054cf5..ba6a29e30b4 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServletServices.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java @@ -37,11 +37,11 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jaspic.config; import static com.sun.enterprise.deployment.web.LoginConfiguration.CLIENT_CERTIFICATION_AUTHENTICATION; -import static com.sun.enterprise.security.jaspic.config.GFServerConfigProvider.HTTPSERVLET; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.POLICY_CONTEXT; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.WEB_BUNDLE; @@ -58,15 +58,18 @@ import com.sun.enterprise.deployment.web.LoginConfiguration; import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; import com.sun.enterprise.security.jacc.JaccWebAuthorizationManager; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; -public class PayaraJaspicServletServices extends PayaraJaspicServices { +public class PayaraEpicyroServletServices extends PayaraEpicyroServices { public static final String AUTH_TYPE = "jakarta.servlet.http.authType"; + + public static final String HTTPSERVLET = "HttpServlet"; private String realmName; - public PayaraJaspicServletServices(String appContext, Map map, CallbackHandler callbackHandler, String realmName, boolean isSystemApp, String defaultSystemProviderID) { + public PayaraEpicyroServletServices(String appContext, Map map, CallbackHandler callbackHandler, String realmName, boolean isSystemApp, String defaultSystemProviderID) { WebBundleDescriptor webBundle = null; @@ -84,7 +87,7 @@ public PayaraJaspicServletServices(String appContext, Map map, C } // Set realmName before init - init(HTTPSERVLET, appContext, map, callbackHandler, Globals.get(WebServicesDelegate.class)); + init(HTTPSERVLET, appContext, map, callbackHandler, (RegistrationWrapperRemover) Globals.get(WebServicesDelegate.class)); if (webBundle != null) { String policyContextId = JaccWebAuthorizationManager.getContextID(webBundle); @@ -106,7 +109,7 @@ public PayaraJaspicServletServices(String appContext, Map map, C // Register the Payara JASPIC provider - String jaspicRegistrationId = factory.registerConfigProvider( + String jaspicRegistrationId = authConfigFactory.registerConfigProvider( configProvider, HTTPSERVLET, appContext, "Payara provider: " + HTTPSERVLET + ":" + appContext); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java deleted file mode 100644 index 0c6e6642cbb..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java +++ /dev/null @@ -1,619 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import java.io.*; -import java.util.*; - -import java.lang.reflect.Method; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.AppConfigurationEntry; - -import com.sun.enterprise.security.jaspic.config.ConfigParser; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; -import com.sun.logging.LogDomains; - -/** - * This is a default file-based AuthConfig implementation. - * - * @version %I%, %G% - */ -class ConfigFile extends AuthConfig { - - // indicates the age of the configuration approximately in - // terms of the number of times refresh has been called - private int epoch; - - // parser class name - private String parserClassName; - - // parser - private ConfigParser parser; - - // package private for ConfigFileParser - static final String CLIENT = "client"; - static final String SERVER = "server"; - - private static final String DEFAULT_HANDLER_CLASS = "com.sun.enterprise.security.jaspic.callback.ContainerCallbackHandler"; - - private static final String DEFAULT_PARSER_CLASS = "com.sun.enterprise.security.jaspic.config.ConfigDomainParser"; - - private static final Logger logger = LogDomains.getLogger(ConfigFile.class, LogDomains.SECURITY_LOGGER); - - ConfigFile() throws IOException { - String propertyValue = System.getProperty("config.parser"); - if (propertyValue == null) { - parserClassName = DEFAULT_PARSER_CLASS; - } else { - parserClassName = propertyValue; - } - this.epoch = 1; - parser = ConfigFile.loadParser(parserClassName); - parser.initialize(null); - } - - /** - * Get a default ClientAuthContext. - * - * @return an instance of ConfigClient. - */ - @Override - public ClientAuthContext getClientAuthContext(String intercept, String id, AuthPolicy requestPolicy, AuthPolicy responsePolicy, - CallbackHandler handler) throws AuthException { - - ConfigFile.Entry[] entries = getEntries(intercept, id, requestPolicy, responsePolicy, CLIENT); - if (entries == null || entries.length == 0) { - return null; - } - - // instantiate and initialize modules up front as well - - if (handler == null) { - handler = ConfigFile.loadDefaultCallbackHandler(); - } else if (handler instanceof DependentCallbackHandler) { - handler = new DelegatingHandler(handler); - } - - for (int i = 0; i < entries.length; i++) { - entries[i].module = ConfigFile.createModule(entries[i], handler); - } - - return new ConfigClient(entries); - } - - /** - * Get a default ServerAuthContext. - * - * @return an instance of ConfigServer. - */ - @Override - public ServerAuthContext getServerAuthContext(String intercept, String id, AuthPolicy requestPolicy, AuthPolicy responsePolicy, - CallbackHandler handler) throws AuthException { - - ConfigFile.Entry[] entries = getEntries(intercept, id, requestPolicy, responsePolicy, SERVER); - if (entries == null || entries.length == 0) { - return null; - } - - // instantiate and initialize modules up front as well - - if (handler == null) { - handler = ConfigFile.loadDefaultCallbackHandler(); - } else if (handler instanceof DependentCallbackHandler) { - handler = new DelegatingHandler(handler); - } - - for (int i = 0; i < entries.length; i++) { - entries[i].module = ConfigFile.createModule(entries[i], handler); - } - - return new ConfigServer(entries); - } - - @Override - public void refresh() throws AuthException { - synchronized (this) { - ConfigParser nextParser; - int next = this.epoch + 1; - try { - nextParser = ConfigFile.loadParser(parserClassName); - } catch (IOException ioe) { - throw new AuthException(ioe.toString()); - } - this.epoch = (next == 0 ? 1 : next); - parser = nextParser; - } - } - - private ConfigFile.Entry[] getEntries(String intercept, String id, AuthPolicy requestPolicy, AuthPolicy responsePolicy, String type) { - - // get the parsed module config and DD information - - Map configMap; - - synchronized (parser) { - configMap = parser.getConfigMap(); - } - - if (configMap == null) { - return null; - } - - // get the module config info for this intercept - - GFServerConfigProvider.InterceptEntry intEntry = (GFServerConfigProvider.InterceptEntry) configMap.get(intercept); - if (intEntry == null || intEntry.getIdMap() == null) { - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("module config has no IDs configured for [" + intercept + "]"); - } - return null; - } - - // look up the DD's provider ID in the module config - - GFServerConfigProvider.IDEntry idEntry = null; - if (id == null || (idEntry = intEntry.getIdMap().get(id)) == null) { - - // either the DD did not specify a provider ID, - // or the DD-specified provider ID was not found - // in the module config. - // - // in either case, look for a default ID in the module config - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("DD did not specify ID, " + "or DD-specified ID for [" + intercept + "] not found in config -- " - + "attempting to look for default ID"); - } - - String defaultID; - if (CLIENT.equals(type)) { - defaultID = intEntry.getDefaultClientID(); - } else { - defaultID = intEntry.getDefaultServerID(); - } - - idEntry = intEntry.getIdMap().get(defaultID); - if (idEntry == null) { - - // did not find a default provider ID - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("no default config ID for [" + intercept + "]"); - } - return null; - } - } - - // we found the DD provider ID in the module config - // or we found a default module config - - // check provider-type - if (idEntry.getType().indexOf(type) < 0) { - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("request type [" + type + "] does not match config type [" + idEntry.getType() + "]"); - } - return null; - } - - // check whether a policy is set - AuthPolicy reqP, respP; - if (requestPolicy != null || responsePolicy != null) { - reqP = requestPolicy; - respP = responsePolicy; - } else if (idEntry.getRequestPolicy() != null || idEntry.getResponsePolicy() != null) { - // default - reqP = new AuthPolicy(idEntry.getRequestPolicy()); - respP = new AuthPolicy(idEntry.getResponsePolicy()); - } else { - // optimization: if policy was not set, return null - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("no policy applies"); - } - return null; - } - - // return the configured modules with the correct policies - - // ConfigFile.Entry[] entries = new Entry[idEntry.modules.size()]; - ConfigFile.Entry[] entries = new Entry[1]; - for (int i = 0; i < entries.length; i++) { - // Login Bridge profile? - entries[i] = new ConfigFile.Entry(reqP, respP, idEntry.getModuleClassName(), - AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, idEntry.getOptions()); - } - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("getEntries found " + entries.length + " entries for: " + intercept + " -- " + id); - - for (int i = 0; i < entries.length; i++) { - logger.fine("Entry " + (i + 1) + ":" + "\n module class: " + entries[i].getLoginModuleName() + "\n flag: " - + entries[i].getControlFlag() + "\n options: " + entries[i].getOptions() + "\n request policy: " - + entries[i].requestPolicy + "\n response policy: " + entries[i].responsePolicy); - } - - } - - return entries; - } - - /** - * get a custom config file parser - * - * XXX custom file that can be used in place of [domain|sun-acc].xml - */ - private static ConfigParser loadParser(String className) throws IOException { - try { - - final String finalClassName = className; - final ClassLoader finalLoader = AuthConfig.getClassLoader(); - - return (ConfigParser) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - Class c = Class.forName(finalClassName, true, finalLoader); - return c.newInstance(); - } - }); - } catch (java.security.PrivilegedActionException pae) { - IOException iex = new IOException(pae.getException().toString()); - iex.initCause(pae.getException()); - throw iex; - } - } - - /** - * get the default callback handler - */ - private static CallbackHandler loadDefaultCallbackHandler() throws AuthException { - - // get the default handler class - try { - - final ClassLoader finalLoader = AuthConfig.getClassLoader(); - - return (CallbackHandler) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - - String className = DEFAULT_HANDLER_CLASS; - Class c = Class.forName(className, true, finalLoader); - return c.newInstance(); - } - }); - } catch (java.security.PrivilegedActionException pae) { - AuthException aex = new AuthException(pae.getException().toString()); - aex.initCause(pae.getException()); - throw aex; - } - } - - /** - * Instantiate+initialize module class - */ - private static Object createModule(ConfigFile.Entry entry, CallbackHandler handler) throws AuthException { - try { - - // instantiate module using no-arg constructor - - Object newModule = entry.newInstance(); - - // initialize module - - Object[] initArgs = { entry.getRequestPolicy(), entry.getResponsePolicy(), handler, entry.getOptions() }; - - try { - Method initMethod = newModule.getClass().getMethod(AuthContext.INIT, AuthPolicy.class, AuthPolicy.class, - CallbackHandler.class, Map.class); - initMethod.invoke(newModule, initArgs); - // return the new module - return newModule; - } catch (Exception ex) { - throw new SecurityException( - "could not invoke " + AuthContext.INIT + " method in module: " + newModule.getClass().getName() + " " + ex, ex); - } - - } catch (Exception e) { - if (e instanceof AuthException) { - throw (AuthException) e; - } - AuthException ae = new AuthException(); - ae.initCause(e); - throw ae; - } - } - - /** - * Class representing a single AuthModule entry configured for an ID, interception point, and stack. - * - *

- * An instance of this class contains the same information as its superclass, AppConfigurationEntry. It additionally - * stores the request and response policy assigned to this module. - * - *

- * This class also provides a way for a caller to obtain an instance of the module listed in the entry by invoking the - * newInstance method. - */ - static class Entry extends javax.security.auth.login.AppConfigurationEntry { - - // for loading modules - private static final Class[] PARAMS = {}; - private static final Object[] ARGS = {}; - - private AuthPolicy requestPolicy; - private AuthPolicy responsePolicy; - Object module = null; // convenience location to store instance - - // package private for AuthContext - - /** - * Construct a ConfigFile entry. - * - *

- * An entry encapsulates a single module and its related information. - * - * @param requestPolicy the request policy assigned to the module listed in this entry, which may be null. - * - * @param responsePolicy the response policy assigned to the module listed in this entry, which may be null. - * - * @param moduleClass the fully qualified class name of the module. - * - * @param flag the module control flag. This value must either be REQUIRED, REQUISITE, SUFFICIENT, or OPTIONAL. - * - * @param options the options configured for this module. - */ - Entry(AuthPolicy requestPolicy, AuthPolicy responsePolicy, String moduleClass, AppConfigurationEntry.LoginModuleControlFlag flag, - Map options) { - super(moduleClass, flag, options); - this.requestPolicy = requestPolicy; - this.responsePolicy = responsePolicy; - } - - /** - * Return the request policy assigned to this module. - * - * @return the policy, which may be null. - */ - AuthPolicy getRequestPolicy() { - return requestPolicy; - } - - /** - * Return the response policy assigned to this module. - * - * @return the policy, which may be null. - */ - AuthPolicy getResponsePolicy() { - return responsePolicy; - } - - /** - * Return a new instance of the module contained in this entry. - * - *

- * The default implementation of this method attempts to invoke the default no-args constructor of the module class. - * This method may be overridden if a different constructor should be invoked. - * - * @return a new instance of the module contained in this entry. - * - * @exception AuthException if the instantiation failed. - */ - Object newInstance() throws AuthException { - try { - final ClassLoader finalLoader = AuthConfig.getClassLoader(); - String clazz = getLoginModuleName(); - Class c = Class.forName(clazz, true, finalLoader); - java.lang.reflect.Constructor constructor = c.getConstructor(PARAMS); - return constructor.newInstance(ARGS); - } catch (Exception e) { - AuthException ae = new AuthException(); - ae.initCause(e); - throw ae; - } - } - } - - /** - * parsed Intercept entry - */ - /* - * static class InterceptEntry { String defaultClientID; String defaultServerID; HashMap idMap; InterceptEntry(String - * defaultClientID, String defaultServerID, HashMap idMap) { this.defaultClientID = defaultClientID; - * this.defaultServerID = defaultServerID; this.idMap = idMap; } } - */ - - /** - * parsed ID entry - */ - /* - * static class IDEntry { private String type; // provider type (client, server, client-server) private AuthPolicy - * requestPolicy; private AuthPolicy responsePolicy; private ArrayList modules; IDEntry(String type, AuthPolicy - * requestPolicy, AuthPolicy responsePolicy, ArrayList modules) { this.type = type; this.modules = modules; - * this.requestPolicy = requestPolicy; this.responsePolicy = responsePolicy; } // XXX delete this later IDEntry(String - * type, String requestPolicy, String responsePolicy, ArrayList modules) { this.type = type; if (requestPolicy != null) - * { this.requestPolicy = new AuthPolicy(AuthPolicy.SOURCE_AUTH_SENDER, true, // recipient-auth true); // beforeContent - * } if (responsePolicy != null) { this.responsePolicy = new AuthPolicy(AuthPolicy.SOURCE_AUTH_CONTENT, true, // - * recipient-auth false); // beforeContent } this.modules = modules; } } - */ - - /** - * Default implementation of ClientAuthContext. - */ - private static class ConfigClient implements ClientAuthContext { - - // class that does all the work - private AuthContext context; - - ConfigClient(Entry[] entries) throws AuthException { - context = new AuthContext(entries, logger); - } - - @Override - public void secureRequest(AuthParam param, Subject subject, Map sharedState) throws AuthException { - - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.SECURE_REQUEST, args); - } - - @Override - public void validateResponse(AuthParam param, Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.VALIDATE_RESPONSE, args); - } - - @Override - public void disposeSubject(Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { subject, sharedState }; - context.invoke(AuthContext.DISPOSE_SUBJECT, args); - } - } - - /** - * Default implementation of ServerAuthContext. - */ - private static class ConfigServer implements ServerAuthContext { - - // class that does all the work - private AuthContext context; - - ConfigServer(Entry[] entries) throws AuthException { - - context = new AuthContext(entries, logger); - } - - @Override - public void validateRequest(AuthParam param, Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.VALIDATE_REQUEST, args); - } - - @Override - public void secureResponse(AuthParam param, Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.SECURE_RESPONSE, args); - } - - @Override - public void disposeSubject(Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { subject, sharedState }; - context.invoke(AuthContext.DISPOSE_SUBJECT, args); - } - - @Override - public boolean managesSessions(Map sharedState) throws AuthException { - - // invoke modules - Object[] args = { sharedState }; - Object[] rValues = null; - - try { - rValues = context.invoke(AuthContext.MANAGES_SESSIONS, args); - } catch (AuthException ae) { - // this new method may not be implemeneted - // by old modules - if (!(ae.getCause() instanceof NoSuchMethodException)) { - throw ae; - } - } - - boolean rvalue = false; - - for (int i = 0; rValues != null && i < rValues.length; i++) { - if (rValues[i] != null) { - boolean thisValue = ((Boolean) rValues[i]).booleanValue(); - rvalue = rvalue | thisValue; - } - } - - return rvalue; - } - } - - private static class DelegatingHandler implements CallbackHandler { - - CallbackHandler handler; - - CallbackHandler defaultHandler; - - private DelegatingHandler(CallbackHandler cbh) { - handler = cbh; - try { - defaultHandler = ConfigFile.loadDefaultCallbackHandler(); - } catch (Exception e) { - defaultHandler = null; - } - } - - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - if (defaultHandler == null) { - handler.handle(callbacks); - } else { - Callback[] oneCallback = new Callback[1]; - for (int i = 0; i < callbacks.length; i++) { - - boolean tryDefault = false; - - oneCallback[0] = callbacks[i]; - try { - handler.handle(oneCallback); - } catch (UnsupportedCallbackException uce) { - tryDefault = true; - } - if (tryDefault) { - defaultHandler.handle(oneCallback); - } - } - } - } - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java index 206dd3f6314..34139192e71 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2017-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] /* * PrincipalGroupFactory.java * @@ -50,8 +50,8 @@ import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; import org.jvnet.hk2.annotations.Service; +import org.glassfish.epicyro.config.helper.CallerPrincipal; import com.sun.enterprise.security.PrincipalGroupFactory; @@ -65,10 +65,10 @@ public class PrincipalGroupFactoryImpl implements PrincipalGroupFactory { private static WeakReference webSecurityManagerFactory = new WeakReference(null); @Override - public PrincipalImpl getPrincipalInstance(String name, String realm) { - PrincipalImpl principal = (PrincipalImpl) getWebSecurityManagerFactory().getAdminPrincipal(name, realm); + public CallerPrincipal getPrincipalInstance(String name, String realm) { + CallerPrincipal principal = (CallerPrincipal) getWebSecurityManagerFactory().getAdminPrincipal(name, realm); if (principal == null) { - principal = new PrincipalImpl(name); + principal = new CallerPrincipal(name); } return principal; diff --git a/appserver/security/jaspic-provider-framework/osgi.bundle b/appserver/security/jaspic-provider-framework/osgi.bundle index c0460d0b2f0..46a378460ef 100644 --- a/appserver/security/jaspic-provider-framework/osgi.bundle +++ b/appserver/security/jaspic-provider-framework/osgi.bundle @@ -37,8 +37,8 @@ # only if the new code is made subject to such option by the copyright # holder. # --exportcontents: \ - com.sun.jaspic.services; \ +# Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] +-exportcontents: \ com.sun.jaspic.config.delegate; \ com.sun.jaspic.config.factory; \ com.sun.jaspic.config.jaas; \ diff --git a/appserver/security/jaspic-provider-framework/pom.xml b/appserver/security/jaspic-provider-framework/pom.xml index a6e37802c2f..a1b0da2f474 100644 --- a/appserver/security/jaspic-provider-framework/pom.xml +++ b/appserver/security/jaspic-provider-framework/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -83,5 +83,9 @@ org.glassfish.soteria jakarta.security.enterprise + + org.glassfish.epicyro + epicyro + diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java deleted file mode 100644 index f46ad3325e8..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -/** - * - * @author ronmonzillo - */ -public class AuthConfigFileFactory extends BaseAuthConfigFactory { - - // MUST "hide" regStore in derived class. - private static volatile RegStoreFileParser regStore; - - /** - * To specialize the defaultEntries passed to the {@link RegStoreFileParser} constructor, create another subclass of - * BaseAuthconfigFactory, that is basically a copy of this class, with a change to the third argument of the call to new - * ResSToreFileParser. To ensure runtime use of the the associated regStore, make sure that the new subclass also - * contains an implementation of the getRegStore method. - * - *

- * As done within this class, use the locks defined in BaseAuthConfigFactory to serialize access to the regStore (both - * within the class constructor, and within getRegStore) - *

- * - *

- * All EentyInfo OBJECTS PASSED as default Entries MUST HAVE BEEN CONSTRUCTED USING THE FOLLOWING CONSTRUCTOR: - * EntryInfo(String className, Map properties); - * - *

- * - */ - public AuthConfigFileFactory() { - if (doReadLocked(() -> regStore != null)) { - return; - } - - String userDir = System.getProperty("user.dir"); - - doWriteLocked(() -> { - if (regStore == null) { - regStore = new RegStoreFileParser(userDir, CONF_FILE_NAME, null); - _loadFactory(); - } - }); - } - - @Override - protected RegStoreFileParser getRegStore() { - return doReadLocked(() -> regStore); - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java deleted file mode 100644 index 851a6f0bccb..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright 2018-2024 Payara Foundation and/or its affiliates -package com.sun.jaspic.config.factory; - -import static com.sun.jaspic.config.helper.JASPICLogManager.JASPIC_LOGGER; -import static com.sun.jaspic.config.helper.JASPICLogManager.RES_BUNDLE; -import static java.util.logging.Level.WARNING; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.function.Supplier; -import java.util.logging.Logger; - -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.RegistrationListener; -import jakarta.security.auth.message.module.ServerAuthModule; -import jakarta.servlet.ServletContext; -import static org.glassfish.soteria.Utils.isEmpty; - - -/** - * This class implements methods in the abstract class AuthConfigFactory. - * - * @author Shing Wai Chan - */ -public abstract class BaseAuthConfigFactory extends AuthConfigFactory { - - private static final Logger logger = Logger.getLogger(JASPIC_LOGGER, RES_BUNDLE); - - private static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); - - public static final Lock readLock = readWriteLock.readLock(); - public static final Lock writeLock = readWriteLock.writeLock(); - - private static Map idToProviderMap; - private static Map idToRegistrationContextMap; - private static Map> idToRegistrationListenersMap; - private static Map> providerToIdsMap; - - protected static final String CONF_FILE_NAME = "auth.conf"; - private static final String CONTEXT_REGISTRATION_ID = "org.glassfish.security.message.registrationId"; - - /** - * Get a registered AuthConfigProvider from the factory. - * - * Get the provider of ServerAuthConfig and/or ClientAuthConfig objects registered for the identified message layer and - * application context. - * - *

- * All factories shall employ the following precedence rules to select the registered AuthConfigProvider that matches - * (via matchConstructors) the layer and appContext arguments: - *

    - *
  • The provider that is specifically registered for both the corresponding message layer and appContext shall be - * selected. - *
  • if no provider is selected according to the preceding rule, the provider specifically registered for the - * corresponding appContext and for all message layers shall be selected. - *
  • if no provider is selected according to the preceding rules, the provider specifically registered for the - * corresponding message layer and for all appContexts shall be selected. - *
  • if no provider is selected according to the preceding rules, the provider registered for all message layers and - * for all appContexts shall be selected. - *
  • if no provider is selected according to the preceding rules, the factory shall terminate its search for a - * registered provider. - *
- * - * @param layer a String identifying the message layer for which the registered AuthConfigProvider is to be returned. - * This argument may be null. - * - * @param appContext a String that identifies the application messaging context for which the registered - * AuthConfigProvider is to be returned. This argument may be null. - * - * @param listener the RegistrationListener whose notify method is to be invoked if the corresponding - * registration is unregistered or replaced. The value of this argument may be null. - * - * @return the implementation of the AuthConfigProvider interface registered at the factory for the layer and appContext - * or null if no AuthConfigProvider is selected. - * - */ - @Override - public AuthConfigProvider getConfigProvider(String layer, String appContext, RegistrationListener listener) { - if (listener == null) { - return doReadLocked(() -> getConfigProviderUnderLock(layer, appContext, null)); - } - - return doWriteLocked(() -> getConfigProviderUnderLock(layer, appContext, listener)); - } - - /** - * Registers within the factory, a provider of ServerAuthConfig and/or ClientAuthConfig objects for a message layer and - * application context identifier. - * - *

- * At most one registration may exist within the factory for a given combination of message layer and appContext. Any - * pre-existing registration with identical values for layer and appContext is replaced by a subsequent registration. - * When replacement occurs, the registration identifier, layer, and appContext identifier remain unchanged, and the - * AuthConfigProvider (with initialization properties) and description are replaced. - * - *

- * Within the lifetime of its Java process, a factory must assign unique registration identifiers to registrations, and - * must never assign a previously used registration identifier to a registration whose message layer and or appContext - * identifier differ from the previous use. - * - *

- * Programmatic registrations performed via this method must update (according to the replacement rules described - * above), the persistent declarative representation of provider registrations employed by the factory constructor. - * - * @param className the fully qualified name of an AuthConfigProvider implementation class. This argument must not be - * null. - * - * @param properties a Map object containing the initialization properties to be passed to the provider constructor. - * This argument may be null. When this argument is not null, all the values and keys occuring in the Map must be of - * type String. - * - * @param layer a String identifying the message layer for which the provider will be registered at the factory. A null - * value may be passed as an argument for this parameter, in which case, the provider is registered at all layers. - * - * @param appContext a String value that may be used by a runtime to request a configuration object from this provider. - * A null value may be passed as an argument for this parameter, in which case, the provider is registered for all - * configuration ids (at the indicated layers). - * - * @param description a text String describing the provider. this value may be null. - * - * @return a String identifier assigned by the factory to the provider registration, and that may be used to remove the - * registration from the provider. - * - * @exception SecurityException If the provider construction (given a non-null className) or - * registration fails. - * - * @exception AuthException if the provider construction or registration fails. - */ - @Override - @SuppressWarnings("unchecked") - public String registerConfigProvider(String className, @SuppressWarnings("rawtypes") Map properties, String layer, String appContext, - String description) { - return _register(_constructProvider(className, properties, null), properties, layer, appContext, description, true); - } - - @Override - public String registerConfigProvider(AuthConfigProvider provider, String layer, String appContext, String description) { - return _register(provider, null, layer, appContext, description, false); - } - - /** - * Remove the identified provider registration from the factory and invoke any listeners associated with the removed - * registration. - * - * @param registrationID a String that identifies a provider registration at the factory - * - * @return true if there was a registration with the specified identifier and it was removed. Return false if the - * registraionID was invalid. - * - */ - @Override - public boolean removeRegistration(String registrationID) { - return _unRegister(registrationID); - } - - /** - * Disassociate the listener from all the provider registrations whose layer and appContext values are matched by the - * corresponding arguments to this method. - * - * @param listener the RegistrationListener to be detached. - * - * @param layer a String identifying the message layer or null. - * - * @param appContext a String value identifying the application context or null. - * - * @return an array of String values where each value identifies a provider registration from which the listener was - * removed. This method never returns null; it returns an empty array if the listener was not removed from any - * registrations. - * - */ - @Override - public String[] detachListener(RegistrationListener listener, String layer, String appContext) { - List removedListenerIds = new ArrayList<>(); - String registrationId = getRegistrationID(layer, appContext); - - doWriteLocked(() -> { - for (Entry> entry : idToRegistrationListenersMap.entrySet()) { - String targetID = entry.getKey(); - if (regIdImplies(registrationId, targetID)) { - List listeners = entry.getValue(); - if (listeners != null && listeners.remove(listener)) { - removedListenerIds.add(targetID); - } - } - } - }); - - return removedListenerIds.toArray(new String[removedListenerIds.size()]); - } - - /** - * Get the registration identifiers for all registrations of the provider instance at the factory. - * - * @param provider the AuthConfigurationProvider whose registration identifiers are to be returned. This argument may be - * null, in which case, it indicates that the the id's of all active registration within the factory are returned. - * - * @return an array of String values where each value identifies a provider registration at the factory. This method - * never returns null; it returns an empty array when their are no registrations at the factory for the identified - * provider. - */ - @Override - public String[] getRegistrationIDs(AuthConfigProvider provider) { - return doReadLocked(() -> { - Collection registrationIDs = null; - - if (provider != null) { - registrationIDs = providerToIdsMap.get(provider); - } else { - Collection> collList = providerToIdsMap.values(); - if (collList != null) { - registrationIDs = new HashSet<>(); - for (List listIds : collList) { - if (listIds != null) { - registrationIDs.addAll(listIds); - } - } - } - } - - return registrationIDs != null ? registrationIDs.toArray(new String[registrationIDs.size()]) : new String[0]; - }); - } - - /** - * Get the the registration context for the identified registration. - * - * @param registrationID a String that identifies a provider registration at the factory - * - * @return a RegistrationContext or null. When a Non-null value is returned, it is a copy of the registration context - * corresponding to the registration. Null is returned when the registration identifier does not correspond to an active - * registration - */ - @Override - public RegistrationContext getRegistrationContext(String registrationID) { - return doReadLocked(() -> idToRegistrationContextMap.get(registrationID)); - } - - /** - * Cause the factory to reprocess its persistent declarative representation of provider registrations. - * - *

- * A factory should only replace an existing registration when a change of provider implementation class or - * initialization properties has occurred. - * - * @exception AuthException if an error occurred during the reinitialization. - * - * @exception SecurityException If an error occurred during the reinitialization. - */ - @Override - public void refresh() { - Map> preExistingListenersMap = doWriteLocked(() -> loadFactory()); - - // Notify pre-existing listeners after (re)loading factory - if (preExistingListenersMap != null) { - notifyListeners(preExistingListenersMap); - } - } - - abstract protected RegStoreFileParser getRegStore(); - - private AuthConfigProvider getConfigProviderUnderLock(String layer, String appContext, RegistrationListener listener) { - AuthConfigProvider provider = null; - String registrationID = getRegistrationID(layer, appContext); - - boolean providerFound = false; - if (idToProviderMap.containsKey(registrationID)) { - provider = idToProviderMap.get(registrationID); - providerFound = true; - } - - if (!providerFound) { - String matchedID = getRegistrationID(null, appContext); - if (idToProviderMap.containsKey(matchedID)) { - provider = idToProviderMap.get(matchedID); - providerFound = true; - } - } - - if (!providerFound) { - String matchedID = getRegistrationID(layer, null); - if (idToProviderMap.containsKey(matchedID)) { - provider = idToProviderMap.get(matchedID); - providerFound = true; - } - } - - if (!providerFound) { - String matchedID = getRegistrationID(null, null); - if (idToProviderMap.containsKey(matchedID)) { - provider = idToProviderMap.get(matchedID); - } - } - - if (listener != null) { - List listeners = idToRegistrationListenersMap.computeIfAbsent( - registrationID, e -> new ArrayList()); - - if (!listeners.contains(listener)) { - listeners.add(listener); - } - } - - return provider; - } - - private static String getRegistrationID(String layer, String appContext) { - - // (layer, appContext) -> __3_ - // (layer, null) -> __2 - // (null, appContext) -> __1 - // (null, null) -> __0 - - if (layer != null) { - return appContext != null ? "__3" + layer.length() + "_" + layer + appContext : "__2" + layer; - } - - return appContext != null ? "__1" + appContext : "__0"; - } - - /** - * This API decomposes the given registration ID into layer and appContext. - * - * @param registrationId - * @return a String array with layer and appContext - */ - private static String[] decomposeRegistrationId(String registrationId) { - String layer = null; - String appContext = null; - - if (registrationId.equals("__0")) { - // null, null - } else if (registrationId.startsWith("__1")) { - appContext = (registrationId.length() == 3) ? "" : registrationId.substring(3); - } else if (registrationId.startsWith("__2")) { - layer = (registrationId.length() == 3) ? "" : registrationId.substring(3); - } else if (registrationId.startsWith("__3")) { - int ind = registrationId.indexOf('_', 3); - if (registrationId.length() > 3 && ind > 0) { - String numberString = registrationId.substring(3, ind); - int n; - try { - n = Integer.parseInt(numberString); - } catch (Exception ex) { - throw new IllegalArgumentException(); - } - layer = registrationId.substring(ind + 1, ind + 1 + n); - appContext = registrationId.substring(ind + 1 + n); - } else { - throw new IllegalArgumentException(); - } - } else { - throw new IllegalArgumentException(); - } - - return new String[] { layer, appContext }; - } - - private static AuthConfigProvider _constructProvider(String className, Map properties, AuthConfigFactory factory) { - AuthConfigProvider provider = null; - - if (className != null) { - try { - provider = (AuthConfigProvider) Class.forName(className, true, Thread.currentThread().getContextClassLoader()) - .getConstructor(Map.class, AuthConfigFactory.class) - .newInstance(new Object[] { properties, factory }); - } catch (Throwable t) { - Throwable cause = t.getCause(); - logger.log(WARNING, "jaspic.factory_unable_to_load_provider", - new Object[] { className, t.toString(), cause == null ? "cannot determine" : cause.toString() }); - } - } - - return provider; - } - - // XXX need to update persistent state and notify effected listeners - private String _register(AuthConfigProvider provider, Map properties, String layer, String appContext, - String description, boolean persistent) { - String registrationId = getRegistrationID(layer, appContext); - RegistrationContext registrationContext = new RegistrationContextImpl(layer, appContext, description, persistent); - - Map> listenerMap = doWriteLocked( - () -> register(provider, properties, persistent, registrationId, registrationContext)); - - // Outside write lock to prevent dead lock - notifyListeners(listenerMap); - - return registrationId; - } - - private Map> register(AuthConfigProvider provider, Map properties, - boolean persistent, String registrationId, RegistrationContext registrationContext) { - RegistrationContext previousRegistrationContext = idToRegistrationContextMap.get(registrationId); - AuthConfigProvider previousProvider = idToProviderMap.get(registrationId); - - // Handle the persistence first - so that any exceptions occur before - // the actual registration happens - if (persistent) { - _storeRegistration(registrationContext, provider, properties); - } else if (previousRegistrationContext != null && previousRegistrationContext.isPersistent()) { - _deleteStoredRegistration(previousRegistrationContext); - } - - if (idToProviderMap.containsKey(registrationId)) { - List previousRegistrationsIds = providerToIdsMap.get(previousProvider); - previousRegistrationsIds.remove(registrationId); - if (previousRegistrationsIds.isEmpty()) { - providerToIdsMap.remove(previousProvider); - } - } - - idToProviderMap.put(registrationId, provider); - idToRegistrationContextMap.put(registrationId, registrationContext); - - List registrationIds = providerToIdsMap.computeIfAbsent(provider, e -> new ArrayList()); - - if (!registrationIds.contains(registrationId)) { - registrationIds.add(registrationId); - } - - return getEffectedListeners(registrationId); - } - - // XXX need to update persistent state and notify effected listeners - private boolean _unRegister(String registrationId) { - boolean hasProvider = false; - Map> listenerMap; - - writeLock.lock(); - try { - RegistrationContext registrationContext = idToRegistrationContextMap.remove(registrationId); - hasProvider = idToProviderMap.containsKey(registrationId); - AuthConfigProvider provider = idToProviderMap.remove(registrationId); - - List registrationIds = providerToIdsMap.get(provider); - if (registrationIds != null) { - registrationIds.remove(registrationId); - } - - if (registrationIds == null || registrationIds.isEmpty()) { - providerToIdsMap.remove(provider); - } - - if (!hasProvider) { - return false; - } - - listenerMap = getEffectedListeners(registrationId); - if (registrationContext != null && registrationContext.isPersistent()) { - _deleteStoredRegistration(registrationContext); - } - } finally { - writeLock.unlock(); - } - - // Outside write lock to prevent dead lock - notifyListeners(listenerMap); - - return hasProvider; - } - - private Map> loadFactory() { - Map> oldId2RegisListenersMap = idToRegistrationListenersMap; - - _loadFactory(); - - return oldId2RegisListenersMap; - } - - // ### The following methods implement the factory's persistence layer - - protected void _loadFactory() { - try { - initializeMaps(); - - List persistedEntries = getRegStore().getPersistedEntries(); - - for (EntryInfo info : persistedEntries) { - if (info.isConstructorEntry()) { - _constructProvider(info.getClassName(), info.getProperties(), this); - } else { - boolean first = true; - AuthConfigProvider configProvider = null; - for (RegistrationContext context : info.getRegistrationContexts()) { - if (first) { - configProvider = _constructProvider(info.getClassName(), info.getProperties(), null); - } - - _loadRegistration(configProvider, context.getMessageLayer(), context.getAppContext(), context.getDescription()); - } - } - } - } catch (Exception e) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_auth_config_loader_failure", e); - } - } - } - - /** - * Initialize the static maps in a static method - */ - private static void initializeMaps() { - idToProviderMap = new HashMap<>(); - idToRegistrationContextMap = new HashMap<>(); - idToRegistrationListenersMap = new HashMap<>(); - providerToIdsMap = new HashMap<>(); - } - - private static String _loadRegistration(AuthConfigProvider provider, String layer, String appContext, String description) { - - RegistrationContext registrationContext = new RegistrationContextImpl(layer, appContext, description, true); - String registrationId = getRegistrationID(layer, appContext); - - AuthConfigProvider previousProvider = idToProviderMap.get(registrationId); - - boolean wasRegistered = idToProviderMap.containsKey(registrationId); - if (wasRegistered) { - List previousRegistrationIds = providerToIdsMap.get(previousProvider); - previousRegistrationIds.remove(registrationId); - if (previousRegistrationIds.isEmpty()) { - providerToIdsMap.remove(previousProvider); - } - } - - idToProviderMap.put(registrationId, provider); - idToRegistrationContextMap.put(registrationId, registrationContext); - - List registrationIds = providerToIdsMap.get(provider); - if (registrationIds == null) { - registrationIds = new ArrayList<>(); - providerToIdsMap.put(provider, registrationIds); - } - - if (!registrationIds.contains(registrationId)) { - registrationIds.add(registrationId); - } - - return registrationId; - } - - private void _storeRegistration(RegistrationContext registrationContext, AuthConfigProvider configProvider, - Map properties) { - String className = null; - if (configProvider != null) { - className = configProvider.getClass().getName(); - } - - if (propertiesContainAnyNonStringValues(properties)) { - throw new IllegalArgumentException("AuthConfigProvider cannot be registered - properties must all be of type String."); - } - - if (registrationContext.isPersistent()) { - getRegStore().store(className, registrationContext, properties); - } - } - - private boolean propertiesContainAnyNonStringValues(Map properties) { - if (properties != null) { - for (Map.Entry entry : properties.entrySet()) { - if (!(entry.getValue() instanceof String)) { - return true; - } - } - } - - return false; - } - - private void _deleteStoredRegistration(RegistrationContext registrationContext) { - if (registrationContext.isPersistent()) { - getRegStore().delete(registrationContext); - } - } - - private static boolean regIdImplies(String reference, String target) { - - boolean rvalue = true; - - String[] refID = decomposeRegistrationId(reference); - String[] targetID = decomposeRegistrationId(target); - - if (refID[0] != null && !refID[0].equals(targetID[0])) { - rvalue = false; - } else if (refID[1] != null && !refID[1].equals(targetID[1])) { - rvalue = false; - } - - return rvalue; - } - - /** - * Will return some extra listeners. In other words, effected listeners could be reduced by removing any associated with - * a provider registration id that is more specific than the one being added or removed. - */ - private static Map> getEffectedListeners(String regisID) { - Map> effectedListeners = new HashMap<>(); - Set listenerRegistrations = new HashSet<>(idToRegistrationListenersMap.keySet()); - - for (String listenerID : listenerRegistrations) { - if (regIdImplies(regisID, listenerID)) { - if (!effectedListeners.containsKey(listenerID)) { - effectedListeners.put(listenerID, new ArrayList<>()); - } - effectedListeners.get(listenerID).addAll(idToRegistrationListenersMap.remove(listenerID)); - } - } - return effectedListeners; - } - - protected T doReadLocked(Supplier supplier) { - readLock.lock(); - try { - return supplier.get(); - } finally { - readLock.unlock(); - } - } - - protected T doWriteLocked(Supplier supplier) { - writeLock.lock(); - try { - return supplier.get(); - } finally { - writeLock.unlock(); - } - } - - protected void doWriteLocked(Runnable runnable) { - writeLock.lock(); - try { - runnable.run(); - } finally { - writeLock.unlock(); - } - } - - private static void notifyListeners(Map> map) { - Set>> entrySet = map.entrySet(); - for (Map.Entry> entry : entrySet) { - List listeners = map.get(entry.getKey()); - - if (listeners != null && listeners.size() > 0) { - String[] dIds = decomposeRegistrationId(entry.getKey()); - - for (RegistrationListener listener : listeners) { - listener.notify(dIds[0], dIds[1]); - } - } - } - } - - @Override - public String registerServerAuthModule(ServerAuthModule sam, Object context) { - String registrationId = null; - if (context instanceof ServletContext) { - ServletContext servletContext = (ServletContext) context; - - String appContext = servletContext.getVirtualServerName() + " " + servletContext.getContextPath(); - registrationId = registerConfigProvider(new DefaultAuthConfigProvider(sam), "HttpServlet", appContext, - "Default authentication config provider"); - - servletContext.setAttribute(CONTEXT_REGISTRATION_ID, registrationId); - } - return registrationId; - } - - @Override - public void removeServerAuthModule(Object context) { - if (context instanceof ServletContext) { - ServletContext servletContext = (ServletContext) context; - String registrationId = (String) servletContext.getAttribute(CONTEXT_REGISTRATION_ID); - if (!isEmpty(registrationId)) { - removeRegistration(registrationId); - } - } - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java deleted file mode 100644 index 0330d918878..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -import static com.sun.jaspic.config.helper.JASPICLogManager.JASPIC_LOGGER; -import static com.sun.jaspic.config.helper.JASPICLogManager.RES_BUNDLE; -import static java.util.logging.Level.FINER; -import static java.util.logging.Level.INFO; -import static java.util.logging.Level.WARNING; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.logging.Logger; - -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; - -/** - * Used by ServerConfigProvider to parse the configuration file. If a file does not exist originally, the default - * providers are not used. A file is only created if needed, which happens if providers are registered or unregistered - * through the store() or delete() methods. - * - * @author Bobby Bissett - */ -public final class RegStoreFileParser { - - private static final Logger logger = Logger.getLogger(JASPIC_LOGGER, RES_BUNDLE); - - private static final String SEP = ":"; - private static final String CON_ENTRY = "con-entry"; - private static final String REG_ENTRY = "reg-entry"; - private static final String REG_CTX = "reg-ctx"; - private static final String LAYER = "layer"; - private static final String APP_CTX = "app-ctx"; - private static final String DESCRIPTION = "description"; - private static final String[] INDENT = { "", " ", " " }; - - private final File configurationFile; - private List entries; - private List defaultEntries; - - /** - * Loads the configuration file from the given filename. If a file is not found, then the default entries are used. - * Otherwise the file is parsed to load the entries. - * - */ - public RegStoreFileParser(String pathParent, String pathChild, List defaultEntries) { - configurationFile = new File(pathParent, pathChild); - this.defaultEntries = defaultEntries == null ? new ArrayList() : defaultEntries; - - try { - loadEntries(); - } catch (IOException ioe) { - logWarningDefault(ioe); - } catch (IllegalArgumentException iae) { - logWarningDefault(iae); - } - } - - /** - * Returns the in-memory list of entries. MUST Hold exclusive lock on calling factory while processing entries - */ - List getPersistedEntries() { - return entries; - } - - /** - * Adds the provider to the entry list if it is not already present, creates the configuration file if necessary, and - * writes the entries to the file. - */ - void store(String className, RegistrationContext registrationContext, Map properties) { - synchronized (configurationFile) { - if (checkAndAddToList(className, registrationContext, properties)) { - try { - writeEntries(); - } catch (IOException ioe) { - logWarningUpdated(ioe); - } - } - } - } - - /** - * Removes the provider from the entry list if it is already present, creates the configuration file if necessary, and - * writes the entries to the file. - */ - void delete(RegistrationContext registrationContext) { - synchronized (configurationFile) { - if (checkAndRemoveFromList(registrationContext)) { - try { - writeEntries(); - } catch (IOException ioe) { - logWarningUpdated(ioe); - } - } - } - } - - /** - * If this entry does not exist, this method stores it in the entries list and returns true to indicate that the - * configuration file should be written. - */ - private boolean checkAndAddToList(String className, RegistrationContext registrationContext, Map properties) { - - // Convention is to use null for empty properties - if (properties != null && properties.isEmpty()) { - properties = null; - } - - EntryInfo newEntry = new EntryInfo(className, properties, registrationContext); - EntryInfo entry = getMatchingRegistrationEntry(newEntry); - - // There is no matching entry, so add to list - if (entry == null) { - entries.add(newEntry); - return true; - } - - // Otherwise, check reg contexts to see if there is a match - if (entry.getRegistrationContexts().contains(registrationContext)) { - return false; - } - - // No matching context in existing entry, so add to existing entry - entry.getRegistrationContexts().add(new RegistrationContextImpl(registrationContext)); - - return true; - } - - /** - * If this registration context does not exist, this method returns false. Otherwise it removes the entry and returns - * true to indicate that the configuration file should be written. - * - * This only makes sense for registry entries. - */ - private boolean checkAndRemoveFromList(RegistrationContext target) { - boolean retValue = false; - try { - ListIterator lit = entries.listIterator(); - while (lit.hasNext()) { - - EntryInfo info = lit.next(); - if (info.isConstructorEntry()) { - continue; - } - - Iterator iter = info.getRegistrationContexts().iterator(); - while (iter.hasNext()) { - RegistrationContext ctx = iter.next(); - if (ctx.equals(target)) { - iter.remove(); - if (info.getRegistrationContexts().isEmpty()) { - lit.remove(); - } - retValue = true; - } - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - - return retValue; - } - - /** - * Used to find a matching registration entry in the 'entries' list without including registration contexts. If there is - * not a matching entry, return null. - */ - private EntryInfo getMatchingRegistrationEntry(EntryInfo target) { - for (EntryInfo info : entries) { - if (!info.isConstructorEntry() && info.matchConstructors(target)) { - return info; - } - } - - return null; - } - - /** - * This method overwrites the existing file with the current entries. - */ - private void writeEntries() throws IOException { - if (configurationFile.exists() && !configurationFile.canWrite() && logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_cannot_write_file", configurationFile.getPath()); - } - - clearExistingFile(); - - PrintWriter out = new PrintWriter(configurationFile); - int indent = 0; - for (EntryInfo info : entries) { - if (info.isConstructorEntry()) { - writeConEntry(info, out, indent); - } else { - writeRegEntry(info, out, indent); - } - } - out.close(); - } - - /** - * Writes constructor entry output of the form: - * - *

-     *  con-entry { className key:value key:value }
-     * 
- * - * The first appearance of a colon ":" separates the key and value of the property (so a value may contain a colon as - * part of the string). For instance: "mydir:c:foo" would have key "mydir" and value "c:foo". - */ - private void writeConEntry(EntryInfo info, PrintWriter out, int i) { - out.println(INDENT[i++] + CON_ENTRY + " {"); - out.println(INDENT[i] + info.getClassName()); - - Map properties = info.getProperties(); - if (properties != null) { - for (Map.Entry val : properties.entrySet()) { - out.println(INDENT[i] + val.getKey() + SEP + val.getValue()); - } - } - - out.println(INDENT[--i] + "}"); - } - - /* - * Write registration entry output of the form:
 reg-entry { con-entry { see writeConEntry() for detail } reg-ctx {
-     * layer:HttpServlet app-ctx:security-jaspic-https description:My provider } } 
- */ - private void writeRegEntry(EntryInfo info, PrintWriter out, int i) { - out.println(INDENT[i++] + REG_ENTRY + " {"); - if (info.getClassName() != null) { - writeConEntry(info, out, i); - } - - for (RegistrationContext registrationContext : info.getRegistrationContexts()) { - out.println(INDENT[i++] + REG_CTX + " {"); - if (registrationContext.getMessageLayer() != null) { - out.println(INDENT[i] + LAYER + SEP + registrationContext.getMessageLayer()); - } - - if (registrationContext.getAppContext() != null) { - out.println(INDENT[i] + APP_CTX + SEP + registrationContext.getAppContext()); - } - - if (registrationContext.getDescription() != null) { - out.println(INDENT[i] + DESCRIPTION + SEP + registrationContext.getDescription()); - } - - out.println(INDENT[--i] + "}"); - } - - out.println(INDENT[--i] + "}"); - } - - private void clearExistingFile() throws IOException { - boolean newCreation = !configurationFile.exists(); - - if (!newCreation) { - if (!configurationFile.delete()) { - throw new IOException(); - } - } - - if (newCreation) { - logger.log(INFO, "jaspic.factory_creating_conf_file", configurationFile.getPath()); - } - - if (!configurationFile.createNewFile()) { - throw new IOException(); - } - } - - /** - * Called from the constructor. This is the only time the file is read, though it is written when new entries are stored - * or deleted. - */ - private void loadEntries() throws IOException { - synchronized (configurationFile) { - entries = new ArrayList(); - if (configurationFile.exists()) { - try (BufferedReader reader = new BufferedReader(new FileReader(configurationFile))) { - String line = reader.readLine(); - while (line != null) { - String trimLine = line.trim(); // can't trim readLine() result - if (trimLine.startsWith(CON_ENTRY)) { - entries.add(readConEntry(reader)); - } else if (trimLine.startsWith(REG_ENTRY)) { - entries.add(readRegEntry(reader)); - } - line = reader.readLine(); - } - } - } else { - if (logger.isLoggable(FINER)) { - logger.log(FINER, "jaspic.factory_file_not_found", - configurationFile.getParent() + File.pathSeparator + configurationFile.getPath()); - } - - for (EntryInfo entry : defaultEntries) { - entries.add(new EntryInfo(entry)); - } - } - } - } - - private EntryInfo readConEntry(BufferedReader reader) throws IOException { - // Entry must contain class name as next line - String className = reader.readLine(); - if (className != null) { - className = className.trim(); - } - - return new EntryInfo(className, readProperties(reader)); - } - - /** - * Properties must be of the form "key:value." While the key String cannot contain a ":" character, the value can. The - * line will be broken into key and value based on the first appearance of the ":" character. - */ - private Map readProperties(BufferedReader reader) throws IOException { - String line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - - if ("}".equals(line)) { - return null; - } - - Map properties = new HashMap(); - while (!"}".equals(line)) { - properties.put(line.substring(0, line.indexOf(SEP)), line.substring(line.indexOf(SEP) + 1, line.length())); - line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - } - - return properties; - } - - private EntryInfo readRegEntry(BufferedReader reader) throws IOException { - String className = null; - Map properties = null; - List ctxs = new ArrayList(); - String line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - while (!"}".equals(line)) { - if (line.startsWith(CON_ENTRY)) { - EntryInfo conEntry = readConEntry(reader); - className = conEntry.getClassName(); - properties = conEntry.getProperties(); - } else if (line.startsWith(REG_CTX)) { - ctxs.add(readRegContext(reader)); - } - line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - - } - return new EntryInfo(className, properties, ctxs); - } - - private RegistrationContext readRegContext(BufferedReader reader) throws IOException { - String layer = null; - String appCtx = null; - String description = null; - String line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - - while (!"}".equals(line)) { - String value = line.substring(line.indexOf(SEP) + 1, line.length()); - if (line.startsWith(LAYER)) { - layer = value; - } else if (line.startsWith(APP_CTX)) { - appCtx = value; - } else if (line.startsWith(DESCRIPTION)) { - description = value; - } - - line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - } - - return new RegistrationContextImpl(layer, appCtx, description, true); - } - - private void logWarningUpdated(Exception exception) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_could_not_persist", exception.toString()); - } - } - - private void logWarningDefault(Exception exception) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_could_not_read", exception.toString()); - } - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java deleted file mode 100644 index f432cd9ab31..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import jakarta.security.auth.message.config.RegistrationListener; - -// Adding package private class because specializing the listener implementation class would -// make the Payara JASPIC (JSR 196) implementation non-replaceable. -// -// This class would hold a RegistrationListener within. -public class AuthConfigRegistrationWrapper { - - private String layer; - private String applicationContextId; - private String jaspicProviderRegistrationId; - private boolean enabled; - private ConfigData data; - - private Lock wLock; - private ReadWriteLock rwLock; - - private AuthConfigRegistrationListener listener; - private int referenceCount = 1; - private RegistrationWrapperRemover removerDelegate; - - public AuthConfigRegistrationWrapper(String layer, String applicationContextId, RegistrationWrapperRemover removerDelegate) { - this.layer = layer; - this.applicationContextId = applicationContextId; - this.removerDelegate = removerDelegate; - this.rwLock = new ReentrantReadWriteLock(true); - this.wLock = rwLock.writeLock(); - - enabled = JaspicServices.factory != null; - listener = new AuthConfigRegistrationListener(layer, applicationContextId); - } - - public AuthConfigRegistrationListener getListener() { - return listener; - } - - public void setListener(AuthConfigRegistrationListener listener) { - this.listener = listener; - } - - public void disable() { - this.wLock.lock(); - - try { - setEnabled(false); - } finally { - this.wLock.unlock(); - data = null; - } - - if (JaspicServices.factory != null) { - JaspicServices.factory.detachListener(this.listener, layer, applicationContextId); - if (getJaspicProviderRegistrationId() != null) { - JaspicServices.factory.removeRegistration(getJaspicProviderRegistrationId()); - } - } - } - - // Detach the listener, but don't remove-registration - public void disableWithRefCount() { - if (referenceCount <= 1) { - disable(); - if (removerDelegate != null) { - removerDelegate.removeListener(this); - } - } else { - try { - this.wLock.lock(); - referenceCount--; - } finally { - this.wLock.unlock(); - } - - } - } - - public void incrementReference() { - try { - this.wLock.lock(); - referenceCount++; - } finally { - this.wLock.unlock(); - } - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getJaspicProviderRegistrationId() { - return this.jaspicProviderRegistrationId; - } - - public void setRegistrationId(String jaspicProviderRegistrationId) { - this.jaspicProviderRegistrationId = jaspicProviderRegistrationId; - } - - public ConfigData getConfigData() { - return data; - } - - public void setConfigData(ConfigData data) { - this.data = data; - } - - public class AuthConfigRegistrationListener implements RegistrationListener { - - private String layer; - private String appCtxt; - - public AuthConfigRegistrationListener(String layer, String appCtxt) { - this.layer = layer; - this.appCtxt = appCtxt; - } - - @Override - public void notify(String layer, String appContext) { - if (this.layer.equals(layer) - && ((this.appCtxt == null && appContext == null) || (appContext != null && appContext.equals(this.appCtxt)))) { - try { - wLock.lock(); - data = null; - } finally { - wLock.unlock(); - } - } - } - - } -} \ No newline at end of file diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java deleted file mode 100644 index 9f3666105ed..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - -import jakarta.security.auth.message.config.AuthConfig; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ServerAuthConfig; - -class ConfigData { - - private AuthConfigProvider provider; - private AuthConfig serverConfig; - private AuthConfig clientConfig; - - ConfigData() { - } - - ConfigData(AuthConfigProvider authConfigProvider, AuthConfig authConfig) { - provider = authConfigProvider; - - if (authConfig == null) { - serverConfig = null; - clientConfig = null; - } else if (authConfig instanceof ServerAuthConfig) { - serverConfig = authConfig; - } else if (authConfig instanceof ClientAuthConfig) { - clientConfig = authConfig; - } else { - throw new IllegalArgumentException(); - } - } - - public AuthConfigProvider getProvider() { - return provider; - } - - public AuthConfig getServerConfig() { - return serverConfig; - } - - public AuthConfig getClientConfig() { - return clientConfig; - } -} \ No newline at end of file diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java deleted file mode 100644 index 5659f9186ff..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.config.AuthConfig; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; - -/** - * This is based Helper class for 196 Configuration. - */ -public abstract class JaspicServices { - - protected static final AuthConfigFactory factory = AuthConfigFactory.getFactory(); - - private ReadWriteLock readWriteLock; - private Lock readLock; - private Lock writeLock; - - protected String layer; - protected String appCtxt; - protected Map map; - protected CallbackHandler callbackHandler; - protected AuthConfigRegistrationWrapper listenerWrapper; - - protected void init(String layer, String appContext, Map map, CallbackHandler callbackHandler, RegistrationWrapperRemover removerDelegate) { - this.layer = layer; - this.appCtxt = appContext; - this.map = map; - this.callbackHandler = callbackHandler; - if (this.callbackHandler == null) { - this.callbackHandler = getCallbackHandler(); - } - - this.readWriteLock = new ReentrantReadWriteLock(true); - this.readLock = readWriteLock.readLock(); - this.writeLock = readWriteLock.writeLock(); - - listenerWrapper = new AuthConfigRegistrationWrapper(this.layer, this.appCtxt, removerDelegate); - } - - public void setRegistrationId(String registrationId) { - listenerWrapper.setRegistrationId(registrationId); - } - - public AuthConfigRegistrationWrapper getRegistrationWrapper() { - return listenerWrapper; - } - - public void setRegistrationWrapper(AuthConfigRegistrationWrapper wrapper) { - this.listenerWrapper = wrapper; - } - - public AuthConfigRegistrationWrapper.AuthConfigRegistrationListener getRegistrationListener() { - return listenerWrapper.getListener(); - } - - public void disable() { - listenerWrapper.disable(); - } - - public Object getProperty(String key) { - return map == null ? null : map.get(key); - } - - public String getAppContextID() { - return appCtxt; - } - - public ClientAuthConfig getClientAuthConfig() throws AuthException { - return (ClientAuthConfig) getAuthConfig(false); - } - - public ServerAuthConfig getServerAuthConfig() throws AuthException { - return (ServerAuthConfig) getAuthConfig(true); - } - - public ClientAuthContext getClientAuthContext(MessageInfo info, Subject clientSubject) throws AuthException { - ClientAuthConfig clientConfig = (ClientAuthConfig) getAuthConfig(false); - if (clientConfig != null) { - return clientConfig.getAuthContext(clientConfig.getAuthContextID(info), clientSubject, map); - } - - return null; - } - - public ServerAuthContext getServerAuthContext(MessageInfo info, Subject serviceSubject) throws AuthException { - ServerAuthConfig serverAuthConfig = (ServerAuthConfig) getAuthConfig(true); - if (serverAuthConfig != null) { - return serverAuthConfig.getAuthContext(serverAuthConfig.getAuthContextID(info), serviceSubject, map); - } - - return null; - } - - protected AuthConfig getAuthConfig(AuthConfigProvider authConfigProvider, boolean isServer) throws AuthException { - AuthConfig authConfig = null; - - if (authConfigProvider != null) { - if (isServer) { - authConfig = authConfigProvider.getServerAuthConfig(layer, appCtxt, callbackHandler); - } else { - authConfig = authConfigProvider.getClientAuthConfig(layer, appCtxt, callbackHandler); - } - } - - return authConfig; - } - - protected AuthConfig getAuthConfig(boolean isServer) throws AuthException { - - ConfigData configData = null; - AuthConfig authConfig = null; - boolean disabled = false; - AuthConfigProvider lastConfigProvider = null; - - try { - readLock.lock(); - disabled = !listenerWrapper.isEnabled(); - if (!disabled) { - configData = listenerWrapper.getConfigData(); - if (configData != null) { - authConfig = isServer ? configData.getServerConfig() : configData.getClientConfig(); - lastConfigProvider = configData.getProvider(); - } - } - - } finally { - readLock.unlock(); - if (disabled || authConfig != null || (configData != null && lastConfigProvider == null)) { - return authConfig; - } - } - - // d == null || (d != null && lastP != null && c == null) - if (configData == null) { - try { - writeLock.lock(); - if (listenerWrapper.getConfigData() == null) { - AuthConfigProvider nextConfigProvider = factory.getConfigProvider(layer, appCtxt, getRegistrationListener()); - - if (nextConfigProvider != null) { - listenerWrapper.setConfigData(new ConfigData(nextConfigProvider, getAuthConfig(nextConfigProvider, isServer))); - } else { - listenerWrapper.setConfigData(new ConfigData()); - } - } - configData = listenerWrapper.getConfigData(); - } finally { - writeLock.unlock(); - } - } - - return isServer ? configData.getServerConfig() : configData.getClientConfig(); - } - - /** - * Check if there is a provider register for a given layer and appCtxt. - */ - protected boolean hasExactMatchAuthProvider() { - boolean exactMatch = false; - - AuthConfigProvider configProvider = factory.getConfigProvider(layer, appCtxt, null); - - if (configProvider != null) { - for (String registrationId : factory.getRegistrationIDs(configProvider)) { - RegistrationContext registrationContext = factory.getRegistrationContext(registrationId); - if (layer.equals(registrationContext.getMessageLayer()) && appCtxt.equals(registrationContext.getAppContext())) { - exactMatch = true; - break; - } - } - } - - return exactMatch; - } - - /** - * Get the callback default handler - */ - protected CallbackHandler getCallbackHandler() { - return null; - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java deleted file mode 100644 index b593a72f2fc..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - - -public interface RegistrationWrapperRemover { - - /** - * remove the registration of the argument listener from the Pipe - * - * @param listener - */ - void removeListener(AuthConfigRegistrationWrapper listener); - -} diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java index 80b2cc68850..253eb82236e 100644 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java +++ b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package test.com.sun.jaspic.config; import java.util.concurrent.TimeUnit; @@ -48,9 +48,6 @@ import java.util.ArrayList; import java.util.List; import com.sun.jaspic.config.factory.EntryInfo; -import com.sun.jaspic.config.factory.AuthConfigFileFactory; -import com.sun.jaspic.config.factory.BaseAuthConfigFactory; -import com.sun.jaspic.config.factory.RegStoreFileParser; import java.security.Security; import org.junit.After; import java.util.HashMap; diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java index 038205a47a1..c8eefa5cb4a 100644 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java +++ b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java @@ -37,10 +37,9 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package test.com.sun.jaspic.config; -import com.sun.jaspic.config.factory.AuthConfigFileFactory; import com.sun.jaspic.config.servlet.JAASServletAuthConfigProvider; import java.io.IOException; import java.util.HashMap; @@ -59,6 +58,7 @@ import jakarta.security.auth.message.config.RegistrationListener; import jakarta.security.auth.message.config.ServerAuthConfig; import jakarta.security.auth.message.config.ServerAuthContext; +import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; /** * diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java index 67d9670a191..006e6423399 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package com.sun.web.security.realmadapter; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.AUTH_TYPE; @@ -93,7 +93,7 @@ import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.security.SecurityContext; -import com.sun.enterprise.security.jaspic.config.PayaraJaspicServletServices; +import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServletServices; import com.sun.enterprise.security.web.integration.WebPrincipal; import com.sun.jaspic.config.servlet.HttpMessageInfo; import com.sun.logging.LogDomains; @@ -130,7 +130,7 @@ public class JaspicRealm { private Container virtualServer; - private PayaraJaspicServletServices jaspicServices; + private PayaraEpicyroServletServices jaspicServices; private AtomicBoolean initialised = new AtomicBoolean(); public JaspicRealm(String realmName, boolean isSystemApp, WebBundleDescriptor webDescriptor, RequestTracingService requestTracing) { @@ -291,11 +291,11 @@ private ServerAuthContext getServerAuthContext(MessageInfo messageInfo) throws A /** * This must be invoked after virtualServer is set. */ - private PayaraJaspicServletServices getConfigHelper(ServletContext servletContext) { + private PayaraEpicyroServletServices getConfigHelper(ServletContext servletContext) { Map map = new HashMap<>(); map.put(WEB_BUNDLE, webDescriptor); - return new PayaraJaspicServletServices( + return new PayaraEpicyroServletServices( getAppContextID(servletContext), map, null, // null handler realmName, isSystemApp, jaspicSystemConfigProviderID); } diff --git a/appserver/security/webservices.security/pom.xml b/appserver/security/webservices.security/pom.xml index cad7aae0333..9e7992bd46c 100644 --- a/appserver/security/webservices.security/pom.xml +++ b/appserver/security/webservices.security/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -144,5 +144,15 @@ logging-annotation-processor true + + org.glassfish.epicyro + epicyro + + + fish.payara.server.internal.security + appclient.security + ${project.version} + true + diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java index 1bd4684ad53..08b59322298 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java @@ -37,17 +37,19 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jauth.jaspic.provider.config; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getMessageSecurityBinding; import static com.sun.enterprise.security.webservices.PipeConstants.BINDING; import static com.sun.enterprise.security.webservices.PipeConstants.ENDPOINT; import static com.sun.enterprise.security.webservices.PipeConstants.SEI_MODEL; import static com.sun.enterprise.security.webservices.PipeConstants.SERVICE_ENDPOINT; -import static com.sun.enterprise.security.webservices.PipeConstants.SOAP_LAYER; import static com.sun.xml.ws.api.SOAPVersion.SOAP_11; +import com.sun.enterprise.security.appclient.ConfigXMLParser; +import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; +import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; +import jakarta.security.auth.message.MessagePolicy; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; @@ -55,6 +57,8 @@ import java.security.PrivilegedExceptionAction; import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import jakarta.security.auth.message.AuthException; @@ -72,6 +76,8 @@ import org.glassfish.api.invocation.ComponentInvocation; import org.glassfish.api.invocation.InvocationManager; import org.glassfish.deployment.common.ModuleDescriptor; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; import org.glassfish.internal.api.Globals; import com.sun.enterprise.deployment.Application; @@ -88,10 +94,9 @@ import com.sun.enterprise.security.common.ClientSecurityContext; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; import com.sun.enterprise.security.ee.authorize.EJBPolicyContextDelegate; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; import com.sun.enterprise.security.jaspic.config.HandlerContext; -import com.sun.enterprise.security.jaspic.config.PayaraJaspicServices; +import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServices; import com.sun.enterprise.security.webservices.PipeConstants; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.io.FileUtils; @@ -106,7 +111,7 @@ import com.sun.xml.ws.api.model.wsdl.WSDLPort; import com.sun.xml.ws.api.server.WSEndpoint; -public class PipeHelper extends PayaraJaspicServices { +public class PipeHelper extends PayaraEpicyroServices { protected static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(PipeConstants.class); @@ -118,7 +123,7 @@ public class PipeHelper extends PayaraJaspicServices { private EJBPolicyContextDelegate ejbDelegate; public PipeHelper(String layer, Map properties, CallbackHandler callbackHandler) { - init(layer, getAppCtxt(properties), properties, callbackHandler, Globals.get(WebServicesDelegate.class)); + init(layer, getAppCtxt(properties), properties, callbackHandler, (RegistrationWrapperRemover) Globals.get(WebServicesDelegate.class)); isEjbEndpoint = processSunDeploymentDescriptor(); seiModel = (SEIModel) properties.get(SEI_MODEL); @@ -402,24 +407,44 @@ public String getRealmName() { } private boolean processSunDeploymentDescriptor() { - if (factory == null) { + if (authConfigFactory == null) { return false; } - MessageSecurityBindingDescriptor binding = getMessageSecurityBinding(SOAP_LAYER, map); + MessageSecurityBindingDescriptor binding = AuthMessagePolicy.getMessageSecurityBinding(com.sun.xml.wss.provider.wsit.PipeConstants.SOAP_LAYER, map); + + Function authContextIdGenerator = + e -> Globals.get(WebServicesDelegate.class).getAuthContextID(e); + + BiFunction, MessagePolicy[]> soapPolicyGenerator = + (authContextId, properties) -> AuthMessagePolicy.getSOAPPolicies( + AuthMessagePolicy.getMessageSecurityBinding("SOAP", properties), + authContextId, true); + + String authModuleId = AuthMessagePolicy.getProviderID(binding); + + map.put("authContextIdGenerator", authContextIdGenerator); + map.put("soapPolicyGenerator", soapPolicyGenerator); + + if (authModuleId != null) { + map.put("authModuleId", authModuleId); + } if (binding != null) { if (!hasExactMatchAuthProvider()) { - String jaspicProviderRegisID = factory.registerConfigProvider( - new GFServerConfigProvider(null, null), - layer, appCtxt, "GF AuthConfigProvider bound by Sun Specific Descriptor"); - - setRegistrationId(jaspicProviderRegisID); + String jmacProviderRegisID = authConfigFactory.registerConfigProvider( + new GFServerConfigProvider( + map, + isACC()? new ConfigXMLParser() : new ConfigDomainParser(), + authConfigFactory), + messageLayer, appContextId, + "GF AuthConfigProvider bound by Sun Specific Descriptor"); + + setRegistrationId(jmacProviderRegisID); } } WebServiceEndpoint webServiceEndpoint = (WebServiceEndpoint) map.get(SERVICE_ENDPOINT); - return webServiceEndpoint == null ? false : webServiceEndpoint.implementedByEjbComponent(); } @@ -538,4 +563,8 @@ private String ejbName() { WebServiceEndpoint wSE = (WebServiceEndpoint) getProperty(PipeConstants.SERVICE_ENDPOINT); return (wSE == null ? "unknown" : wSE.getEjbComponentImpl().getName()); } + + private static boolean isACC() { + return SecurityServicesUtil.getInstance() == null || SecurityServicesUtil.getInstance().isACC(); + } } diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java index 162a55e99f3..62c7771236a 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static java.util.Collections.synchronizedMap; @@ -47,7 +47,7 @@ import java.util.WeakHashMap; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.jaspic.services.AuthConfigRegistrationWrapper; +import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; public class ClientPipeCloser { diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java index a0421be7125..f06686cfe72 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2022] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static com.sun.enterprise.security.webservices.PipeConstants.ASSEMBLER_CONTEXT; @@ -53,7 +53,7 @@ import java.util.HashMap; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.jaspic.services.AuthConfigRegistrationWrapper; +import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; import com.sun.xml.ws.api.pipe.ClientPipeAssemblerContext; import com.sun.xml.ws.api.pipe.Pipe; import com.sun.xml.ws.assembler.metro.dev.ClientPipelineHook; diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java index 554546d1ce7..e0145fad991 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import java.util.Iterator; @@ -63,11 +63,11 @@ import com.sun.enterprise.deployment.ServiceRefPortInfo; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; import com.sun.enterprise.security.jauth.AuthParam; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.SOAPAuthParam; -import com.sun.jaspic.services.AuthConfigRegistrationWrapper; +import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; import com.sun.xml.ws.api.message.Message; import com.sun.xml.ws.api.message.Packet; import com.sun.xml.ws.api.model.wsdl.WSDLBoundOperation; diff --git a/core/core-parent/pom.xml b/core/core-parent/pom.xml index 1d9c8d6e823..91f51bb3ba8 100644 --- a/core/core-parent/pom.xml +++ b/core/core-parent/pom.xml @@ -617,6 +617,8 @@ io.opentelemetry.extension io.opentelemetry.instrumentation fish.payara.shaded + com.sun.enterprise.security + com.sun.jaspic.services diff --git a/core/pom.xml b/core/pom.xml index 0966a83c81d..b54cf459fe4 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -123,6 +123,7 @@ 1.0 4.12.0 2.0.20 + 3.1.0 3.2.3.payara-p1 @@ -913,6 +914,11 @@ jakarta.authentication-api ${jakarta.authentication-api.version} + + org.glassfish.epicyro + epicyro + ${epyciro.version} + jakarta.persistence jakarta.persistence-api diff --git a/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java b/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java index 84705677cb5..de361201707 100644 --- a/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java +++ b/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019] Payara Foundation and/or affiliates +// Portions Copyright [2019-2024] Payara Foundation and/or affiliates package org.glassfish.deployment.common; @@ -88,11 +88,11 @@ public void addExtraAttribute(String name, Object value) { * @param name the attribute name * @return the attribute value of null of non existent */ - public Object getExtraAttribute(String name) { + public T getExtraAttribute(String name) { if (dynamicAttributes == null) { return null; } - return dynamicAttributes.get(name); + return (T) dynamicAttributes.get(name); } /** diff --git a/nucleus/security/core/pom.xml b/nucleus/security/core/pom.xml index b56a19b9c31..7c5f5896585 100644 --- a/nucleus/security/core/pom.xml +++ b/nucleus/security/core/pom.xml @@ -39,7 +39,7 @@ only if the new code is made subject to such option by the copyright holder. - Portions Copyright [2019-2022] [Payara Foundation and/or its affiliates] + Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] --> logging-annotation-processor true + + org.glassfish.epicyro + epicyro + org.javassist javassist diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java index 677f8758199..6d6b8b22368 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; import static com.sun.enterprise.security.SecurityLoggerInfo.noPwdCredentialProvidedError; @@ -58,10 +58,10 @@ import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; - +import org.glassfish.epicyro.config.helper.CallerPrincipal; import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; + import com.sun.enterprise.security.auth.login.LoginCallbackHandler; import com.sun.enterprise.security.auth.login.common.PasswordCredential; @@ -98,7 +98,7 @@ public abstract class BasePasswordLoginModule implements LoginModule { // the authentication status protected boolean _succeeded; protected boolean _commitSucceeded; - protected PrincipalImpl _userPrincipal; + protected CallerPrincipal _userPrincipal; protected String[] _groupsList; /** @@ -169,7 +169,7 @@ public boolean commit() throws LoginException { if (factory != null) { _userPrincipal = factory.getPrincipalInstance(getUsername(), realmName); } else { - _userPrincipal = new PrincipalImpl(getUsername()); + _userPrincipal = new CallerPrincipal(getUsername()); } Set principals = _subject.getPrincipals(); @@ -444,7 +444,7 @@ public boolean isCommitSucceeded() { /** * @return the UserPrincipal - for backward compatibility */ - public PrincipalImpl getUserPrincipal() { + public CallerPrincipal getUserPrincipal() { return _userPrincipal; } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java index 01ecb60710c..54b50e11022 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java @@ -37,11 +37,11 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2017-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.epicyro.config.helper.CallerPrincipal; import org.jvnet.hk2.annotations.Contract; /** @@ -50,7 +50,7 @@ @Contract public interface PrincipalGroupFactory { - PrincipalImpl getPrincipalInstance(String name, String realm); + CallerPrincipal getPrincipalInstance(String name, String realm); Group getGroupInstance(String name, String realm); } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java index 56a48d9063a..7c790c0aff9 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2021] Payara Services Ltd. +// Portions Copyright [2021-2024] Payara Services Ltd. package com.sun.enterprise.security.audit; @@ -193,7 +193,6 @@ public void loadAuditModules() { * Add the given audit module to the list of loaded audit module. * Adding the same name twice will override previous one. * @param name of auditModule - * @param am an instance of a class extending BaseAuditModule that has been * successfully loaded into the system. * @exception */ @@ -284,7 +283,6 @@ public Logger getLogger() { /** * logs the authentication call for all the loaded modules. - * @see com.sun.appserv.security.BaseAuditModule.authentication */ @Override public void authentication(final String user, final String realm, final boolean success){ diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java index 4ea09f6432c..b1706ca12f1 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.common; import java.security.Principal; @@ -74,8 +74,8 @@ public final class ClientSecurityContext extends AbstractSecurityContext { /** * This creates a new ClientSecurityContext object. * - * @param The name of the user. - * @param The Credentials of the user. + * @param username name of the user. + * @param subject Credentials of the user. */ public ClientSecurityContext(String username, Subject subject) { this.callerPrincipal = new PrincipalImpl(username); @@ -101,7 +101,6 @@ public static ClientSecurityContext getCurrent() { /** * This method sets the SecurityContext to be stored here. * - * @param The Security Context that should be stored. */ public static void setCurrent(ClientSecurityContext clientSecurityContext) { if (isPerThreadAuth) { From 911a08b81ad1cbd1fb9abf2ecd75e37fc47f93f5 Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Wed, 13 Nov 2024 16:52:24 +0000 Subject: [PATCH 02/34] Security API downgrade shim Signed-off-by: Andrew Pielage --- .../external/jakarta-ee11-shim/pom.xml | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/appserver/packager/external/jakarta-ee11-shim/pom.xml b/appserver/packager/external/jakarta-ee11-shim/pom.xml index 3c946f5f268..7ad63f09bf0 100644 --- a/appserver/packager/external/jakarta-ee11-shim/pom.xml +++ b/appserver/packager/external/jakarta-ee11-shim/pom.xml @@ -91,6 +91,13 @@ jakarta.ws.rs-api provided + + + + jakarta.security.enterprise + jakarta.security.enterprise-api + provided + @@ -124,7 +131,9 @@ jakarta.security.jacc-api, - jakarta.ws.rs-api + jakarta.ws.rs-api, + + jakarta.security.enterprise-api + jakarta.security.enterprise; + jakarta.security.enterprise.authentication.mechanism.http; + jakarta.security.enterprise.authentication.mechanism.http.openid; + jakarta.security.enterprise.credential; + jakarta.security.enterprise.identitystore; + jakarta.security.enterprise.identitystore.openid;version="3.0.99";shim=true From b51a9ffe1123dac65d6330a9f77adbda4d638f93 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Wed, 30 Oct 2024 23:45:30 -0600 Subject: [PATCH 03/34] FISH-8925: rebasing last changes from Payara7 branch --- appserver/connectors/work-management/pom.xml | 7 +- .../context/ConnectorCallbackHandler.java | 8 +- .../deployment/runtime/RuntimeDescriptor.java | 4 +- .../glassfish/ejb/startup/EjbDeployer.java | 2 +- .../appclient/AppClientSecurityInfoImpl.java | 6 +- .../security/appclient/ConfigXMLParser.java | 49 +- appserver/security/core-ee/pom.xml | 6 +- .../security/ee/JavaEESecurityLifecycle.java | 89 +- .../ee/auth/login/DigestLoginModule.java | 6 +- .../jakarta/AuthMessagePolicy.java | 238 +++++ .../jakarta}/ConfigDomainParser.java | 44 +- .../jakarta}/WebServicesDelegate.java | 6 +- .../security/ee/authorize}/PolicyLoader.java | 3 +- .../jacc/JaccWebAuthorizationManager.java | 3 +- .../security/jacc/package-info.java | 4 +- .../security/jaspic/AuthMessagePolicy.java | 334 ------ ...essageSecurityConfigEventListenerImpl.java | 76 +- .../security/jaspic/config/ConfigParser.java | 101 -- .../jaspic/config/GFAuthConfigFactory.java | 126 --- .../jaspic/config/GFServerConfigProvider.java | 981 ------------------ ...rvices.java => PayaraEpicyroServices.java} | 8 +- ...java => PayaraEpicyroServletServices.java} | 17 +- .../enterprise/security/jauth/ConfigFile.java | 619 ----------- .../PrincipalGroupFactoryImpl.java | 10 +- .../jaspic-provider-framework/osgi.bundle | 4 +- .../jaspic-provider-framework/pom.xml | 6 +- .../config/factory/AuthConfigFileFactory.java | 89 -- .../config/factory/BaseAuthConfigFactory.java | 728 ------------- .../config/factory/RegStoreFileParser.java | 454 -------- .../AuthConfigRegistrationWrapper.java | 180 ---- .../com/sun/jaspic/services/ConfigData.java | 83 -- .../sun/jaspic/services/JaspicServices.java | 237 ----- .../services/RegistrationWrapperRemover.java | 53 - .../com/sun/jaspic/config/FactoryTest.java | 5 +- .../sun/jaspic/config/RuntimeSurrogate.java | 4 +- .../security/realmadapter/JaspicRealm.java | 10 +- .../security/webservices.security/pom.xml | 12 +- .../jaspic/provider/config/PipeHelper.java | 61 +- .../webservices/ClientPipeCloser.java | 4 +- .../webservices/ClientPipeCreator.java | 4 +- .../webservices/WebServicesDelegateImpl.java | 6 +- core/core-parent/pom.xml | 2 + core/pom.xml | 6 + .../common/DynamicAttributesDescriptor.java | 6 +- nucleus/security/core/pom.xml | 6 +- .../security/BasePasswordLoginModule.java | 12 +- .../security/PrincipalGroupFactory.java | 6 +- .../security/audit/BaseAuditManager.java | 4 +- .../common/ClientSecurityContext.java | 7 +- 49 files changed, 527 insertions(+), 4209 deletions(-) create mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic/config => ee/authentication/jakarta}/ConfigDomainParser.java (86%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic => ee/authentication/jakarta}/WebServicesDelegate.java (95%) rename {nucleus/security/core/src/main/java/com/sun/enterprise/security => appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize}/PolicyLoader.java (99%) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/{PayaraJaspicServices.java => PayaraEpicyroServices.java} (91%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/{PayaraJaspicServletServices.java => PayaraEpicyroServletServices.java} (86%) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java diff --git a/appserver/connectors/work-management/pom.xml b/appserver/connectors/work-management/pom.xml index 9925f728c2d..1687e63df76 100644 --- a/appserver/connectors/work-management/pom.xml +++ b/appserver/connectors/work-management/pom.xml @@ -39,7 +39,7 @@ holder. --> - + 4.0.0 @@ -148,5 +148,10 @@ logging-annotation-processor true + + + org.glassfish.epicyro + epicyro + diff --git a/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java b/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java index a259af6a339..fcd5da07d55 100644 --- a/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java +++ b/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.connectors.work.context; import com.sun.enterprise.security.SecurityContext; @@ -45,7 +45,7 @@ import org.glassfish.logging.annotation.LogMessageInfo; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.epicyro.config.helper.CallerPrincipal; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -276,12 +276,12 @@ public Callback handleCallerPrincipalCallbackWithMapping(CallerPrincipalCallback private Principal getMappedPrincipal(Principal eisPrincipal, String eisName) { Principal asPrincipal = null; if (eisPrincipal != null) { - asPrincipal = (PrincipalImpl) securityMap.get(eisPrincipal); + asPrincipal = (CallerPrincipal) securityMap.get(eisPrincipal); if(logger.isLoggable(Level.FINEST)){ logger.finest("got mapped principal as [" + asPrincipal + "] for eis-group [" + eisPrincipal.getName() + "]"); } } else if (eisName != null) { - asPrincipal = ((PrincipalImpl) securityMap.get(new PrincipalImpl(eisName))); + asPrincipal = ((CallerPrincipal) securityMap.get(new CallerPrincipal(eisName))); if(logger.isLoggable(Level.FINEST)){ logger.finest("got mapped principal as [" + asPrincipal + "] for eis-group [" + eisName + "]"); } diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java index 7b89d2bc908..1be283f8542 100644 --- a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2020] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.deployment.runtime; @@ -121,7 +121,7 @@ public void setValue(String name, Object value) { /** * @return a property value */ - public Object getValue(String name) { + public T getValue(String name) { return getExtraAttribute(name); } diff --git a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java index 46326ada624..207f4258b46 100644 --- a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java +++ b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java @@ -89,7 +89,7 @@ import com.sun.enterprise.deployment.Application; import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.module.bootstrap.StartupContext; -import com.sun.enterprise.security.PolicyLoader; +import com.sun.enterprise.security.ee.authorize.PolicyLoader; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.util.IASSecurityException; import com.sun.enterprise.util.LocalStringManagerImpl; diff --git a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java index 7cc9ff43c2c..e5fd188d81e 100644 --- a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java +++ b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2022] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.appclient; import com.sun.enterprise.security.SecurityServicesUtil; @@ -50,7 +50,6 @@ import com.sun.enterprise.security.common.Util; import com.sun.enterprise.security.ee.J2EESecurityManager; import com.sun.enterprise.security.integration.AppClientSSL; -import com.sun.enterprise.security.jaspic.config.GFAuthConfigFactory; import com.sun.enterprise.security.ssl.SSLUtils; import com.sun.logging.LogDomains; import jakarta.inject.Inject; @@ -60,6 +59,7 @@ import org.glassfish.appclient.client.acc.config.Ssl; import org.glassfish.appclient.client.acc.config.TargetServer; import org.glassfish.enterprise.iiop.api.IIOPSSLUtil; +import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; import org.jvnet.hk2.annotations.Service; import javax.security.auth.Subject; @@ -147,7 +147,7 @@ public void initializeSecurity( if (defaultFactory == null) { java.security.Security.setProperty (AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY, - GFAuthConfigFactory.class.getName()); + AuthConfigFileFactory.class.getName()); } } catch (Exception e) { diff --git a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java index ec0352c1261..197b75e9db2 100644 --- a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java +++ b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java @@ -37,15 +37,12 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright 2019-2022 Payara Foundation and/or its affiliates +// Portions Copyright 2019-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.security.appclient; import com.sun.enterprise.security.common.Util; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; -import com.sun.enterprise.security.jaspic.config.ConfigParser; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; import com.sun.logging.LogDomains; import jakarta.security.auth.message.MessagePolicy; import jakarta.xml.bind.JAXBContext; @@ -57,6 +54,10 @@ import org.glassfish.appclient.client.acc.config.ProviderConfig; import org.glassfish.appclient.client.acc.config.RequestPolicy; import org.glassfish.appclient.client.acc.config.ResponsePolicy; +import org.glassfish.epicyro.config.factory.ConfigParser; +import org.glassfish.epicyro.config.helper.AuthMessagePolicy; +import org.glassfish.epicyro.data.AuthModuleConfig; +import org.glassfish.epicyro.data.AuthModulesLayerConfig; import org.glassfish.internal.api.Globals; import java.io.FileInputStream; @@ -83,22 +84,22 @@ public class ConfigXMLParser implements ConfigParser { private static Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{\\{(.*?)}}|\\$\\{(.*?)}"); // configuration info - private Map configMap = new HashMap(); + private final Map authModuleLayers = new HashMap<>(); private Set layersWithDefault = new HashSet(); private List msgSecConfigs = null; private static final String ACC_XML = "glassfish-acc.xml.url"; - public ConfigXMLParser() throws IOException { + public ConfigXMLParser() { } public void initialize(List msgConfigs) throws IOException { this.msgSecConfigs = msgConfigs; if (this.msgSecConfigs != null) { - processClientConfigContext(configMap); + processClientConfigContext(authModuleLayers); } } - private void processClientConfigContext(Map newConfig) throws IOException { + private void processClientConfigContext(Map newConfig) throws IOException { // auth-layer String intercept = null; @@ -113,16 +114,12 @@ private void processClientConfigContext(Map newConfig) throws IOException { } } - - public Map getConfigMap() { - return configMap; - } - + public Set getLayersWithDefault() { return layersWithDefault; } - private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { + private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { String intercept = null; String defaultServerID = null; String defaultClientID = null; @@ -140,19 +137,19 @@ private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfi layersWithDefault.add(intercept); } - GFServerConfigProvider.InterceptEntry intEntry = (GFServerConfigProvider.InterceptEntry) newConfig.get(intercept); + AuthModulesLayerConfig intEntry = newConfig.get(intercept); if (intEntry != null) { throw new IOException("found multiple MessageSecurityConfig " + "entries with the same auth-layer"); } // create new intercept entry - intEntry = new GFServerConfigProvider.InterceptEntry(defaultClientID, defaultServerID, null); + intEntry = new AuthModulesLayerConfig(defaultClientID, defaultServerID, null); newConfig.put(intercept, intEntry); return intercept; } // duplicate implementation for clientbeans config - private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercept) throws IOException { + private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercept) throws IOException { String id = pConfig.getProviderId(); String type = pConfig.getProviderType(); String moduleClass = pConfig.getClassName(); @@ -183,20 +180,21 @@ private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercep // create ID entry - GFServerConfigProvider.IDEntry idEntry = new GFServerConfigProvider.IDEntry(type, moduleClass, requestPolicy, - responsePolicy, options); + //GFServerConfigProvider.IDEntry idEntry = new GFServerConfigProvider.IDEntry(type, moduleClass, requestPolicy, + // responsePolicy, options); + AuthModuleConfig idEntry = new AuthModuleConfig(type, moduleClass, requestPolicy, responsePolicy, options); - GFServerConfigProvider.InterceptEntry intEntry = (GFServerConfigProvider.InterceptEntry) newConfig.get(intercept); + AuthModulesLayerConfig intEntry = newConfig.get(intercept); if (intEntry == null) { throw new IOException("intercept entry for " + intercept + " must be specified before ID entries"); } - if (intEntry.getIdMap() == null) { - intEntry.setIdMap(new HashMap()); + if (intEntry.getAuthModules() == null) { + intEntry.setIdMap(new HashMap<>()); } // map id to Intercept - intEntry.getIdMap().put(id, idEntry); + intEntry.getAuthModules().put(id, idEntry); } private String expand(String rawProperty) { @@ -270,4 +268,9 @@ public void initialize(Object config) throws IOException { this.initialize(msgconfigs); } + + @Override + public Map getAuthModuleLayers() { + return this.authModuleLayers; + } } diff --git a/appserver/security/core-ee/pom.xml b/appserver/security/core-ee/pom.xml index 0f7f0f28bf1..3172d64f9c3 100644 --- a/appserver/security/core-ee/pom.xml +++ b/appserver/security/core-ee/pom.xml @@ -41,7 +41,7 @@ --> - + 4.0.0 @@ -282,5 +282,9 @@ org.glassfish.exousia exousia + + org.glassfish.epicyro + epicyro + diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java index 6a33dc32c3e..fb41dad5358 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java @@ -37,26 +37,39 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.ee; import com.sun.enterprise.security.ContainerSecurityLifecycle; -import com.sun.enterprise.security.jaspic.config.GFAuthConfigFactory; +import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; +import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; +import com.sun.enterprise.security.ee.authorize.PolicyLoader; import com.sun.logging.LogDomains; +import jakarta.inject.Inject; +import jakarta.security.auth.message.MessageInfo; +import jakarta.security.auth.message.MessagePolicy; +import java.security.Provider; import java.security.Security; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; import java.util.logging.Logger; import jakarta.inject.Singleton; import org.glassfish.common.util.Constants; +import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import org.glassfish.hk2.api.PostConstruct; import org.glassfish.hk2.api.Rank; +import org.glassfish.internal.api.Globals; import org.glassfish.internal.api.InitRunLevel; import org.jvnet.hk2.annotations.Service; -import static java.util.logging.Level.WARNING; import static jakarta.security.auth.message.config.AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY; +import static org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory.DEFAULT_FACTORY_DEFAULT_PROVIDERS; /** @@ -71,42 +84,62 @@ public class JavaEESecurityLifecycle implements ContainerSecurityLifecycle, Post private static final Logger LOG = LogDomains.getLogger(JavaEESecurityLifecycle.class, LogDomains.SECURITY_LOGGER); + @Inject + PolicyLoader policyLoader; + @Override public void postConstruct() { onInitialization(); } - @Override public void onInitialization() { - LOG.finest(() -> "Initializing " + getClass()); - - // TODO: Need some way to not override the security manager if the EmbeddedServer was - // run with a different non-default security manager. - // - // Right now there seems no way to find out if the security manager is the VM's default security manager. - final SecurityManager systemSecurityManager = System.getSecurityManager(); - if (systemSecurityManager != null && !(J2EESecurityManager.class.equals(systemSecurityManager.getClass()))) { - J2EESecurityManager eeSecurityManager = new J2EESecurityManager(); - try { - System.setSecurityManager(eeSecurityManager); - LOG.config(() -> "System security manager has been set to " + eeSecurityManager); - } catch (SecurityException ex) { - LOG.log(WARNING, "security.secmgr.could.not.override", ex); - } - } - initializeJASPIC(); + initializeJakartaAuthentication(); + initializeJakartaAuthorization(); } - private void initializeJASPIC() { + private void initializeJakartaAuthentication() { + // Define default factory if it is not already defined. - // The factory will be constructed on the first getFactory call. - final String defaultFactory = Security.getProperty(DEFAULT_FACTORY_SECURITY_PROPERTY); + // The factory will be constructed on first getFactory call. + + String defaultFactory = Security.getProperty(DEFAULT_FACTORY_SECURITY_PROPERTY); if (defaultFactory == null) { - final String defaultAuthConfigProvideFactoryClassName = GFAuthConfigFactory.class.getName(); - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, defaultAuthConfigProvideFactoryClassName); - LOG.config(() -> String.format("System JVM option '%s' has been set to '%s'", - DEFAULT_FACTORY_SECURITY_PROPERTY, defaultAuthConfigProvideFactoryClassName)); + Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, AuthConfigFileFactory.class.getName()); + } + + String defaultProvidersString = null; + WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); + if (delegate == null) { + defaultProvidersString = GFServerConfigProvider.class.getName(); + } else { + // NOTE: Order matters here. Providers for the same auth layer (HttpServlet or SOAP) will be overwritten + // by ones that appear later in this string without warning. + defaultProvidersString = delegate.getDefaultWebServicesProvider() + " " + GFServerConfigProvider.class.getName(); } + + Security.setProperty(DEFAULT_FACTORY_DEFAULT_PROVIDERS, defaultProvidersString); + + Function authContextIdGenerator = + e -> Globals.get(WebServicesDelegate.class).getAuthContextID(e); + + BiFunction, MessagePolicy[]> soapPolicyGenerator = + (authContextId, properties) -> AuthMessagePolicy.getSOAPPolicies( + AuthMessagePolicy.getMessageSecurityBinding("SOAP", properties), + authContextId, true); + + Provider provider = new Provider("EleosProvider", "1.0", "") { + private static final long serialVersionUID = 1L; + }; + provider.put("authContextIdGenerator", authContextIdGenerator); + provider.put("soapPolicyGenerator", soapPolicyGenerator); + + Security.addProvider(provider); + + System.setProperty("config.parser", ConfigDomainParser.class.getName()); + } + + private void initializeJakartaAuthorization() { + policyLoader.loadPolicy(); } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java index 558144aaa21..3fe8835a307 100755 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.ee.auth.login; import static com.sun.logging.LogDomains.SECURITY_LOGGER; @@ -58,7 +58,7 @@ import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.epicyro.config.helper.CallerPrincipal; import com.sun.enterprise.security.PrincipalGroupFactory; import com.sun.enterprise.security.auth.digest.api.DigestAlgorithmParameter; @@ -76,7 +76,7 @@ public abstract class DigestLoginModule implements LoginModule { protected boolean _succeeded; protected boolean _commitSucceeded; - protected PrincipalImpl _userPrincipal; + protected CallerPrincipal _userPrincipal; private DigestCredentials digestCredentials; private Subject subject; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java new file mode 100644 index 00000000000..fc2dc352ab3 --- /dev/null +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ +package com.sun.enterprise.security.ee.authentication.jakarta; + +import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; +import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; +import static org.glassfish.epicyro.config.helper.HttpServletConstants.SOAP; + +import com.sun.enterprise.deployment.ServiceReferenceDescriptor; +import com.sun.enterprise.deployment.WebBundleDescriptor; +import com.sun.enterprise.deployment.WebServiceEndpoint; +import com.sun.enterprise.deployment.runtime.common.MessageDescriptor; +import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; +import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; +import com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor; +import com.sun.enterprise.deployment.runtime.web.SunWebApp; +import jakarta.security.auth.message.MessagePolicy; +import java.util.List; +import java.util.Map; +import javax.security.auth.callback.CallbackHandler; +import org.glassfish.internal.api.Globals; + +/** + * Utility class for Jakarta Authentication appserver implementation. + */ +public class AuthMessagePolicy { + + public static final String WEB_BUNDLE = "WEB_BUNDLE"; + + private static final String HANDLER_CLASS_PROPERTY = "security.jmac.config.ConfigHelper.CallbackHandler"; + private static final String DEFAULT_HANDLER_CLASS = "com.sun.enterprise.security.ee.authentication.jakarta.callback.ContainerCallbackHandler"; + + private static String handlerClassName; + + private AuthMessagePolicy() { + } + + public static MessageSecurityBindingDescriptor getMessageSecurityBinding(String layer, Map properties) { + if (properties == null) { + return null; + } + + MessageSecurityBindingDescriptor binding = null; + + WebServiceEndpoint webServiceEndpoint = (WebServiceEndpoint) properties.get("SERVICE_ENDPOINT"); + + if (webServiceEndpoint != null) { + binding = webServiceEndpoint.getMessageSecurityBinding(); + } else { + ServiceReferenceDescriptor serviceReferenceDescriptor = (ServiceReferenceDescriptor) properties.get("SERVICE_REF"); + if (serviceReferenceDescriptor != null) { + WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); + if (delegate != null) { + binding = delegate.getBinding(serviceReferenceDescriptor, properties); + } + } + } + + if (binding != null) { + String bindingLayer = (String) binding.getValue(AUTH_LAYER); + if (bindingLayer == null || layer.equals(bindingLayer)) { + return binding; + } + } + + return null; + } + + public static MessagePolicy getMessagePolicy(ProtectionDescriptor protectionDescriptor) { + MessagePolicy messagePolicy = null; + if (protectionDescriptor != null) { + String source = protectionDescriptor.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); + String recipient = protectionDescriptor.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); + messagePolicy = org.glassfish.epicyro.config.helper.AuthMessagePolicy.getMessagePolicy(source, recipient); + } + + return messagePolicy; + } + + public static String getProviderID(MessageSecurityBindingDescriptor binding) { + if (binding == null) { + return null; + } + + if (!SOAP.equals(binding.getValue(AUTH_LAYER))) { + return null; + } + + return binding.getValue(PROVIDER_ID); + } + + public static MessagePolicy[] getSOAPPolicies(MessageSecurityBindingDescriptor binding, String operation, boolean onePolicy) { + MessagePolicy requestPolicy = null; + MessagePolicy responsePolicy = null; + + if (binding != null) { + List messageSecurityDescriptors = null; + String layer = binding.getValue(AUTH_LAYER); + if (SOAP.equals(layer)) { + messageSecurityDescriptors = binding.getMessageSecurityDescriptors(); + } + + if (messageSecurityDescriptors != null) { + if (onePolicy) { + if (messageSecurityDescriptors.size() > 0) { + MessageSecurityDescriptor messageSecurityDescriptor = messageSecurityDescriptors.get(0); + requestPolicy = getMessagePolicy(messageSecurityDescriptor.getRequestProtectionDescriptor()); + responsePolicy = getMessagePolicy(messageSecurityDescriptor.getResponseProtectionDescriptor()); + } + } else { // try to match + MessageSecurityDescriptor matchMsd = null; + for (int i = 0; i < messageSecurityDescriptors.size(); i++) { + MessageSecurityDescriptor msd = messageSecurityDescriptors.get(i); + List msgDescs = msd.getMessageDescriptors(); + for (int j = i + 1; j < msgDescs.size(); j++) { + // XXX don't know how to get JavaMethod from operation + MessageDescriptor msgDesc = msgDescs.get(j); + String opName = msgDesc.getOperationName(); + if (opName == null && matchMsd == null) { + matchMsd = msd; + } else if (opName != null && opName.equals(operation)) { + matchMsd = msd; + break; + } + } + + if (matchMsd != null) { + requestPolicy = getMessagePolicy(matchMsd.getRequestProtectionDescriptor()); + responsePolicy = getMessagePolicy(matchMsd.getResponseProtectionDescriptor()); + } + } + } + } + } + + return new MessagePolicy[] { requestPolicy, responsePolicy }; + } + + public static boolean oneSOAPPolicy(MessageSecurityBindingDescriptor binding) { + + boolean onePolicy = true; + List msgSecDescs = null; + if (binding != null) { + String layer = binding.getAttributeValue(AUTH_LAYER); + if (SOAP.equals(layer)) { + msgSecDescs = binding.getMessageSecurityDescriptors(); + } + } + + if (msgSecDescs == null) { + return true; + } + + for (int i = 0; i < msgSecDescs.size(); i++) { + + MessageSecurityDescriptor msd = msgSecDescs.get(i); + + // Determine if all the different messageSecurityDesriptors have the + // same policy which will help us interpret the effective policy if + // we cannot determine the opcode of a request at runtime. + for (int j = 0; j < msgSecDescs.size(); j++) { + if (j != i && !policiesAreEqual(msd, msgSecDescs.get(j))) { + onePolicy = false; + } + } + } + + return onePolicy; + } + + public static SunWebApp getSunWebApp(Map properties) { + if (properties == null) { + return null; + } + + WebBundleDescriptor webBundle = (WebBundleDescriptor) properties.get(WEB_BUNDLE); + return webBundle.getSunDescriptor(); + } + + public static String getProviderID(SunWebApp sunWebApp) { + if (sunWebApp == null) { + return null; + } + + return sunWebApp.getAttributeValue(SunWebApp.HTTPSERVLET_SECURITY_PROVIDER); + } + + + public static CallbackHandler getDefaultCallbackHandler() { + try { + if (handlerClassName == null) { + handlerClassName = System.getProperty(HANDLER_CLASS_PROPERTY, DEFAULT_HANDLER_CLASS); + } + + return (CallbackHandler) + Class.forName(handlerClassName, true, Thread.currentThread().getContextClassLoader()) + .getDeclaredConstructor() + .newInstance(); + + } catch (ReflectiveOperationException pae) { + throw new RuntimeException(pae); + } + } + + private static boolean policiesAreEqual(MessageSecurityDescriptor reference, MessageSecurityDescriptor other) { + return protectionDescriptorsAreEqual(reference.getRequestProtectionDescriptor(), other.getRequestProtectionDescriptor()) + && protectionDescriptorsAreEqual(reference.getResponseProtectionDescriptor(), other.getResponseProtectionDescriptor()); + } + + private static boolean protectionDescriptorsAreEqual(ProtectionDescriptor pd1, ProtectionDescriptor pd2) { + String authSource1 = pd1.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); + String authRecipient1 = pd1.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); + + String authSource2 = pd2.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); + String authRecipient2 = pd2.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); + + boolean sameAuthSource = authSource1 == null && authSource2 == null || authSource1 != null && authSource1.equals(authSource2); + boolean sameAuthRecipient = authRecipient1 == null && authRecipient2 == null + || authRecipient1 != null && authRecipient1.equals(authRecipient2); + + return sameAuthSource && sameAuthRecipient; + } +} + diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigDomainParser.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/ConfigDomainParser.java similarity index 86% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigDomainParser.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/ConfigDomainParser.java index c978289d313..f93a305683e 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigDomainParser.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/ConfigDomainParser.java @@ -37,18 +37,21 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright 2019-2022 Payara Foundation and/or its affiliates +// Portions Copyright 2019-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license -package com.sun.enterprise.security.jaspic.config; +package com.sun.enterprise.security.ee.authentication.jakarta; import com.sun.enterprise.config.serverbeans.MessageSecurityConfig; import com.sun.enterprise.config.serverbeans.ProviderConfig; import com.sun.enterprise.config.serverbeans.RequestPolicy; import com.sun.enterprise.config.serverbeans.ResponsePolicy; import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; import com.sun.logging.LogDomains; import jakarta.security.auth.message.MessagePolicy; +import org.glassfish.epicyro.config.factory.ConfigParser; +import org.glassfish.epicyro.config.helper.AuthMessagePolicy; +import org.glassfish.epicyro.data.AuthModuleConfig; +import org.glassfish.epicyro.data.AuthModulesLayerConfig; import org.glassfish.internal.api.Globals; import org.jvnet.hk2.config.types.Property; @@ -78,10 +81,10 @@ public class ConfigDomainParser implements ConfigParser { private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{\\{(.*?)}}|\\$\\{(.*?)}"); // configuration info - private Map configMap = new HashMap<>(); + private Map configMap = new HashMap<>(); private Set layersWithDefault = new HashSet(); - public ConfigDomainParser() throws IOException { + public ConfigDomainParser() { } public void initialize(Object service) throws IOException { @@ -94,7 +97,12 @@ public void initialize(Object service) throws IOException { } } - private void processServerConfig(SecurityService service, Map newConfig) throws IOException { + @Override + public Map getAuthModuleLayers() { + return configMap; + } + + private void processServerConfig(SecurityService service, Map newConfig) throws IOException { List configList = service.getMessageSecurityConfig(); if (configList != null) { @@ -119,7 +127,7 @@ private void processServerConfig(SecurityService service, Map getConfigMap() { + public Map getConfigMap() { return configMap; } @@ -127,7 +135,7 @@ public Set getLayersWithDefault() { return layersWithDefault; } - private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { + private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { String intercept = null; String defaultServerID = null; String defaultClientID = null; @@ -145,19 +153,19 @@ private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig, String intercept) throws IOException { + private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercept) throws IOException { String id = pConfig.getProviderId(); String type = pConfig.getProviderType(); @@ -194,20 +202,20 @@ private void parseIDEntry(ProviderConfig pConfig, Map(); + if (intEntry.getAuthModules() == null) { + intEntry.setIdMap(new HashMap()); } // map id to Intercept - intEntry.idMap.put(id, idEntry); + intEntry.getAuthModules().put(id, idEntry); } private String expand(String rawProperty) { diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/WebServicesDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java similarity index 95% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/WebServicesDelegate.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java index 2241ca072f6..7951de32a2f 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/WebServicesDelegate.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java @@ -37,8 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic; +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authentication.jakarta; import java.util.Map; @@ -50,7 +50,7 @@ import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; import com.sun.enterprise.security.jauth.AuthParam; -import com.sun.jaspic.services.RegistrationWrapperRemover; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; /** * A Delegate interface for handling WebServices specific security and JASPIC (JSR 196) providers. diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java similarity index 99% rename from nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java index 4071525d44d..10612bf5fdc 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java @@ -38,10 +38,11 @@ * holder. */ // Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security; +package com.sun.enterprise.security.ee.authorize; import com.sun.enterprise.config.serverbeans.JaccProvider; import com.sun.enterprise.config.serverbeans.SecurityService; +import com.sun.enterprise.security.SecurityLoggerInfo; import com.sun.enterprise.util.i18n.StringManager; import jakarta.inject.Inject; import jakarta.inject.Named; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java index ca9558ac5e2..84bec4504fd 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java @@ -49,7 +49,7 @@ import com.sun.enterprise.deployment.runtime.common.wls.SecurityRoleAssignment; import com.sun.enterprise.deployment.runtime.web.SunWebApp; import com.sun.enterprise.deployment.web.LoginConfiguration; -import com.sun.enterprise.security.PolicyLoader; +import com.sun.enterprise.security.ee.authorize.PolicyLoader; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityRoleMapperFactoryGen; import com.sun.enterprise.security.SecurityServicesUtil; @@ -80,7 +80,6 @@ import jakarta.servlet.http.HttpServletRequest; import org.glassfish.deployment.common.SecurityRoleMapperFactory; import org.glassfish.exousia.AuthorizationService; -import org.glassfish.exousia.mapping.DefaultPrincipalMapper; import org.glassfish.internal.api.ServerContext; import org.glassfish.security.common.Group; import org.glassfish.security.common.PrincipalImpl; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java index d3455e78ed6..96c34b3ef69 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java @@ -38,7 +38,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] /** * This package contains much of the implementation code for JACC. * @@ -59,7 +59,7 @@ * *

* The pluggable JACC components are loaded by a class in nucleus: - * {@link com.sun.enterprise.security.PolicyLoader} + * {@link com.sun.enterprise.security.ee.authorize.PolicyLoader} * */ package com.sun.enterprise.security.jacc; \ No newline at end of file diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java deleted file mode 100644 index c2f723f3b91..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic; - -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; -import static com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor.AUTH_RECIPIENT; -import static com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor.AUTH_SOURCE; -import static com.sun.enterprise.deployment.runtime.web.SunWebApp.HTTPSERVLET_SECURITY_PROVIDER; -import static com.sun.enterprise.security.common.AppservAccessController.doPrivileged; -import static com.sun.enterprise.security.jaspic.config.GFServerConfigProvider.SOAP; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.WEB_BUNDLE; -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_CONTENT; -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_RECIPIENT; -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_SENDER; - -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.MessagePolicy.TargetPolicy; - -import org.glassfish.internal.api.Globals; - -import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.enterprise.deployment.WebBundleDescriptor; -import com.sun.enterprise.deployment.WebServiceEndpoint; -import com.sun.enterprise.deployment.runtime.common.MessageDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; -import com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor; -import com.sun.enterprise.deployment.runtime.web.SunWebApp; - -/** - * Utility class for JASPIC appserver implementation. - */ -public class AuthMessagePolicy { - - private static final String SENDER = "sender"; - private static final String CONTENT = "content"; - private static final String BEFORE_CONTENT = "before-content"; - private static final String HANDLER_CLASS_PROPERTY = "security.jaspic.config.ConfigHelper.CallbackHandler"; - private static final String DEFAULT_HANDLER_CLASS = "com.sun.enterprise.security.jaspic.callback.ContainerCallbackHandler"; - - // for HttpServlet profile - private static final MessagePolicy MANDATORY_POLICY = getMessagePolicy(SENDER, null, true); - private static final MessagePolicy OPTIONAL_POLICY = getMessagePolicy(SENDER, null, false); - - private static String handlerClassName; - - private AuthMessagePolicy() { - } - - public static MessageSecurityBindingDescriptor getMessageSecurityBinding(String layer, Map properties) { - if (properties == null) { - return null; - } - - MessageSecurityBindingDescriptor messageSecurityBinding = null; - - WebServiceEndpoint webServiceEndpoint = (WebServiceEndpoint) properties.get("SERVICE_ENDPOINT"); - - if (webServiceEndpoint != null) { - messageSecurityBinding = webServiceEndpoint.getMessageSecurityBinding(); - } else { - ServiceReferenceDescriptor serviceReference = (ServiceReferenceDescriptor) properties.get("SERVICE_REF"); - if (serviceReference != null) { - WebServicesDelegate webServicesDelegate = Globals.get(WebServicesDelegate.class); - if (webServicesDelegate != null) { - messageSecurityBinding = webServicesDelegate.getBinding(serviceReference, properties); - } - } - } - - if (messageSecurityBinding != null) { - String bindingLayer = messageSecurityBinding.getAttributeValue(AUTH_LAYER); - if (bindingLayer == null || layer.equals(bindingLayer)) { - return messageSecurityBinding; - } - } - - return null; - } - - public static MessagePolicy getMessagePolicy(String authSource, String authRecipient) { - boolean sourceSender = SENDER.equals(authSource); - boolean sourceContent = CONTENT.equals(authSource); - boolean recipientAuth = authRecipient != null; - boolean mandatory = (sourceSender || sourceContent) || recipientAuth; - - return getMessagePolicy(authSource, authRecipient, mandatory); - } - - public static MessagePolicy getMessagePolicy(String authSource, String authRecipient, boolean mandatory) { - boolean sourceSender = SENDER.equals(authSource); - boolean sourceContent = CONTENT.equals(authSource); - boolean recipientAuth = authRecipient != null; - boolean beforeContent = BEFORE_CONTENT.equals(authRecipient); - - List targetPolicies = new ArrayList(); - - if (recipientAuth && beforeContent) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_RECIPIENT)); - - if (sourceSender) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_SENDER)); - } else if (sourceContent) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_CONTENT)); - } - } else { - if (sourceSender) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_SENDER)); - } else if (sourceContent) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_CONTENT)); - } - - if (recipientAuth) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_RECIPIENT)); - } - } - - return new MessagePolicy(targetPolicies.toArray(new TargetPolicy[targetPolicies.size()]), mandatory); - } - - public static MessagePolicy getMessagePolicy(ProtectionDescriptor protectionDescriptor) { - if (protectionDescriptor == null) { - return null; - } - - String source = protectionDescriptor.getAttributeValue(AUTH_SOURCE); - String recipient = protectionDescriptor.getAttributeValue(AUTH_RECIPIENT); - - return getMessagePolicy(source, recipient); - } - - public static String getProviderID(MessageSecurityBindingDescriptor binding) { - String providerID = null; - if (binding != null) { - String layer = binding.getAttributeValue(AUTH_LAYER); - if (SOAP.equals(layer)) { - providerID = binding.getAttributeValue(PROVIDER_ID); - } - } - - return providerID; - } - - public static MessagePolicy[] getSOAPPolicies(MessageSecurityBindingDescriptor binding, String operation, boolean onePolicy) { - - MessagePolicy requestPolicy = null; - MessagePolicy responsePolicy = null; - - if (binding != null) { - List messageSecurityDescriptors = null; - String layer = binding.getAttributeValue(AUTH_LAYER); - if (SOAP.equals(layer)) { - messageSecurityDescriptors = binding.getMessageSecurityDescriptors(); - } - - if (messageSecurityDescriptors != null) { - if (onePolicy) { - if (messageSecurityDescriptors.size() > 0) { - MessageSecurityDescriptor msd = messageSecurityDescriptors.get(0); - requestPolicy = getMessagePolicy(msd.getRequestProtectionDescriptor()); - responsePolicy = getMessagePolicy(msd.getResponseProtectionDescriptor()); - } - } else { // try to match - MessageSecurityDescriptor matchMsd = null; - for (int i = 0; i < messageSecurityDescriptors.size(); i++) { - MessageSecurityDescriptor msd = messageSecurityDescriptors.get(i); - List msgDescs = msd.getMessageDescriptors(); - for (int j = i + 1; j < msgDescs.size(); j++) { - // XXX don't know how to get JavaMethod from operation - MessageDescriptor msgDesc = (MessageDescriptor) msgDescs.get(j); - String opName = msgDesc.getOperationName(); - if ((opName == null && matchMsd == null)) { - matchMsd = msd; - } else if (opName != null && opName.equals(operation)) { - matchMsd = msd; - break; - } - } - - if (matchMsd != null) { - requestPolicy = getMessagePolicy(matchMsd.getRequestProtectionDescriptor()); - responsePolicy = getMessagePolicy(matchMsd.getResponseProtectionDescriptor()); - } - } - } - } - } - - return new MessagePolicy[] { requestPolicy, responsePolicy }; - } - - public static boolean oneSOAPPolicy(MessageSecurityBindingDescriptor binding) { - boolean onePolicy = true; - List messageSecurityDescriptor = null; - - if (binding != null) { - if (SOAP.equals(binding.getAttributeValue(AUTH_LAYER))) { - messageSecurityDescriptor = binding.getMessageSecurityDescriptors(); - } - } - - if (messageSecurityDescriptor == null) { - return true; - } - - for (int i = 0; i < messageSecurityDescriptor.size(); i++) { - - MessageSecurityDescriptor msd = messageSecurityDescriptor.get(i); - - // Determine if all the different messageSecurityDesriptors have the - // same policy which will help us interpret the effective policy if - // we cannot determine the opcode of a request at runtime. - - for (int j = 0; j < messageSecurityDescriptor.size(); j++) { - if (j != i && !policiesAreEqual(msd, messageSecurityDescriptor.get(j))) { - onePolicy = false; - } - } - } - - return onePolicy; - } - - public static SunWebApp getSunWebApp(Map properties) { - if (properties == null) { - return null; - } - - return ((WebBundleDescriptor) properties.get(WEB_BUNDLE)).getSunDescriptor(); - } - - public static String getProviderID(SunWebApp sunWebApp) { - String providerID = null; - if (sunWebApp != null) { - providerID = sunWebApp.getAttributeValue(HTTPSERVLET_SECURITY_PROVIDER); - } - - return providerID; - } - - public static MessagePolicy[] getHttpServletPolicies(String authContextID) { - if (Boolean.valueOf(authContextID)) { - return new MessagePolicy[] { MANDATORY_POLICY, null }; - } - - return new MessagePolicy[] { OPTIONAL_POLICY, null }; - } - - public static CallbackHandler getDefaultCallbackHandler() { - // Get the default handler class - try { - return (CallbackHandler) doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (handlerClassName == null) { - handlerClassName = System.getProperty(HANDLER_CLASS_PROPERTY, DEFAULT_HANDLER_CLASS); - } - - return Class.forName(handlerClassName, true, loader) - .newInstance(); - } - }); - - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); - } - } - - private static boolean policiesAreEqual(MessageSecurityDescriptor reference, MessageSecurityDescriptor other) { - return (protectionDescriptorsAreEqual(reference.getRequestProtectionDescriptor(), other.getRequestProtectionDescriptor()) - && protectionDescriptorsAreEqual(reference.getResponseProtectionDescriptor(), other.getResponseProtectionDescriptor())); - } - - private static boolean protectionDescriptorsAreEqual(ProtectionDescriptor pd1, ProtectionDescriptor pd2) { - String authSource1 = pd1.getAttributeValue(AUTH_SOURCE); - String authRecipient1 = pd1.getAttributeValue(AUTH_RECIPIENT); - - String authSource2 = pd2.getAttributeValue(AUTH_SOURCE); - String authRecipient2 = pd2.getAttributeValue(AUTH_RECIPIENT); - - boolean sameAuthSource = (authSource1 == null && authSource2 == null) || (authSource1 != null && authSource1.equals(authSource2)); - boolean sameAuthRecipient = (authRecipient1 == null && authRecipient2 == null) - || (authRecipient1 != null && authRecipient1.equals(authRecipient2)); - - return sameAuthSource && sameAuthRecipient; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java index 369753c1155..c74d027dec1 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java @@ -37,12 +37,13 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation] +// Portions Copyright [2016-2024] [Payara Foundation] package com.sun.enterprise.security.jaspic; import static com.sun.logging.LogDomains.SECURITY_LOGGER; +import jakarta.security.auth.message.config.AuthConfigFactory; import java.beans.PropertyChangeEvent; import java.util.logging.Logger; @@ -62,7 +63,6 @@ import com.sun.enterprise.config.serverbeans.MessageSecurityConfig; import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; import com.sun.logging.LogDomains; /** @@ -80,59 +80,7 @@ public class MessageSecurityConfigEventListenerImpl implements ConfigListener { @Inject @Named(ServerEnvironment.DEFAULT_INSTANCE_NAME) private SecurityService service; - - /** - * @param event - Event to be processed. - * @throws AdminEventListenerException when the listener is unable to process the event. - */ - public NotProcessed handleUpdate(T instance) { - NotProcessed notProcessed = null; - logger.fine("MessageSecurityConfigEventListenerImpl - handleUpdate called"); - - // Handle only the MessageSecurityConfig. - if (instance instanceof MessageSecurityConfig) { - GFServerConfigProvider.loadConfigContext(service); - } else { - notProcessed = new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); - } - - return notProcessed; - } - - /** - * @param event Event to be processed. - * @throws AdminEventListenerException when the listener is unable to process the event. - */ - public NotProcessed handleDelete(T instance) { - NotProcessed notProcessed = null; - logger.fine("MessageSecurityConfigEventListenerImpl - handleDelete called"); - - if (instance instanceof MessageSecurityConfig) { - GFServerConfigProvider.loadConfigContext(service); - } else { - notProcessed = new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); - } - - return notProcessed; - } - - /** - * @param event Event to be processed. - * @throws AdminEventListenerException when the listener is unable to process the event. - */ - public NotProcessed handleCreate(T instance) { - NotProcessed notProcessed = null; - logger.fine("MessageSecurityConfigEventListenerImpl - handleCreate called"); - - if (instance instanceof MessageSecurityConfig) { - GFServerConfigProvider.loadConfigContext(service); - } else { - notProcessed = new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); - } - - return notProcessed; - } - + @Override public UnprocessedChangeEvents changed(PropertyChangeEvent[] events) { ConfigSupport.sortAndDispatch(events, new Changed() { @@ -151,15 +99,15 @@ public NotProcessed changed(TYPE type, Class chan switch (type) { case ADD: logger.fine("A new " + changedType.getName() + " was added : " + " " + changedInstance); - notProcessed = handleCreate(changedInstance); + notProcessed = handle(changedInstance); break; case CHANGE: logger.fine("A " + changedType.getName() + " was changed : " + changedInstance); - notProcessed = handleUpdate(changedInstance); + notProcessed = handle(changedInstance); break; case REMOVE: logger.fine("A " + changedType.getName() + " was removed : " + changedInstance); - notProcessed = handleDelete(changedInstance); + notProcessed = handle(changedInstance); break; } @@ -169,4 +117,16 @@ public NotProcessed changed(TYPE type, Class chan return null; } + + private NotProcessed handle(T instance) { + if (instance instanceof MessageSecurityConfig) { + AuthConfigFactory factory = AuthConfigFactory.getFactory(); + if (factory != null) { + factory.refresh(); + } + return null; + } + + return new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); + } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java deleted file mode 100644 index dd0c2a12440..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import java.io.IOException; -import java.util.Map; -import java.util.Set; - - -/** - * AuthConfigImpl relies on a ConfigParser to read - * the module configuration. - * - *

The ConfigParser is expected to parse that information - * into the HashMap described below. - * - * @version %I%, %G% - */ -public interface ConfigParser { - - /** - * Initialize the parser. - * Passing null as argument means the parser is to find - * configuration object as necessary. - */ - public void initialize(Object config) throws IOException; - - /** - * Get the module configuration information. - * The information is returned as a HashMap. - * - *

The key is an intercept: - *

    - *
  • SOAP - *
  • HttpServlet - *
- * - *

The value is a AuthConfigImpl.InterceptEntry, which contains: - *

    - *
  • default provider ID - *
  • default type (client or server) - *
  • HashMap, where - * key = provider ID - * value = BaseAuthConfigImpl.IDEntry - *
- * - *

An IDEntry contains: - *

    - *
  • type (client or server) - *
  • moduleClassName - *
  • default requestPolicy - *
  • default responsePolicy - *
  • options - *
  • - *
- */ - public Map getConfigMap(); - - /** - * Get the name of layers with default set in domain.xml. - */ - public Set getLayersWithDefault(); -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java deleted file mode 100644 index 23cdb90706f..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import static java.util.Arrays.asList; - -import java.util.List; - -import com.sun.enterprise.security.SecurityServicesUtil; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; -import com.sun.jaspic.config.factory.BaseAuthConfigFactory; -import com.sun.jaspic.config.factory.EntryInfo; -import com.sun.jaspic.config.factory.RegStoreFileParser; - -/** - * This class implements methods in the abstract class AuthConfigFactory. - * - * @author Shing Wai Chan - */ -public class GFAuthConfigFactory extends BaseAuthConfigFactory { - - // MUST "hide" regStore in derived class. - private static RegStoreFileParser regStore; - - /** - * To specialize the defaultEntries passed to the RegStoreFileParser constructor, create another subclass of - * BaseAuthconfigFactory, that is basically a copy of this class, with a change to the third argument of the call to new - * ResSToreFileParser. to ensure runtime use of the the associated regStore, make sure that the new subclass also - * contains an implementation of the getRegStore method. - * - *

- * As done within this class, use the locks defined in - * BaseAuthConfigFactory to serialize access to the regStore (both within the class constructor, and within getRegStore) - * - *

- * All EntyInfo OBJECTS PASSED as defaultEntries MUST HAVE BEEN CONSTRUCTED USING THE FOLLOWING CONSTRUCTOR: - * - * EntryInfo(String className, Map properties); - * - */ - public GFAuthConfigFactory() { - if (doReadLocked(() -> regStore != null)) { - return; - } - - String userDir = System.getProperty("user.dir"); - - doWriteLocked(() -> { - if (regStore == null) { - initializeRegStore(userDir); - _loadFactory(); - } - }); - } - - /** - * @param userDir - */ - private static void initializeRegStore(String userDir) { - regStore = new RegStoreFileParser(userDir, CONF_FILE_NAME, getDefaultProviders()); - } - - @Override - protected RegStoreFileParser getRegStore() { - return doReadLocked(() -> regStore); - } - - /** - * Contains the default providers used when none are configured in a factory configuration file. - */ - private static List getDefaultProviders() { - WebServicesDelegate delegate = null; - SecurityServicesUtil securityServicesUtil = SecurityServicesUtil.getInstance(); - - if (securityServicesUtil != null) { - delegate = securityServicesUtil.getHabitat().getService(WebServicesDelegate.class); - } - - if (delegate != null) { - return asList( - new EntryInfo(delegate.getDefaultWebServicesProvider()), - new EntryInfo(GFServerConfigProvider.class.getName())); - } - - return asList(new EntryInfo(GFServerConfigProvider.class.getName())); - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java deleted file mode 100644 index 465f2d874c7..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java +++ /dev/null @@ -1,981 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getHttpServletPolicies; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getMessageSecurityBinding; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getProviderID; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getSOAPPolicies; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getSunWebApp; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.oneSOAPPolicy; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.IS_MANDATORY; -import static java.security.AccessController.doPrivileged; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; - -import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.logging.Logger; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -// jsr 196 interface types -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.config.AuthConfig; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ClientAuthModule; -import jakarta.security.auth.message.module.ServerAuthModule; - -import org.glassfish.internal.api.Globals; - -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.web.SunWebApp; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; -import com.sun.logging.LogDomains; - -/** - * This class implements the interface AuthConfigProvider. - * - * @author Shing Wai Chan - * @author Ronald Monzillo - */ -public class GFServerConfigProvider implements AuthConfigProvider { - - private static final Logger logger = LogDomains.getLogger(GFServerConfigProvider.class, LogDomains.SECURITY_LOGGER); - - public static final String SOAP = "SOAP"; - public static final String HTTPSERVLET = "HttpServlet"; - - protected static final String CLIENT = "client"; - protected static final String SERVER = "server"; - protected static final String MANAGES_SESSIONS_OPTION = "managessessions"; - - private static final String DEFAULT_PARSER_CLASS = "com.sun.enterprise.security.jaspic.config.ConfigDomainParser"; - - // since old api does not have subject in PasswordValdiationCallback, - // this is for old modules to pass group info back to subject - private static final ThreadLocal subjectLocal = new ThreadLocal(); - - protected static final ReadWriteLock rwLock = new ReentrantReadWriteLock(); - protected static final Map layerDefaultRegisIDMap = new HashMap(); - - // Mutable statics should be kept package private to eliminate - // the ability for subclasses to access them - static int epoch; - static String parserClassName; - static ConfigParser parser; - static boolean parserInitialized; - static AuthConfigFactory slaveFactory; - - // keep the slave from being visible outside - static AuthConfigProvider slaveProvider; - - protected AuthConfigFactory factory; - private WebServicesDelegate wsdelegate; - - public GFServerConfigProvider(Map properties, AuthConfigFactory factory) { - this.factory = factory; - initializeParser(); - - if (factory != null) { - boolean hasSlaveFactory = false; - try { - rwLock.readLock().lock(); - hasSlaveFactory = (slaveFactory != null); - } finally { - rwLock.readLock().unlock(); - } - - if (!hasSlaveFactory) { - try { - rwLock.writeLock().lock(); - if (slaveFactory == null) { - slaveFactory = factory; - } - } finally { - rwLock.writeLock().unlock(); - } - } - } - - boolean hasSlaveProvider = false; - try { - rwLock.readLock().lock(); - hasSlaveProvider = slaveProvider != null; - } finally { - rwLock.readLock().unlock(); - } - - if (!hasSlaveProvider) { - try { - rwLock.writeLock().lock(); - if (slaveProvider == null) { - slaveProvider = this; - } - } finally { - rwLock.writeLock().unlock(); - } - } - wsdelegate = Globals.get(WebServicesDelegate.class); - } - - private void initializeParser() { - try { - rwLock.readLock().lock(); - if (parserInitialized) { - return; - } - } finally { - rwLock.readLock().unlock(); - } - - try { - rwLock.writeLock().lock(); - if (!parserInitialized) { - parserClassName = System.getProperty("config.parser", DEFAULT_PARSER_CLASS); - loadParser(this, factory, null); - parserInitialized = true; - } - } finally { - rwLock.writeLock().unlock(); - } - } - - /** - * Instantiate and initialize module class - */ - static ModuleInfo createModuleInfo(Entry entry, CallbackHandler handler, String type, Map properties) throws AuthException { - try { - // Instantiate module using no-arg constructor - Object newModule = entry.newInstance(); - - Map map = properties; - Map entryOptions = entry.getOptions(); - - if (entryOptions != null) { - if (map == null) { - map = new HashMap<>(); - } else { - map = new HashMap<>(map); - } - map.putAll(entryOptions); - } - - // Initialize Module - if (SERVER.equals(type)) { - ServerAuthModule sam = (ServerAuthModule) newModule; - sam.initialize(entry.getRequestPolicy(), entry.getResponsePolicy(), handler, map); - } else { // CLIENT - ClientAuthModule cam = (ClientAuthModule) newModule; - cam.initialize(entry.getRequestPolicy(), entry.getResponsePolicy(), handler, map); - } - - return new ModuleInfo(newModule, map); - } catch (Exception e) { - if (e instanceof AuthException) { - throw (AuthException) e; - } - - throw (AuthException) new AuthException().initCause(e); - } - } - - /** - * Create an object of a given class. - * - * @param className - * - */ - private static Object createObject(String className) { - ClassLoader loader = getClassLoader(); - - if (System.getSecurityManager() != null) { - try { - return doPrivileged((PrivilegedExceptionAction) - () -> Class.forName(className, true, loader).newInstance()); - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); - } - } - - try { - return Class.forName(className, true, loader).newInstance(); - } catch (Throwable t) { - throw new RuntimeException(t); - } - } - - Entry getEntry(String intercept, String id, MessagePolicy requestPolicy, MessagePolicy responsePolicy, String type) { - - // get the parsed module config and DD information - - Map configMap; - - try { - rwLock.readLock().lock(); - configMap = parser.getConfigMap(); - } finally { - rwLock.readLock().unlock(); - } - - if (configMap == null) { - return null; - } - - // get the module config info for this intercept - - InterceptEntry intEntry = configMap.get(intercept); - if (intEntry == null || intEntry.idMap == null) { - if (logger.isLoggable(FINE)) { - logger.fine("module config has no IDs configured for [" + intercept + "]"); - } - - return null; - } - - // look up the DD's provider ID in the module config - - IDEntry idEntry = null; - if (id == null || (idEntry = (IDEntry) intEntry.idMap.get(id)) == null) { - - // either the DD did not specify a provider ID, - // or the DD-specified provider ID was not found - // in the module config. - // - // in either case, look for a default ID in the module config - - if (logger.isLoggable(FINE)) { - logger.fine("DD did not specify ID, " + "or DD-specified ID for [" + intercept + "] not found in config -- " - + "attempting to look for default ID"); - } - - String defaultID; - if (CLIENT.equals(type)) { - defaultID = intEntry.defaultClientID; - } else { - defaultID = intEntry.defaultServerID; - } - - idEntry = (IDEntry) intEntry.idMap.get(defaultID); - if (idEntry == null) { - - // did not find a default provider ID - - if (logger.isLoggable(FINE)) { - logger.fine("no default config ID for [" + intercept + "]"); - } - - return null; - } - } - - // We found the DD provider ID in the module config - // or we found a default module config - - // check provider-type - if (idEntry.type.indexOf(type) < 0) { - if (logger.isLoggable(FINE)) { - logger.fine("request type [" + type + "] does not match config type [" + idEntry.type + "]"); - } - - return null; - } - - // check whether a policy is set - MessagePolicy reqP = requestPolicy != null || responsePolicy != null ? requestPolicy : idEntry.requestPolicy; // default; - - MessagePolicy respP = requestPolicy != null || responsePolicy != null ? responsePolicy : idEntry.responsePolicy; // default; - - // optimization: if policy was not set, return null - if (reqP == null && respP == null) { - if (logger.isLoggable(FINE)) { - logger.fine("no policy applies"); - } - return null; - } - - // return the configured modules with the correct policies - - Entry entry = new Entry(idEntry.moduleClassName, reqP, respP, idEntry.options); - - if (logger.isLoggable(FINE)) { - logger.fine("getEntry for: " + intercept + " -- " + id + "\n module class: " + entry.moduleClassName + "\n options: " - + entry.options + "\n request policy: " + entry.requestPolicy + "\n response policy: " + entry.responsePolicy); - } - - return entry; - } - - /** - * Class representing a single AuthModule entry configured for an ID, interception point, and stack. - * - *

- * This class also provides a way for a caller to obtain an instance of the module listed in the entry by invoking the - * newInstance method. - */ - static class Entry { - - // For loading modules - private static final Class[] PARAMS = {}; - private static final Object[] ARGS = {}; - - private String moduleClassName; - private MessagePolicy requestPolicy; - private MessagePolicy responsePolicy; - private Map options; - - /** - * Construct a ConfigFile entry. - * - *

- * An entry encapsulates a single module and its related information. - * - * @param moduleClassName - * the module class name - * @param requestPolicy - * the request policy assigned to the module listed in this entry, which may be null. - * - * @param responsePolicy - * the response policy assigned to the module listed in this entry, which may be null. - * - * @param options - * the options configured for this module. - */ - Entry(String moduleClassName, MessagePolicy requestPolicy, MessagePolicy responsePolicy, Map options) { - this.moduleClassName = moduleClassName; - this.requestPolicy = requestPolicy; - this.responsePolicy = responsePolicy; - this.options = options; - } - - /** - * Return the request policy assigned to this module. - * - * @return the policy, which may be null. - */ - MessagePolicy getRequestPolicy() { - return requestPolicy; - } - - /** - * Return the response policy assigned to this module. - * - * @return the policy, which may be null. - */ - MessagePolicy getResponsePolicy() { - return responsePolicy; - } - - String getModuleClassName() { - return moduleClassName; - } - - Map getOptions() { - return options; - } - - /** - * Return a new instance of the module contained in this entry. - * - *

- * The default implementation of this method attempts to invoke the default no-args constructor of the module class. - * This method may be overridden if a different constructor should be invoked. - * - * @return a new instance of the module contained in this entry. - * - * @exception AuthException - * if the instantiation failed. - */ - Object newInstance() throws AuthException { - try { - return Class.forName(moduleClassName, true, getClassLoader()) - .getConstructor(PARAMS) - .newInstance(ARGS); - } catch (Exception e) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.provider_unable_to_load_authmodule", new String[] { moduleClassName, e.toString() }); - } - - AuthException ae = new AuthException(); - ae.initCause(e); - throw ae; - } - } - } - - public static class InterceptEntry { - String defaultClientID; - String defaultServerID; - Map idMap; - - public InterceptEntry(String defaultClientID, String defaultServerID, Map idMap) { - this.defaultClientID = defaultClientID; - this.defaultServerID = defaultServerID; - this.idMap = idMap; - } - - public Map getIdMap() { - return idMap; - } - - public void setIdMap(Map map) { - idMap = map; - } - - public String getDefaultClientID() { - return defaultClientID; - } - - public String getDefaultServerID() { - return defaultServerID; - } - } - - /** - * Get an instance of ClientAuthConfig from this provider. - * - *

- * The implementation of this method returns a ClientAuthConfig instance that describes the configuration of - * ClientAuthModules at a given message layer, and for use in an identified application context. - * - * @param layer - * a String identifying the message layer for the returned ClientAuthConfig object. This argument must not be - * null. - * - * @param appContext - * a String that identifies the messaging context for the returned ClientAuthConfig object. This argument - * must not be null. - * - * @param handler - * a CallbackHandler to be passed to the ClientAuthModules encapsulated by ClientAuthContext objects derived - * from the returned ClientAuthConfig. This argument may be null, in which case the implementation may assign - * a default handler to the configuration. - * - * @return a ClientAuthConfig Object that describes the configuration of ClientAuthModules at the message layer and - * messaging context identified by the layer and appContext arguments. This method does not return null. - * - * @exception AuthException - * if this provider does not support the assignment of a default CallbackHandler to the returned - * ClientAuthConfig. - * - * @exception SecurityException - * if the caller does not have permission to retrieve the configuration. - * - * The CallbackHandler assigned to the configuration must support the Callback objects required to be - * supported by the profile of this specification being followed by the messaging runtime. The - * CallbackHandler instance must be initialized with any application context needed to process the - * required callbacks on behalf of the corresponding application. - */ - public ClientAuthConfig getClientAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException { - return new GFClientAuthConfig(this, layer, appContext, handler); - } - - /** - * Get an instance of ServerAuthConfig from this provider. - * - *

- * The implementation of this method returns a ServerAuthConfig instance that describes the configuration of - * ServerAuthModules at a given message layer, and for a particular application context. - * - * @param layer - * a String identifying the message layer for the returned ServerAuthConfig object. This argument must not be - * null. - * - * @param appContext - * a String that identifies the messaging context for the returned ServerAuthConfig object. This argument - * must not be null. - * - * @param handler - * a CallbackHandler to be passed to the ServerAuthModules encapsulated by ServerAuthContext objects derived - * from thr returned ServerAuthConfig. This argument may be null, in which case the implementation may assign - * a default handler to the configuration. - * - * @return a ServerAuthConfig Object that describes the configuration of ServerAuthModules at a given message layer, and - * for a particular application context. This method does not return null. - * - * @exception AuthException - * if this provider does not support the assignment of a default CallbackHandler to the returned - * ServerAuthConfig. - * - * @exception SecurityException - * if the caller does not have permission to retrieve the configuration. - *

- * The CallbackHandler assigned to the configuration must support the Callback objects required to be - * supported by the profile of this specification being followed by the messaging runtime. The - * CallbackHandler instance must be initialized with any application context needed to process the - * required callbacks on behalf of the corresponding application. - */ - public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException { - return new GFServerAuthConfig(this, layer, appContext, handler); - } - - /** - * Causes a dynamic configuration provider to update its internal state such that any resulting change to its state is - * reflected in the corresponding authentication context configuration objects previously created by the provider within - * the current process context. - * - * @exception AuthException - * if an error occured during the refresh. - * - * @exception SecurityException - * if the caller does not have permission to refresh the provider. - */ - - public void refresh() { - loadParser(this, factory, null); - } - - /** - * this method is intended to be called by the admin configuration system when the corresponding config object has - * changed. It relies on the slaves, since it is a static method. - * - * @param config - * a config object of type understood by the parser. NOTE: there appears to be a thread saftey problem, and - * this method will fail if a slaveProvider has not been established prior to its call. - */ - public static void loadConfigContext(Object config) { - - boolean hasSlaveFactory = false; - rwLock.readLock().lock(); - try { - hasSlaveFactory = (slaveFactory != null); - } finally { - rwLock.readLock().unlock(); - } - - if (slaveProvider == null) { - if (logger.isLoggable(SEVERE)) { - logger.severe("unableToLoad.noSlaveProvider"); - } - return; - } - - if (!hasSlaveFactory) { - rwLock.writeLock().lock(); - try { - if (slaveFactory == null) { - slaveFactory = AuthConfigFactory.getFactory(); - } - } finally { - rwLock.writeLock().unlock(); - } - } - - loadParser(slaveProvider, slaveFactory, config); - } - - protected static void loadParser(AuthConfigProvider aProvider, AuthConfigFactory aFactory, Object config) { - rwLock.writeLock().lock(); - try { - ConfigParser nextParser; - int next = epoch + 1; - nextParser = (ConfigParser) createObject(parserClassName); - nextParser.initialize(config); - - if (aFactory != null && aProvider != null) { - Set layerSet = nextParser.getLayersWithDefault(); - for (String layer : layerDefaultRegisIDMap.keySet()) { - if (!layerSet.contains(layer)) { - String regisID = layerDefaultRegisIDMap.remove(layer); - aFactory.removeRegistration(regisID); - } - } - - for (String layer : layerSet) { - if (!layerDefaultRegisIDMap.containsKey(layer)) { - String regisID = aFactory.registerConfigProvider(aProvider, layer, null, - "GFServerConfigProvider: self registration"); - layerDefaultRegisIDMap.put(layer, regisID); - } - } - } - epoch = (next == 0 ? 1 : next); - parser = nextParser; - } catch (IOException ex) { - throw new RuntimeException(ex); - } finally { - rwLock.writeLock().unlock(); - } - } - - protected static ClassLoader getClassLoader() { - if (System.getSecurityManager() == null) { - return Thread.currentThread().getContextClassLoader(); - } - - return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - return Thread.currentThread().getContextClassLoader(); - } - }); - } - - // for old API - public static void setValidateRequestSubject(Subject subject) { - subjectLocal.set(subject); - } - - class GFAuthConfig implements AuthConfig { - - protected AuthConfigProvider provider; - protected String layer; - protected String appContext; - protected CallbackHandler handler; - protected String type; - protected String providerID; - protected boolean init; - protected boolean onePolicy; - protected MessageSecurityBindingDescriptor binding; - protected SunWebApp sunWebApp; - - protected GFAuthConfig(AuthConfigProvider provider, String layer, String appContext, CallbackHandler handler, String type) { - this.provider = provider; - this.layer = layer; - this.appContext = appContext; - this.handler = handler != null ? handler : AuthMessagePolicy.getDefaultCallbackHandler(); - this.type = type; - } - - /** - * Get the message layer name of this authentication context configuration object. - * - * @return the message layer name of this configuration object, or null if the configuration object pertains to an - * unspecified message layer. - */ - public String getMessageLayer() { - return layer; - } - - /** - * Get the application context identifier of this authentication context configuration object. - * - * @return the String identifying the application context of this configuration object or null if the configuration - * object pertains to an unspecified application context. - */ - public String getAppContext() { - return appContext; - } - - /** - * Get the authentication context identifier corresponding to the request and response objects encapsulated in - * messageInfo. - * - * See method AuthMessagePolicy. getHttpServletPolicies() for more details on why this method returns the String's - * "true" or "false" for AuthContextID. - * - * @param messageInfo - * a contextual Object that encapsulates the client request and server response objects. - * - * @return the authentication context identifier corresponding to the encapsulated request and response objects, or - * null. - * - * - * @throws IllegalArgumentException - * if the type of the message objects incorporated in messageInfo are not compatible with the message types - * supported by this authentication context configuration object. - */ - public String getAuthContextID(MessageInfo messageInfo) { - if (HTTPSERVLET.equals(layer)) { - return Boolean.valueOf((String) messageInfo.getMap().get(IS_MANDATORY)).toString(); - } - - if (SOAP.equals(layer) && wsdelegate != null) { - return wsdelegate.getAuthContextID(messageInfo); - } - - return null; - } - - // we should be able to replace the following with a method on packet - - /** - * Causes a dynamic anthentication context configuration object to update the internal state that it uses to process - * calls to its getAuthContext method. - * - * @exception AuthException - * if an error occured during the update. - * - * @exception SecurityException - * if the caller does not have permission to refresh the configuration object. - */ - public void refresh() { - loadParser(provider, factory, null); - } - - /** - * Used to determine whether or not the getAuthContext method of the authentication context configuration - * will return null for all possible values of authentication context identifier. - * - * @return false when getAuthContext will return null for all possible values of authentication context - * identifier. Otherwise, this method returns true. - */ - public boolean isProtected() { - // XXX TBD - return true; - } - - - CallbackHandler getCallbackHandler() { - return handler; - } - - protected ModuleInfo getModuleInfo(String authContextID, Map properties) throws AuthException { - if (!init) { - initialize(properties); - } - - MessagePolicy[] policies = null; - - if (HTTPSERVLET.equals(layer)) { - policies = getHttpServletPolicies(authContextID); - } else { - policies = getSOAPPolicies(binding, authContextID, onePolicy); - } - - MessagePolicy requestPolicy = policies[0]; - MessagePolicy responsePolicy = policies[1]; - - Entry entry = getEntry(layer, providerID, requestPolicy, responsePolicy, type); - - return entry != null ? createModuleInfo(entry, handler, type, properties) : null; - } - - // Lazy initialize this as SunWebApp is not available in RealmAdapter creation - private void initialize(Map properties) { - if (!init) { - if (HTTPSERVLET.equals(layer)) { - sunWebApp = getSunWebApp(properties); - providerID = getProviderID(sunWebApp); - onePolicy = true; - } else { - binding = getMessageSecurityBinding(layer, properties); - providerID = getProviderID(binding); - onePolicy = oneSOAPPolicy(binding); - } - - // HandlerContext need to be explicitly set by caller - init = true; - } - } - } - - class GFServerAuthConfig extends GFAuthConfig implements ServerAuthConfig { - - protected GFServerAuthConfig(AuthConfigProvider provider, String layer, String appContext, CallbackHandler handler) { - super(provider, layer, appContext, handler, SERVER); - } - - public ServerAuthContext getAuthContext(String authContextID, Subject serviceSubject, @SuppressWarnings("rawtypes") Map properties) throws AuthException { - @SuppressWarnings("unchecked") - ModuleInfo moduleInfo = getModuleInfo(authContextID, (Map) properties); - - if (moduleInfo != null && moduleInfo.getModule() != null) { - return new GFServerAuthContext(moduleInfo.getModule()); - } - - return null; - } - } - - class GFClientAuthConfig extends GFAuthConfig implements ClientAuthConfig { - - protected GFClientAuthConfig(AuthConfigProvider provider, String layer, String appContext, CallbackHandler handler) { - super(provider, layer, appContext, handler, CLIENT); - } - - public ClientAuthContext getAuthContext(String authContextID, Subject clientSubject, @SuppressWarnings("rawtypes") Map properties) throws AuthException { - @SuppressWarnings("unchecked") - ModuleInfo moduleInfo = getModuleInfo(authContextID, (Map) properties); - - if (moduleInfo != null && moduleInfo.getModule() != null) { - return new GFClientAuthContext(moduleInfo.getModule()); - } - - return null; - } - } - - static protected class GFServerAuthContext implements ServerAuthContext { - - private final ServerAuthModule module; - - GFServerAuthContext(ServerAuthModule module) { - this.module = module; - } - - public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.validateRequest(messageInfo, clientSubject, serviceSubject); - } - - public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.secureResponse(messageInfo, serviceSubject); - } - - public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - module.cleanSubject(messageInfo, subject); - } - } - - static protected class GFClientAuthContext implements ClientAuthContext { - - private final ClientAuthModule module; - - GFClientAuthContext(ClientAuthModule module) { - this.module = module; - } - - public AuthStatus secureRequest(MessageInfo messageInfo, Subject clientSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.secureRequest(messageInfo, clientSubject); - } - - public AuthStatus validateResponse(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.validateResponse(messageInfo, clientSubject, serviceSubject); - } - - public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - module.cleanSubject(messageInfo, subject); - } - } - - /** - * parsed ID entry - */ - public static class IDEntry { - private String type; // provider type (client, server, client-server) - private String moduleClassName; - private MessagePolicy requestPolicy; - private MessagePolicy responsePolicy; - private Map options; - - public IDEntry(String type, String moduleClassName, MessagePolicy requestPolicy, MessagePolicy responsePolicy, Map options) { - this.type = type; - this.moduleClassName = moduleClassName; - this.requestPolicy = requestPolicy; - this.responsePolicy = responsePolicy; - this.options = options; - } - - public String getModuleClassName() { - return moduleClassName; - } - - public Map getOptions() { - return options; - } - - public MessagePolicy getRequestPolicy() { - return requestPolicy; - } - - public MessagePolicy getResponsePolicy() { - return responsePolicy; - } - - public String getType() { - return type; - } - } - - /** - * A data object contains module object and the corresponding map. - */ - protected static class ModuleInfo { - - private final Object module; - private final Map map; - - ModuleInfo(Object module, Map map) { - this.module = module; - this.map = map; - } - - @SuppressWarnings("unchecked") - T getModule() { - return (T) module; - } - - Map getMap() { - return map; - } - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java similarity index 91% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServices.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java index 4386c028fcd..dd401546776 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServices.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java @@ -37,20 +37,20 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jaspic.config; import java.util.Map; import javax.security.auth.callback.CallbackHandler; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; -import com.sun.jaspic.services.JaspicServices; +import org.glassfish.epicyro.config.helper.AuthMessagePolicy; +import org.glassfish.epicyro.services.BaseAuthenticationService; /** * This is based Helper class for 196 Configuration. */ -public abstract class PayaraJaspicServices extends JaspicServices { +public abstract class PayaraEpicyroServices extends BaseAuthenticationService { /** * Get the default callback handler diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServletServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java similarity index 86% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServletServices.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java index 8b4d5054cf5..ba6a29e30b4 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServletServices.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java @@ -37,11 +37,11 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jaspic.config; import static com.sun.enterprise.deployment.web.LoginConfiguration.CLIENT_CERTIFICATION_AUTHENTICATION; -import static com.sun.enterprise.security.jaspic.config.GFServerConfigProvider.HTTPSERVLET; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.POLICY_CONTEXT; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.WEB_BUNDLE; @@ -58,15 +58,18 @@ import com.sun.enterprise.deployment.web.LoginConfiguration; import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; import com.sun.enterprise.security.jacc.JaccWebAuthorizationManager; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; -public class PayaraJaspicServletServices extends PayaraJaspicServices { +public class PayaraEpicyroServletServices extends PayaraEpicyroServices { public static final String AUTH_TYPE = "jakarta.servlet.http.authType"; + + public static final String HTTPSERVLET = "HttpServlet"; private String realmName; - public PayaraJaspicServletServices(String appContext, Map map, CallbackHandler callbackHandler, String realmName, boolean isSystemApp, String defaultSystemProviderID) { + public PayaraEpicyroServletServices(String appContext, Map map, CallbackHandler callbackHandler, String realmName, boolean isSystemApp, String defaultSystemProviderID) { WebBundleDescriptor webBundle = null; @@ -84,7 +87,7 @@ public PayaraJaspicServletServices(String appContext, Map map, C } // Set realmName before init - init(HTTPSERVLET, appContext, map, callbackHandler, Globals.get(WebServicesDelegate.class)); + init(HTTPSERVLET, appContext, map, callbackHandler, (RegistrationWrapperRemover) Globals.get(WebServicesDelegate.class)); if (webBundle != null) { String policyContextId = JaccWebAuthorizationManager.getContextID(webBundle); @@ -106,7 +109,7 @@ public PayaraJaspicServletServices(String appContext, Map map, C // Register the Payara JASPIC provider - String jaspicRegistrationId = factory.registerConfigProvider( + String jaspicRegistrationId = authConfigFactory.registerConfigProvider( configProvider, HTTPSERVLET, appContext, "Payara provider: " + HTTPSERVLET + ":" + appContext); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java deleted file mode 100644 index 0c6e6642cbb..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java +++ /dev/null @@ -1,619 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import java.io.*; -import java.util.*; - -import java.lang.reflect.Method; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.AppConfigurationEntry; - -import com.sun.enterprise.security.jaspic.config.ConfigParser; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; -import com.sun.logging.LogDomains; - -/** - * This is a default file-based AuthConfig implementation. - * - * @version %I%, %G% - */ -class ConfigFile extends AuthConfig { - - // indicates the age of the configuration approximately in - // terms of the number of times refresh has been called - private int epoch; - - // parser class name - private String parserClassName; - - // parser - private ConfigParser parser; - - // package private for ConfigFileParser - static final String CLIENT = "client"; - static final String SERVER = "server"; - - private static final String DEFAULT_HANDLER_CLASS = "com.sun.enterprise.security.jaspic.callback.ContainerCallbackHandler"; - - private static final String DEFAULT_PARSER_CLASS = "com.sun.enterprise.security.jaspic.config.ConfigDomainParser"; - - private static final Logger logger = LogDomains.getLogger(ConfigFile.class, LogDomains.SECURITY_LOGGER); - - ConfigFile() throws IOException { - String propertyValue = System.getProperty("config.parser"); - if (propertyValue == null) { - parserClassName = DEFAULT_PARSER_CLASS; - } else { - parserClassName = propertyValue; - } - this.epoch = 1; - parser = ConfigFile.loadParser(parserClassName); - parser.initialize(null); - } - - /** - * Get a default ClientAuthContext. - * - * @return an instance of ConfigClient. - */ - @Override - public ClientAuthContext getClientAuthContext(String intercept, String id, AuthPolicy requestPolicy, AuthPolicy responsePolicy, - CallbackHandler handler) throws AuthException { - - ConfigFile.Entry[] entries = getEntries(intercept, id, requestPolicy, responsePolicy, CLIENT); - if (entries == null || entries.length == 0) { - return null; - } - - // instantiate and initialize modules up front as well - - if (handler == null) { - handler = ConfigFile.loadDefaultCallbackHandler(); - } else if (handler instanceof DependentCallbackHandler) { - handler = new DelegatingHandler(handler); - } - - for (int i = 0; i < entries.length; i++) { - entries[i].module = ConfigFile.createModule(entries[i], handler); - } - - return new ConfigClient(entries); - } - - /** - * Get a default ServerAuthContext. - * - * @return an instance of ConfigServer. - */ - @Override - public ServerAuthContext getServerAuthContext(String intercept, String id, AuthPolicy requestPolicy, AuthPolicy responsePolicy, - CallbackHandler handler) throws AuthException { - - ConfigFile.Entry[] entries = getEntries(intercept, id, requestPolicy, responsePolicy, SERVER); - if (entries == null || entries.length == 0) { - return null; - } - - // instantiate and initialize modules up front as well - - if (handler == null) { - handler = ConfigFile.loadDefaultCallbackHandler(); - } else if (handler instanceof DependentCallbackHandler) { - handler = new DelegatingHandler(handler); - } - - for (int i = 0; i < entries.length; i++) { - entries[i].module = ConfigFile.createModule(entries[i], handler); - } - - return new ConfigServer(entries); - } - - @Override - public void refresh() throws AuthException { - synchronized (this) { - ConfigParser nextParser; - int next = this.epoch + 1; - try { - nextParser = ConfigFile.loadParser(parserClassName); - } catch (IOException ioe) { - throw new AuthException(ioe.toString()); - } - this.epoch = (next == 0 ? 1 : next); - parser = nextParser; - } - } - - private ConfigFile.Entry[] getEntries(String intercept, String id, AuthPolicy requestPolicy, AuthPolicy responsePolicy, String type) { - - // get the parsed module config and DD information - - Map configMap; - - synchronized (parser) { - configMap = parser.getConfigMap(); - } - - if (configMap == null) { - return null; - } - - // get the module config info for this intercept - - GFServerConfigProvider.InterceptEntry intEntry = (GFServerConfigProvider.InterceptEntry) configMap.get(intercept); - if (intEntry == null || intEntry.getIdMap() == null) { - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("module config has no IDs configured for [" + intercept + "]"); - } - return null; - } - - // look up the DD's provider ID in the module config - - GFServerConfigProvider.IDEntry idEntry = null; - if (id == null || (idEntry = intEntry.getIdMap().get(id)) == null) { - - // either the DD did not specify a provider ID, - // or the DD-specified provider ID was not found - // in the module config. - // - // in either case, look for a default ID in the module config - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("DD did not specify ID, " + "or DD-specified ID for [" + intercept + "] not found in config -- " - + "attempting to look for default ID"); - } - - String defaultID; - if (CLIENT.equals(type)) { - defaultID = intEntry.getDefaultClientID(); - } else { - defaultID = intEntry.getDefaultServerID(); - } - - idEntry = intEntry.getIdMap().get(defaultID); - if (idEntry == null) { - - // did not find a default provider ID - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("no default config ID for [" + intercept + "]"); - } - return null; - } - } - - // we found the DD provider ID in the module config - // or we found a default module config - - // check provider-type - if (idEntry.getType().indexOf(type) < 0) { - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("request type [" + type + "] does not match config type [" + idEntry.getType() + "]"); - } - return null; - } - - // check whether a policy is set - AuthPolicy reqP, respP; - if (requestPolicy != null || responsePolicy != null) { - reqP = requestPolicy; - respP = responsePolicy; - } else if (idEntry.getRequestPolicy() != null || idEntry.getResponsePolicy() != null) { - // default - reqP = new AuthPolicy(idEntry.getRequestPolicy()); - respP = new AuthPolicy(idEntry.getResponsePolicy()); - } else { - // optimization: if policy was not set, return null - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("no policy applies"); - } - return null; - } - - // return the configured modules with the correct policies - - // ConfigFile.Entry[] entries = new Entry[idEntry.modules.size()]; - ConfigFile.Entry[] entries = new Entry[1]; - for (int i = 0; i < entries.length; i++) { - // Login Bridge profile? - entries[i] = new ConfigFile.Entry(reqP, respP, idEntry.getModuleClassName(), - AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, idEntry.getOptions()); - } - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("getEntries found " + entries.length + " entries for: " + intercept + " -- " + id); - - for (int i = 0; i < entries.length; i++) { - logger.fine("Entry " + (i + 1) + ":" + "\n module class: " + entries[i].getLoginModuleName() + "\n flag: " - + entries[i].getControlFlag() + "\n options: " + entries[i].getOptions() + "\n request policy: " - + entries[i].requestPolicy + "\n response policy: " + entries[i].responsePolicy); - } - - } - - return entries; - } - - /** - * get a custom config file parser - * - * XXX custom file that can be used in place of [domain|sun-acc].xml - */ - private static ConfigParser loadParser(String className) throws IOException { - try { - - final String finalClassName = className; - final ClassLoader finalLoader = AuthConfig.getClassLoader(); - - return (ConfigParser) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - Class c = Class.forName(finalClassName, true, finalLoader); - return c.newInstance(); - } - }); - } catch (java.security.PrivilegedActionException pae) { - IOException iex = new IOException(pae.getException().toString()); - iex.initCause(pae.getException()); - throw iex; - } - } - - /** - * get the default callback handler - */ - private static CallbackHandler loadDefaultCallbackHandler() throws AuthException { - - // get the default handler class - try { - - final ClassLoader finalLoader = AuthConfig.getClassLoader(); - - return (CallbackHandler) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - - String className = DEFAULT_HANDLER_CLASS; - Class c = Class.forName(className, true, finalLoader); - return c.newInstance(); - } - }); - } catch (java.security.PrivilegedActionException pae) { - AuthException aex = new AuthException(pae.getException().toString()); - aex.initCause(pae.getException()); - throw aex; - } - } - - /** - * Instantiate+initialize module class - */ - private static Object createModule(ConfigFile.Entry entry, CallbackHandler handler) throws AuthException { - try { - - // instantiate module using no-arg constructor - - Object newModule = entry.newInstance(); - - // initialize module - - Object[] initArgs = { entry.getRequestPolicy(), entry.getResponsePolicy(), handler, entry.getOptions() }; - - try { - Method initMethod = newModule.getClass().getMethod(AuthContext.INIT, AuthPolicy.class, AuthPolicy.class, - CallbackHandler.class, Map.class); - initMethod.invoke(newModule, initArgs); - // return the new module - return newModule; - } catch (Exception ex) { - throw new SecurityException( - "could not invoke " + AuthContext.INIT + " method in module: " + newModule.getClass().getName() + " " + ex, ex); - } - - } catch (Exception e) { - if (e instanceof AuthException) { - throw (AuthException) e; - } - AuthException ae = new AuthException(); - ae.initCause(e); - throw ae; - } - } - - /** - * Class representing a single AuthModule entry configured for an ID, interception point, and stack. - * - *

- * An instance of this class contains the same information as its superclass, AppConfigurationEntry. It additionally - * stores the request and response policy assigned to this module. - * - *

- * This class also provides a way for a caller to obtain an instance of the module listed in the entry by invoking the - * newInstance method. - */ - static class Entry extends javax.security.auth.login.AppConfigurationEntry { - - // for loading modules - private static final Class[] PARAMS = {}; - private static final Object[] ARGS = {}; - - private AuthPolicy requestPolicy; - private AuthPolicy responsePolicy; - Object module = null; // convenience location to store instance - - // package private for AuthContext - - /** - * Construct a ConfigFile entry. - * - *

- * An entry encapsulates a single module and its related information. - * - * @param requestPolicy the request policy assigned to the module listed in this entry, which may be null. - * - * @param responsePolicy the response policy assigned to the module listed in this entry, which may be null. - * - * @param moduleClass the fully qualified class name of the module. - * - * @param flag the module control flag. This value must either be REQUIRED, REQUISITE, SUFFICIENT, or OPTIONAL. - * - * @param options the options configured for this module. - */ - Entry(AuthPolicy requestPolicy, AuthPolicy responsePolicy, String moduleClass, AppConfigurationEntry.LoginModuleControlFlag flag, - Map options) { - super(moduleClass, flag, options); - this.requestPolicy = requestPolicy; - this.responsePolicy = responsePolicy; - } - - /** - * Return the request policy assigned to this module. - * - * @return the policy, which may be null. - */ - AuthPolicy getRequestPolicy() { - return requestPolicy; - } - - /** - * Return the response policy assigned to this module. - * - * @return the policy, which may be null. - */ - AuthPolicy getResponsePolicy() { - return responsePolicy; - } - - /** - * Return a new instance of the module contained in this entry. - * - *

- * The default implementation of this method attempts to invoke the default no-args constructor of the module class. - * This method may be overridden if a different constructor should be invoked. - * - * @return a new instance of the module contained in this entry. - * - * @exception AuthException if the instantiation failed. - */ - Object newInstance() throws AuthException { - try { - final ClassLoader finalLoader = AuthConfig.getClassLoader(); - String clazz = getLoginModuleName(); - Class c = Class.forName(clazz, true, finalLoader); - java.lang.reflect.Constructor constructor = c.getConstructor(PARAMS); - return constructor.newInstance(ARGS); - } catch (Exception e) { - AuthException ae = new AuthException(); - ae.initCause(e); - throw ae; - } - } - } - - /** - * parsed Intercept entry - */ - /* - * static class InterceptEntry { String defaultClientID; String defaultServerID; HashMap idMap; InterceptEntry(String - * defaultClientID, String defaultServerID, HashMap idMap) { this.defaultClientID = defaultClientID; - * this.defaultServerID = defaultServerID; this.idMap = idMap; } } - */ - - /** - * parsed ID entry - */ - /* - * static class IDEntry { private String type; // provider type (client, server, client-server) private AuthPolicy - * requestPolicy; private AuthPolicy responsePolicy; private ArrayList modules; IDEntry(String type, AuthPolicy - * requestPolicy, AuthPolicy responsePolicy, ArrayList modules) { this.type = type; this.modules = modules; - * this.requestPolicy = requestPolicy; this.responsePolicy = responsePolicy; } // XXX delete this later IDEntry(String - * type, String requestPolicy, String responsePolicy, ArrayList modules) { this.type = type; if (requestPolicy != null) - * { this.requestPolicy = new AuthPolicy(AuthPolicy.SOURCE_AUTH_SENDER, true, // recipient-auth true); // beforeContent - * } if (responsePolicy != null) { this.responsePolicy = new AuthPolicy(AuthPolicy.SOURCE_AUTH_CONTENT, true, // - * recipient-auth false); // beforeContent } this.modules = modules; } } - */ - - /** - * Default implementation of ClientAuthContext. - */ - private static class ConfigClient implements ClientAuthContext { - - // class that does all the work - private AuthContext context; - - ConfigClient(Entry[] entries) throws AuthException { - context = new AuthContext(entries, logger); - } - - @Override - public void secureRequest(AuthParam param, Subject subject, Map sharedState) throws AuthException { - - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.SECURE_REQUEST, args); - } - - @Override - public void validateResponse(AuthParam param, Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.VALIDATE_RESPONSE, args); - } - - @Override - public void disposeSubject(Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { subject, sharedState }; - context.invoke(AuthContext.DISPOSE_SUBJECT, args); - } - } - - /** - * Default implementation of ServerAuthContext. - */ - private static class ConfigServer implements ServerAuthContext { - - // class that does all the work - private AuthContext context; - - ConfigServer(Entry[] entries) throws AuthException { - - context = new AuthContext(entries, logger); - } - - @Override - public void validateRequest(AuthParam param, Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.VALIDATE_REQUEST, args); - } - - @Override - public void secureResponse(AuthParam param, Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.SECURE_RESPONSE, args); - } - - @Override - public void disposeSubject(Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { subject, sharedState }; - context.invoke(AuthContext.DISPOSE_SUBJECT, args); - } - - @Override - public boolean managesSessions(Map sharedState) throws AuthException { - - // invoke modules - Object[] args = { sharedState }; - Object[] rValues = null; - - try { - rValues = context.invoke(AuthContext.MANAGES_SESSIONS, args); - } catch (AuthException ae) { - // this new method may not be implemeneted - // by old modules - if (!(ae.getCause() instanceof NoSuchMethodException)) { - throw ae; - } - } - - boolean rvalue = false; - - for (int i = 0; rValues != null && i < rValues.length; i++) { - if (rValues[i] != null) { - boolean thisValue = ((Boolean) rValues[i]).booleanValue(); - rvalue = rvalue | thisValue; - } - } - - return rvalue; - } - } - - private static class DelegatingHandler implements CallbackHandler { - - CallbackHandler handler; - - CallbackHandler defaultHandler; - - private DelegatingHandler(CallbackHandler cbh) { - handler = cbh; - try { - defaultHandler = ConfigFile.loadDefaultCallbackHandler(); - } catch (Exception e) { - defaultHandler = null; - } - } - - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - if (defaultHandler == null) { - handler.handle(callbacks); - } else { - Callback[] oneCallback = new Callback[1]; - for (int i = 0; i < callbacks.length; i++) { - - boolean tryDefault = false; - - oneCallback[0] = callbacks[i]; - try { - handler.handle(oneCallback); - } catch (UnsupportedCallbackException uce) { - tryDefault = true; - } - if (tryDefault) { - defaultHandler.handle(oneCallback); - } - } - } - } - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java index 206dd3f6314..34139192e71 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2017-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] /* * PrincipalGroupFactory.java * @@ -50,8 +50,8 @@ import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; import org.jvnet.hk2.annotations.Service; +import org.glassfish.epicyro.config.helper.CallerPrincipal; import com.sun.enterprise.security.PrincipalGroupFactory; @@ -65,10 +65,10 @@ public class PrincipalGroupFactoryImpl implements PrincipalGroupFactory { private static WeakReference webSecurityManagerFactory = new WeakReference(null); @Override - public PrincipalImpl getPrincipalInstance(String name, String realm) { - PrincipalImpl principal = (PrincipalImpl) getWebSecurityManagerFactory().getAdminPrincipal(name, realm); + public CallerPrincipal getPrincipalInstance(String name, String realm) { + CallerPrincipal principal = (CallerPrincipal) getWebSecurityManagerFactory().getAdminPrincipal(name, realm); if (principal == null) { - principal = new PrincipalImpl(name); + principal = new CallerPrincipal(name); } return principal; diff --git a/appserver/security/jaspic-provider-framework/osgi.bundle b/appserver/security/jaspic-provider-framework/osgi.bundle index c0460d0b2f0..46a378460ef 100644 --- a/appserver/security/jaspic-provider-framework/osgi.bundle +++ b/appserver/security/jaspic-provider-framework/osgi.bundle @@ -37,8 +37,8 @@ # only if the new code is made subject to such option by the copyright # holder. # --exportcontents: \ - com.sun.jaspic.services; \ +# Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] +-exportcontents: \ com.sun.jaspic.config.delegate; \ com.sun.jaspic.config.factory; \ com.sun.jaspic.config.jaas; \ diff --git a/appserver/security/jaspic-provider-framework/pom.xml b/appserver/security/jaspic-provider-framework/pom.xml index cb53f558935..e923a2c6615 100644 --- a/appserver/security/jaspic-provider-framework/pom.xml +++ b/appserver/security/jaspic-provider-framework/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -83,5 +83,9 @@ org.glassfish.soteria jakarta.security.enterprise + + org.glassfish.epicyro + epicyro + diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java deleted file mode 100644 index f46ad3325e8..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -/** - * - * @author ronmonzillo - */ -public class AuthConfigFileFactory extends BaseAuthConfigFactory { - - // MUST "hide" regStore in derived class. - private static volatile RegStoreFileParser regStore; - - /** - * To specialize the defaultEntries passed to the {@link RegStoreFileParser} constructor, create another subclass of - * BaseAuthconfigFactory, that is basically a copy of this class, with a change to the third argument of the call to new - * ResSToreFileParser. To ensure runtime use of the the associated regStore, make sure that the new subclass also - * contains an implementation of the getRegStore method. - * - *

- * As done within this class, use the locks defined in BaseAuthConfigFactory to serialize access to the regStore (both - * within the class constructor, and within getRegStore) - *

- * - *

- * All EentyInfo OBJECTS PASSED as default Entries MUST HAVE BEEN CONSTRUCTED USING THE FOLLOWING CONSTRUCTOR: - * EntryInfo(String className, Map properties); - * - *

- * - */ - public AuthConfigFileFactory() { - if (doReadLocked(() -> regStore != null)) { - return; - } - - String userDir = System.getProperty("user.dir"); - - doWriteLocked(() -> { - if (regStore == null) { - regStore = new RegStoreFileParser(userDir, CONF_FILE_NAME, null); - _loadFactory(); - } - }); - } - - @Override - protected RegStoreFileParser getRegStore() { - return doReadLocked(() -> regStore); - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java deleted file mode 100644 index 851a6f0bccb..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright 2018-2024 Payara Foundation and/or its affiliates -package com.sun.jaspic.config.factory; - -import static com.sun.jaspic.config.helper.JASPICLogManager.JASPIC_LOGGER; -import static com.sun.jaspic.config.helper.JASPICLogManager.RES_BUNDLE; -import static java.util.logging.Level.WARNING; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.function.Supplier; -import java.util.logging.Logger; - -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.RegistrationListener; -import jakarta.security.auth.message.module.ServerAuthModule; -import jakarta.servlet.ServletContext; -import static org.glassfish.soteria.Utils.isEmpty; - - -/** - * This class implements methods in the abstract class AuthConfigFactory. - * - * @author Shing Wai Chan - */ -public abstract class BaseAuthConfigFactory extends AuthConfigFactory { - - private static final Logger logger = Logger.getLogger(JASPIC_LOGGER, RES_BUNDLE); - - private static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); - - public static final Lock readLock = readWriteLock.readLock(); - public static final Lock writeLock = readWriteLock.writeLock(); - - private static Map idToProviderMap; - private static Map idToRegistrationContextMap; - private static Map> idToRegistrationListenersMap; - private static Map> providerToIdsMap; - - protected static final String CONF_FILE_NAME = "auth.conf"; - private static final String CONTEXT_REGISTRATION_ID = "org.glassfish.security.message.registrationId"; - - /** - * Get a registered AuthConfigProvider from the factory. - * - * Get the provider of ServerAuthConfig and/or ClientAuthConfig objects registered for the identified message layer and - * application context. - * - *

- * All factories shall employ the following precedence rules to select the registered AuthConfigProvider that matches - * (via matchConstructors) the layer and appContext arguments: - *

    - *
  • The provider that is specifically registered for both the corresponding message layer and appContext shall be - * selected. - *
  • if no provider is selected according to the preceding rule, the provider specifically registered for the - * corresponding appContext and for all message layers shall be selected. - *
  • if no provider is selected according to the preceding rules, the provider specifically registered for the - * corresponding message layer and for all appContexts shall be selected. - *
  • if no provider is selected according to the preceding rules, the provider registered for all message layers and - * for all appContexts shall be selected. - *
  • if no provider is selected according to the preceding rules, the factory shall terminate its search for a - * registered provider. - *
- * - * @param layer a String identifying the message layer for which the registered AuthConfigProvider is to be returned. - * This argument may be null. - * - * @param appContext a String that identifies the application messaging context for which the registered - * AuthConfigProvider is to be returned. This argument may be null. - * - * @param listener the RegistrationListener whose notify method is to be invoked if the corresponding - * registration is unregistered or replaced. The value of this argument may be null. - * - * @return the implementation of the AuthConfigProvider interface registered at the factory for the layer and appContext - * or null if no AuthConfigProvider is selected. - * - */ - @Override - public AuthConfigProvider getConfigProvider(String layer, String appContext, RegistrationListener listener) { - if (listener == null) { - return doReadLocked(() -> getConfigProviderUnderLock(layer, appContext, null)); - } - - return doWriteLocked(() -> getConfigProviderUnderLock(layer, appContext, listener)); - } - - /** - * Registers within the factory, a provider of ServerAuthConfig and/or ClientAuthConfig objects for a message layer and - * application context identifier. - * - *

- * At most one registration may exist within the factory for a given combination of message layer and appContext. Any - * pre-existing registration with identical values for layer and appContext is replaced by a subsequent registration. - * When replacement occurs, the registration identifier, layer, and appContext identifier remain unchanged, and the - * AuthConfigProvider (with initialization properties) and description are replaced. - * - *

- * Within the lifetime of its Java process, a factory must assign unique registration identifiers to registrations, and - * must never assign a previously used registration identifier to a registration whose message layer and or appContext - * identifier differ from the previous use. - * - *

- * Programmatic registrations performed via this method must update (according to the replacement rules described - * above), the persistent declarative representation of provider registrations employed by the factory constructor. - * - * @param className the fully qualified name of an AuthConfigProvider implementation class. This argument must not be - * null. - * - * @param properties a Map object containing the initialization properties to be passed to the provider constructor. - * This argument may be null. When this argument is not null, all the values and keys occuring in the Map must be of - * type String. - * - * @param layer a String identifying the message layer for which the provider will be registered at the factory. A null - * value may be passed as an argument for this parameter, in which case, the provider is registered at all layers. - * - * @param appContext a String value that may be used by a runtime to request a configuration object from this provider. - * A null value may be passed as an argument for this parameter, in which case, the provider is registered for all - * configuration ids (at the indicated layers). - * - * @param description a text String describing the provider. this value may be null. - * - * @return a String identifier assigned by the factory to the provider registration, and that may be used to remove the - * registration from the provider. - * - * @exception SecurityException If the provider construction (given a non-null className) or - * registration fails. - * - * @exception AuthException if the provider construction or registration fails. - */ - @Override - @SuppressWarnings("unchecked") - public String registerConfigProvider(String className, @SuppressWarnings("rawtypes") Map properties, String layer, String appContext, - String description) { - return _register(_constructProvider(className, properties, null), properties, layer, appContext, description, true); - } - - @Override - public String registerConfigProvider(AuthConfigProvider provider, String layer, String appContext, String description) { - return _register(provider, null, layer, appContext, description, false); - } - - /** - * Remove the identified provider registration from the factory and invoke any listeners associated with the removed - * registration. - * - * @param registrationID a String that identifies a provider registration at the factory - * - * @return true if there was a registration with the specified identifier and it was removed. Return false if the - * registraionID was invalid. - * - */ - @Override - public boolean removeRegistration(String registrationID) { - return _unRegister(registrationID); - } - - /** - * Disassociate the listener from all the provider registrations whose layer and appContext values are matched by the - * corresponding arguments to this method. - * - * @param listener the RegistrationListener to be detached. - * - * @param layer a String identifying the message layer or null. - * - * @param appContext a String value identifying the application context or null. - * - * @return an array of String values where each value identifies a provider registration from which the listener was - * removed. This method never returns null; it returns an empty array if the listener was not removed from any - * registrations. - * - */ - @Override - public String[] detachListener(RegistrationListener listener, String layer, String appContext) { - List removedListenerIds = new ArrayList<>(); - String registrationId = getRegistrationID(layer, appContext); - - doWriteLocked(() -> { - for (Entry> entry : idToRegistrationListenersMap.entrySet()) { - String targetID = entry.getKey(); - if (regIdImplies(registrationId, targetID)) { - List listeners = entry.getValue(); - if (listeners != null && listeners.remove(listener)) { - removedListenerIds.add(targetID); - } - } - } - }); - - return removedListenerIds.toArray(new String[removedListenerIds.size()]); - } - - /** - * Get the registration identifiers for all registrations of the provider instance at the factory. - * - * @param provider the AuthConfigurationProvider whose registration identifiers are to be returned. This argument may be - * null, in which case, it indicates that the the id's of all active registration within the factory are returned. - * - * @return an array of String values where each value identifies a provider registration at the factory. This method - * never returns null; it returns an empty array when their are no registrations at the factory for the identified - * provider. - */ - @Override - public String[] getRegistrationIDs(AuthConfigProvider provider) { - return doReadLocked(() -> { - Collection registrationIDs = null; - - if (provider != null) { - registrationIDs = providerToIdsMap.get(provider); - } else { - Collection> collList = providerToIdsMap.values(); - if (collList != null) { - registrationIDs = new HashSet<>(); - for (List listIds : collList) { - if (listIds != null) { - registrationIDs.addAll(listIds); - } - } - } - } - - return registrationIDs != null ? registrationIDs.toArray(new String[registrationIDs.size()]) : new String[0]; - }); - } - - /** - * Get the the registration context for the identified registration. - * - * @param registrationID a String that identifies a provider registration at the factory - * - * @return a RegistrationContext or null. When a Non-null value is returned, it is a copy of the registration context - * corresponding to the registration. Null is returned when the registration identifier does not correspond to an active - * registration - */ - @Override - public RegistrationContext getRegistrationContext(String registrationID) { - return doReadLocked(() -> idToRegistrationContextMap.get(registrationID)); - } - - /** - * Cause the factory to reprocess its persistent declarative representation of provider registrations. - * - *

- * A factory should only replace an existing registration when a change of provider implementation class or - * initialization properties has occurred. - * - * @exception AuthException if an error occurred during the reinitialization. - * - * @exception SecurityException If an error occurred during the reinitialization. - */ - @Override - public void refresh() { - Map> preExistingListenersMap = doWriteLocked(() -> loadFactory()); - - // Notify pre-existing listeners after (re)loading factory - if (preExistingListenersMap != null) { - notifyListeners(preExistingListenersMap); - } - } - - abstract protected RegStoreFileParser getRegStore(); - - private AuthConfigProvider getConfigProviderUnderLock(String layer, String appContext, RegistrationListener listener) { - AuthConfigProvider provider = null; - String registrationID = getRegistrationID(layer, appContext); - - boolean providerFound = false; - if (idToProviderMap.containsKey(registrationID)) { - provider = idToProviderMap.get(registrationID); - providerFound = true; - } - - if (!providerFound) { - String matchedID = getRegistrationID(null, appContext); - if (idToProviderMap.containsKey(matchedID)) { - provider = idToProviderMap.get(matchedID); - providerFound = true; - } - } - - if (!providerFound) { - String matchedID = getRegistrationID(layer, null); - if (idToProviderMap.containsKey(matchedID)) { - provider = idToProviderMap.get(matchedID); - providerFound = true; - } - } - - if (!providerFound) { - String matchedID = getRegistrationID(null, null); - if (idToProviderMap.containsKey(matchedID)) { - provider = idToProviderMap.get(matchedID); - } - } - - if (listener != null) { - List listeners = idToRegistrationListenersMap.computeIfAbsent( - registrationID, e -> new ArrayList()); - - if (!listeners.contains(listener)) { - listeners.add(listener); - } - } - - return provider; - } - - private static String getRegistrationID(String layer, String appContext) { - - // (layer, appContext) -> __3_ - // (layer, null) -> __2 - // (null, appContext) -> __1 - // (null, null) -> __0 - - if (layer != null) { - return appContext != null ? "__3" + layer.length() + "_" + layer + appContext : "__2" + layer; - } - - return appContext != null ? "__1" + appContext : "__0"; - } - - /** - * This API decomposes the given registration ID into layer and appContext. - * - * @param registrationId - * @return a String array with layer and appContext - */ - private static String[] decomposeRegistrationId(String registrationId) { - String layer = null; - String appContext = null; - - if (registrationId.equals("__0")) { - // null, null - } else if (registrationId.startsWith("__1")) { - appContext = (registrationId.length() == 3) ? "" : registrationId.substring(3); - } else if (registrationId.startsWith("__2")) { - layer = (registrationId.length() == 3) ? "" : registrationId.substring(3); - } else if (registrationId.startsWith("__3")) { - int ind = registrationId.indexOf('_', 3); - if (registrationId.length() > 3 && ind > 0) { - String numberString = registrationId.substring(3, ind); - int n; - try { - n = Integer.parseInt(numberString); - } catch (Exception ex) { - throw new IllegalArgumentException(); - } - layer = registrationId.substring(ind + 1, ind + 1 + n); - appContext = registrationId.substring(ind + 1 + n); - } else { - throw new IllegalArgumentException(); - } - } else { - throw new IllegalArgumentException(); - } - - return new String[] { layer, appContext }; - } - - private static AuthConfigProvider _constructProvider(String className, Map properties, AuthConfigFactory factory) { - AuthConfigProvider provider = null; - - if (className != null) { - try { - provider = (AuthConfigProvider) Class.forName(className, true, Thread.currentThread().getContextClassLoader()) - .getConstructor(Map.class, AuthConfigFactory.class) - .newInstance(new Object[] { properties, factory }); - } catch (Throwable t) { - Throwable cause = t.getCause(); - logger.log(WARNING, "jaspic.factory_unable_to_load_provider", - new Object[] { className, t.toString(), cause == null ? "cannot determine" : cause.toString() }); - } - } - - return provider; - } - - // XXX need to update persistent state and notify effected listeners - private String _register(AuthConfigProvider provider, Map properties, String layer, String appContext, - String description, boolean persistent) { - String registrationId = getRegistrationID(layer, appContext); - RegistrationContext registrationContext = new RegistrationContextImpl(layer, appContext, description, persistent); - - Map> listenerMap = doWriteLocked( - () -> register(provider, properties, persistent, registrationId, registrationContext)); - - // Outside write lock to prevent dead lock - notifyListeners(listenerMap); - - return registrationId; - } - - private Map> register(AuthConfigProvider provider, Map properties, - boolean persistent, String registrationId, RegistrationContext registrationContext) { - RegistrationContext previousRegistrationContext = idToRegistrationContextMap.get(registrationId); - AuthConfigProvider previousProvider = idToProviderMap.get(registrationId); - - // Handle the persistence first - so that any exceptions occur before - // the actual registration happens - if (persistent) { - _storeRegistration(registrationContext, provider, properties); - } else if (previousRegistrationContext != null && previousRegistrationContext.isPersistent()) { - _deleteStoredRegistration(previousRegistrationContext); - } - - if (idToProviderMap.containsKey(registrationId)) { - List previousRegistrationsIds = providerToIdsMap.get(previousProvider); - previousRegistrationsIds.remove(registrationId); - if (previousRegistrationsIds.isEmpty()) { - providerToIdsMap.remove(previousProvider); - } - } - - idToProviderMap.put(registrationId, provider); - idToRegistrationContextMap.put(registrationId, registrationContext); - - List registrationIds = providerToIdsMap.computeIfAbsent(provider, e -> new ArrayList()); - - if (!registrationIds.contains(registrationId)) { - registrationIds.add(registrationId); - } - - return getEffectedListeners(registrationId); - } - - // XXX need to update persistent state and notify effected listeners - private boolean _unRegister(String registrationId) { - boolean hasProvider = false; - Map> listenerMap; - - writeLock.lock(); - try { - RegistrationContext registrationContext = idToRegistrationContextMap.remove(registrationId); - hasProvider = idToProviderMap.containsKey(registrationId); - AuthConfigProvider provider = idToProviderMap.remove(registrationId); - - List registrationIds = providerToIdsMap.get(provider); - if (registrationIds != null) { - registrationIds.remove(registrationId); - } - - if (registrationIds == null || registrationIds.isEmpty()) { - providerToIdsMap.remove(provider); - } - - if (!hasProvider) { - return false; - } - - listenerMap = getEffectedListeners(registrationId); - if (registrationContext != null && registrationContext.isPersistent()) { - _deleteStoredRegistration(registrationContext); - } - } finally { - writeLock.unlock(); - } - - // Outside write lock to prevent dead lock - notifyListeners(listenerMap); - - return hasProvider; - } - - private Map> loadFactory() { - Map> oldId2RegisListenersMap = idToRegistrationListenersMap; - - _loadFactory(); - - return oldId2RegisListenersMap; - } - - // ### The following methods implement the factory's persistence layer - - protected void _loadFactory() { - try { - initializeMaps(); - - List persistedEntries = getRegStore().getPersistedEntries(); - - for (EntryInfo info : persistedEntries) { - if (info.isConstructorEntry()) { - _constructProvider(info.getClassName(), info.getProperties(), this); - } else { - boolean first = true; - AuthConfigProvider configProvider = null; - for (RegistrationContext context : info.getRegistrationContexts()) { - if (first) { - configProvider = _constructProvider(info.getClassName(), info.getProperties(), null); - } - - _loadRegistration(configProvider, context.getMessageLayer(), context.getAppContext(), context.getDescription()); - } - } - } - } catch (Exception e) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_auth_config_loader_failure", e); - } - } - } - - /** - * Initialize the static maps in a static method - */ - private static void initializeMaps() { - idToProviderMap = new HashMap<>(); - idToRegistrationContextMap = new HashMap<>(); - idToRegistrationListenersMap = new HashMap<>(); - providerToIdsMap = new HashMap<>(); - } - - private static String _loadRegistration(AuthConfigProvider provider, String layer, String appContext, String description) { - - RegistrationContext registrationContext = new RegistrationContextImpl(layer, appContext, description, true); - String registrationId = getRegistrationID(layer, appContext); - - AuthConfigProvider previousProvider = idToProviderMap.get(registrationId); - - boolean wasRegistered = idToProviderMap.containsKey(registrationId); - if (wasRegistered) { - List previousRegistrationIds = providerToIdsMap.get(previousProvider); - previousRegistrationIds.remove(registrationId); - if (previousRegistrationIds.isEmpty()) { - providerToIdsMap.remove(previousProvider); - } - } - - idToProviderMap.put(registrationId, provider); - idToRegistrationContextMap.put(registrationId, registrationContext); - - List registrationIds = providerToIdsMap.get(provider); - if (registrationIds == null) { - registrationIds = new ArrayList<>(); - providerToIdsMap.put(provider, registrationIds); - } - - if (!registrationIds.contains(registrationId)) { - registrationIds.add(registrationId); - } - - return registrationId; - } - - private void _storeRegistration(RegistrationContext registrationContext, AuthConfigProvider configProvider, - Map properties) { - String className = null; - if (configProvider != null) { - className = configProvider.getClass().getName(); - } - - if (propertiesContainAnyNonStringValues(properties)) { - throw new IllegalArgumentException("AuthConfigProvider cannot be registered - properties must all be of type String."); - } - - if (registrationContext.isPersistent()) { - getRegStore().store(className, registrationContext, properties); - } - } - - private boolean propertiesContainAnyNonStringValues(Map properties) { - if (properties != null) { - for (Map.Entry entry : properties.entrySet()) { - if (!(entry.getValue() instanceof String)) { - return true; - } - } - } - - return false; - } - - private void _deleteStoredRegistration(RegistrationContext registrationContext) { - if (registrationContext.isPersistent()) { - getRegStore().delete(registrationContext); - } - } - - private static boolean regIdImplies(String reference, String target) { - - boolean rvalue = true; - - String[] refID = decomposeRegistrationId(reference); - String[] targetID = decomposeRegistrationId(target); - - if (refID[0] != null && !refID[0].equals(targetID[0])) { - rvalue = false; - } else if (refID[1] != null && !refID[1].equals(targetID[1])) { - rvalue = false; - } - - return rvalue; - } - - /** - * Will return some extra listeners. In other words, effected listeners could be reduced by removing any associated with - * a provider registration id that is more specific than the one being added or removed. - */ - private static Map> getEffectedListeners(String regisID) { - Map> effectedListeners = new HashMap<>(); - Set listenerRegistrations = new HashSet<>(idToRegistrationListenersMap.keySet()); - - for (String listenerID : listenerRegistrations) { - if (regIdImplies(regisID, listenerID)) { - if (!effectedListeners.containsKey(listenerID)) { - effectedListeners.put(listenerID, new ArrayList<>()); - } - effectedListeners.get(listenerID).addAll(idToRegistrationListenersMap.remove(listenerID)); - } - } - return effectedListeners; - } - - protected T doReadLocked(Supplier supplier) { - readLock.lock(); - try { - return supplier.get(); - } finally { - readLock.unlock(); - } - } - - protected T doWriteLocked(Supplier supplier) { - writeLock.lock(); - try { - return supplier.get(); - } finally { - writeLock.unlock(); - } - } - - protected void doWriteLocked(Runnable runnable) { - writeLock.lock(); - try { - runnable.run(); - } finally { - writeLock.unlock(); - } - } - - private static void notifyListeners(Map> map) { - Set>> entrySet = map.entrySet(); - for (Map.Entry> entry : entrySet) { - List listeners = map.get(entry.getKey()); - - if (listeners != null && listeners.size() > 0) { - String[] dIds = decomposeRegistrationId(entry.getKey()); - - for (RegistrationListener listener : listeners) { - listener.notify(dIds[0], dIds[1]); - } - } - } - } - - @Override - public String registerServerAuthModule(ServerAuthModule sam, Object context) { - String registrationId = null; - if (context instanceof ServletContext) { - ServletContext servletContext = (ServletContext) context; - - String appContext = servletContext.getVirtualServerName() + " " + servletContext.getContextPath(); - registrationId = registerConfigProvider(new DefaultAuthConfigProvider(sam), "HttpServlet", appContext, - "Default authentication config provider"); - - servletContext.setAttribute(CONTEXT_REGISTRATION_ID, registrationId); - } - return registrationId; - } - - @Override - public void removeServerAuthModule(Object context) { - if (context instanceof ServletContext) { - ServletContext servletContext = (ServletContext) context; - String registrationId = (String) servletContext.getAttribute(CONTEXT_REGISTRATION_ID); - if (!isEmpty(registrationId)) { - removeRegistration(registrationId); - } - } - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java deleted file mode 100644 index 0330d918878..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -import static com.sun.jaspic.config.helper.JASPICLogManager.JASPIC_LOGGER; -import static com.sun.jaspic.config.helper.JASPICLogManager.RES_BUNDLE; -import static java.util.logging.Level.FINER; -import static java.util.logging.Level.INFO; -import static java.util.logging.Level.WARNING; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.logging.Logger; - -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; - -/** - * Used by ServerConfigProvider to parse the configuration file. If a file does not exist originally, the default - * providers are not used. A file is only created if needed, which happens if providers are registered or unregistered - * through the store() or delete() methods. - * - * @author Bobby Bissett - */ -public final class RegStoreFileParser { - - private static final Logger logger = Logger.getLogger(JASPIC_LOGGER, RES_BUNDLE); - - private static final String SEP = ":"; - private static final String CON_ENTRY = "con-entry"; - private static final String REG_ENTRY = "reg-entry"; - private static final String REG_CTX = "reg-ctx"; - private static final String LAYER = "layer"; - private static final String APP_CTX = "app-ctx"; - private static final String DESCRIPTION = "description"; - private static final String[] INDENT = { "", " ", " " }; - - private final File configurationFile; - private List entries; - private List defaultEntries; - - /** - * Loads the configuration file from the given filename. If a file is not found, then the default entries are used. - * Otherwise the file is parsed to load the entries. - * - */ - public RegStoreFileParser(String pathParent, String pathChild, List defaultEntries) { - configurationFile = new File(pathParent, pathChild); - this.defaultEntries = defaultEntries == null ? new ArrayList() : defaultEntries; - - try { - loadEntries(); - } catch (IOException ioe) { - logWarningDefault(ioe); - } catch (IllegalArgumentException iae) { - logWarningDefault(iae); - } - } - - /** - * Returns the in-memory list of entries. MUST Hold exclusive lock on calling factory while processing entries - */ - List getPersistedEntries() { - return entries; - } - - /** - * Adds the provider to the entry list if it is not already present, creates the configuration file if necessary, and - * writes the entries to the file. - */ - void store(String className, RegistrationContext registrationContext, Map properties) { - synchronized (configurationFile) { - if (checkAndAddToList(className, registrationContext, properties)) { - try { - writeEntries(); - } catch (IOException ioe) { - logWarningUpdated(ioe); - } - } - } - } - - /** - * Removes the provider from the entry list if it is already present, creates the configuration file if necessary, and - * writes the entries to the file. - */ - void delete(RegistrationContext registrationContext) { - synchronized (configurationFile) { - if (checkAndRemoveFromList(registrationContext)) { - try { - writeEntries(); - } catch (IOException ioe) { - logWarningUpdated(ioe); - } - } - } - } - - /** - * If this entry does not exist, this method stores it in the entries list and returns true to indicate that the - * configuration file should be written. - */ - private boolean checkAndAddToList(String className, RegistrationContext registrationContext, Map properties) { - - // Convention is to use null for empty properties - if (properties != null && properties.isEmpty()) { - properties = null; - } - - EntryInfo newEntry = new EntryInfo(className, properties, registrationContext); - EntryInfo entry = getMatchingRegistrationEntry(newEntry); - - // There is no matching entry, so add to list - if (entry == null) { - entries.add(newEntry); - return true; - } - - // Otherwise, check reg contexts to see if there is a match - if (entry.getRegistrationContexts().contains(registrationContext)) { - return false; - } - - // No matching context in existing entry, so add to existing entry - entry.getRegistrationContexts().add(new RegistrationContextImpl(registrationContext)); - - return true; - } - - /** - * If this registration context does not exist, this method returns false. Otherwise it removes the entry and returns - * true to indicate that the configuration file should be written. - * - * This only makes sense for registry entries. - */ - private boolean checkAndRemoveFromList(RegistrationContext target) { - boolean retValue = false; - try { - ListIterator lit = entries.listIterator(); - while (lit.hasNext()) { - - EntryInfo info = lit.next(); - if (info.isConstructorEntry()) { - continue; - } - - Iterator iter = info.getRegistrationContexts().iterator(); - while (iter.hasNext()) { - RegistrationContext ctx = iter.next(); - if (ctx.equals(target)) { - iter.remove(); - if (info.getRegistrationContexts().isEmpty()) { - lit.remove(); - } - retValue = true; - } - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - - return retValue; - } - - /** - * Used to find a matching registration entry in the 'entries' list without including registration contexts. If there is - * not a matching entry, return null. - */ - private EntryInfo getMatchingRegistrationEntry(EntryInfo target) { - for (EntryInfo info : entries) { - if (!info.isConstructorEntry() && info.matchConstructors(target)) { - return info; - } - } - - return null; - } - - /** - * This method overwrites the existing file with the current entries. - */ - private void writeEntries() throws IOException { - if (configurationFile.exists() && !configurationFile.canWrite() && logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_cannot_write_file", configurationFile.getPath()); - } - - clearExistingFile(); - - PrintWriter out = new PrintWriter(configurationFile); - int indent = 0; - for (EntryInfo info : entries) { - if (info.isConstructorEntry()) { - writeConEntry(info, out, indent); - } else { - writeRegEntry(info, out, indent); - } - } - out.close(); - } - - /** - * Writes constructor entry output of the form: - * - *

-     *  con-entry { className key:value key:value }
-     * 
- * - * The first appearance of a colon ":" separates the key and value of the property (so a value may contain a colon as - * part of the string). For instance: "mydir:c:foo" would have key "mydir" and value "c:foo". - */ - private void writeConEntry(EntryInfo info, PrintWriter out, int i) { - out.println(INDENT[i++] + CON_ENTRY + " {"); - out.println(INDENT[i] + info.getClassName()); - - Map properties = info.getProperties(); - if (properties != null) { - for (Map.Entry val : properties.entrySet()) { - out.println(INDENT[i] + val.getKey() + SEP + val.getValue()); - } - } - - out.println(INDENT[--i] + "}"); - } - - /* - * Write registration entry output of the form:
 reg-entry { con-entry { see writeConEntry() for detail } reg-ctx {
-     * layer:HttpServlet app-ctx:security-jaspic-https description:My provider } } 
- */ - private void writeRegEntry(EntryInfo info, PrintWriter out, int i) { - out.println(INDENT[i++] + REG_ENTRY + " {"); - if (info.getClassName() != null) { - writeConEntry(info, out, i); - } - - for (RegistrationContext registrationContext : info.getRegistrationContexts()) { - out.println(INDENT[i++] + REG_CTX + " {"); - if (registrationContext.getMessageLayer() != null) { - out.println(INDENT[i] + LAYER + SEP + registrationContext.getMessageLayer()); - } - - if (registrationContext.getAppContext() != null) { - out.println(INDENT[i] + APP_CTX + SEP + registrationContext.getAppContext()); - } - - if (registrationContext.getDescription() != null) { - out.println(INDENT[i] + DESCRIPTION + SEP + registrationContext.getDescription()); - } - - out.println(INDENT[--i] + "}"); - } - - out.println(INDENT[--i] + "}"); - } - - private void clearExistingFile() throws IOException { - boolean newCreation = !configurationFile.exists(); - - if (!newCreation) { - if (!configurationFile.delete()) { - throw new IOException(); - } - } - - if (newCreation) { - logger.log(INFO, "jaspic.factory_creating_conf_file", configurationFile.getPath()); - } - - if (!configurationFile.createNewFile()) { - throw new IOException(); - } - } - - /** - * Called from the constructor. This is the only time the file is read, though it is written when new entries are stored - * or deleted. - */ - private void loadEntries() throws IOException { - synchronized (configurationFile) { - entries = new ArrayList(); - if (configurationFile.exists()) { - try (BufferedReader reader = new BufferedReader(new FileReader(configurationFile))) { - String line = reader.readLine(); - while (line != null) { - String trimLine = line.trim(); // can't trim readLine() result - if (trimLine.startsWith(CON_ENTRY)) { - entries.add(readConEntry(reader)); - } else if (trimLine.startsWith(REG_ENTRY)) { - entries.add(readRegEntry(reader)); - } - line = reader.readLine(); - } - } - } else { - if (logger.isLoggable(FINER)) { - logger.log(FINER, "jaspic.factory_file_not_found", - configurationFile.getParent() + File.pathSeparator + configurationFile.getPath()); - } - - for (EntryInfo entry : defaultEntries) { - entries.add(new EntryInfo(entry)); - } - } - } - } - - private EntryInfo readConEntry(BufferedReader reader) throws IOException { - // Entry must contain class name as next line - String className = reader.readLine(); - if (className != null) { - className = className.trim(); - } - - return new EntryInfo(className, readProperties(reader)); - } - - /** - * Properties must be of the form "key:value." While the key String cannot contain a ":" character, the value can. The - * line will be broken into key and value based on the first appearance of the ":" character. - */ - private Map readProperties(BufferedReader reader) throws IOException { - String line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - - if ("}".equals(line)) { - return null; - } - - Map properties = new HashMap(); - while (!"}".equals(line)) { - properties.put(line.substring(0, line.indexOf(SEP)), line.substring(line.indexOf(SEP) + 1, line.length())); - line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - } - - return properties; - } - - private EntryInfo readRegEntry(BufferedReader reader) throws IOException { - String className = null; - Map properties = null; - List ctxs = new ArrayList(); - String line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - while (!"}".equals(line)) { - if (line.startsWith(CON_ENTRY)) { - EntryInfo conEntry = readConEntry(reader); - className = conEntry.getClassName(); - properties = conEntry.getProperties(); - } else if (line.startsWith(REG_CTX)) { - ctxs.add(readRegContext(reader)); - } - line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - - } - return new EntryInfo(className, properties, ctxs); - } - - private RegistrationContext readRegContext(BufferedReader reader) throws IOException { - String layer = null; - String appCtx = null; - String description = null; - String line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - - while (!"}".equals(line)) { - String value = line.substring(line.indexOf(SEP) + 1, line.length()); - if (line.startsWith(LAYER)) { - layer = value; - } else if (line.startsWith(APP_CTX)) { - appCtx = value; - } else if (line.startsWith(DESCRIPTION)) { - description = value; - } - - line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - } - - return new RegistrationContextImpl(layer, appCtx, description, true); - } - - private void logWarningUpdated(Exception exception) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_could_not_persist", exception.toString()); - } - } - - private void logWarningDefault(Exception exception) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_could_not_read", exception.toString()); - } - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java deleted file mode 100644 index f432cd9ab31..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import jakarta.security.auth.message.config.RegistrationListener; - -// Adding package private class because specializing the listener implementation class would -// make the Payara JASPIC (JSR 196) implementation non-replaceable. -// -// This class would hold a RegistrationListener within. -public class AuthConfigRegistrationWrapper { - - private String layer; - private String applicationContextId; - private String jaspicProviderRegistrationId; - private boolean enabled; - private ConfigData data; - - private Lock wLock; - private ReadWriteLock rwLock; - - private AuthConfigRegistrationListener listener; - private int referenceCount = 1; - private RegistrationWrapperRemover removerDelegate; - - public AuthConfigRegistrationWrapper(String layer, String applicationContextId, RegistrationWrapperRemover removerDelegate) { - this.layer = layer; - this.applicationContextId = applicationContextId; - this.removerDelegate = removerDelegate; - this.rwLock = new ReentrantReadWriteLock(true); - this.wLock = rwLock.writeLock(); - - enabled = JaspicServices.factory != null; - listener = new AuthConfigRegistrationListener(layer, applicationContextId); - } - - public AuthConfigRegistrationListener getListener() { - return listener; - } - - public void setListener(AuthConfigRegistrationListener listener) { - this.listener = listener; - } - - public void disable() { - this.wLock.lock(); - - try { - setEnabled(false); - } finally { - this.wLock.unlock(); - data = null; - } - - if (JaspicServices.factory != null) { - JaspicServices.factory.detachListener(this.listener, layer, applicationContextId); - if (getJaspicProviderRegistrationId() != null) { - JaspicServices.factory.removeRegistration(getJaspicProviderRegistrationId()); - } - } - } - - // Detach the listener, but don't remove-registration - public void disableWithRefCount() { - if (referenceCount <= 1) { - disable(); - if (removerDelegate != null) { - removerDelegate.removeListener(this); - } - } else { - try { - this.wLock.lock(); - referenceCount--; - } finally { - this.wLock.unlock(); - } - - } - } - - public void incrementReference() { - try { - this.wLock.lock(); - referenceCount++; - } finally { - this.wLock.unlock(); - } - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getJaspicProviderRegistrationId() { - return this.jaspicProviderRegistrationId; - } - - public void setRegistrationId(String jaspicProviderRegistrationId) { - this.jaspicProviderRegistrationId = jaspicProviderRegistrationId; - } - - public ConfigData getConfigData() { - return data; - } - - public void setConfigData(ConfigData data) { - this.data = data; - } - - public class AuthConfigRegistrationListener implements RegistrationListener { - - private String layer; - private String appCtxt; - - public AuthConfigRegistrationListener(String layer, String appCtxt) { - this.layer = layer; - this.appCtxt = appCtxt; - } - - @Override - public void notify(String layer, String appContext) { - if (this.layer.equals(layer) - && ((this.appCtxt == null && appContext == null) || (appContext != null && appContext.equals(this.appCtxt)))) { - try { - wLock.lock(); - data = null; - } finally { - wLock.unlock(); - } - } - } - - } -} \ No newline at end of file diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java deleted file mode 100644 index 9f3666105ed..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - -import jakarta.security.auth.message.config.AuthConfig; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ServerAuthConfig; - -class ConfigData { - - private AuthConfigProvider provider; - private AuthConfig serverConfig; - private AuthConfig clientConfig; - - ConfigData() { - } - - ConfigData(AuthConfigProvider authConfigProvider, AuthConfig authConfig) { - provider = authConfigProvider; - - if (authConfig == null) { - serverConfig = null; - clientConfig = null; - } else if (authConfig instanceof ServerAuthConfig) { - serverConfig = authConfig; - } else if (authConfig instanceof ClientAuthConfig) { - clientConfig = authConfig; - } else { - throw new IllegalArgumentException(); - } - } - - public AuthConfigProvider getProvider() { - return provider; - } - - public AuthConfig getServerConfig() { - return serverConfig; - } - - public AuthConfig getClientConfig() { - return clientConfig; - } -} \ No newline at end of file diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java deleted file mode 100644 index 5659f9186ff..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.config.AuthConfig; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; - -/** - * This is based Helper class for 196 Configuration. - */ -public abstract class JaspicServices { - - protected static final AuthConfigFactory factory = AuthConfigFactory.getFactory(); - - private ReadWriteLock readWriteLock; - private Lock readLock; - private Lock writeLock; - - protected String layer; - protected String appCtxt; - protected Map map; - protected CallbackHandler callbackHandler; - protected AuthConfigRegistrationWrapper listenerWrapper; - - protected void init(String layer, String appContext, Map map, CallbackHandler callbackHandler, RegistrationWrapperRemover removerDelegate) { - this.layer = layer; - this.appCtxt = appContext; - this.map = map; - this.callbackHandler = callbackHandler; - if (this.callbackHandler == null) { - this.callbackHandler = getCallbackHandler(); - } - - this.readWriteLock = new ReentrantReadWriteLock(true); - this.readLock = readWriteLock.readLock(); - this.writeLock = readWriteLock.writeLock(); - - listenerWrapper = new AuthConfigRegistrationWrapper(this.layer, this.appCtxt, removerDelegate); - } - - public void setRegistrationId(String registrationId) { - listenerWrapper.setRegistrationId(registrationId); - } - - public AuthConfigRegistrationWrapper getRegistrationWrapper() { - return listenerWrapper; - } - - public void setRegistrationWrapper(AuthConfigRegistrationWrapper wrapper) { - this.listenerWrapper = wrapper; - } - - public AuthConfigRegistrationWrapper.AuthConfigRegistrationListener getRegistrationListener() { - return listenerWrapper.getListener(); - } - - public void disable() { - listenerWrapper.disable(); - } - - public Object getProperty(String key) { - return map == null ? null : map.get(key); - } - - public String getAppContextID() { - return appCtxt; - } - - public ClientAuthConfig getClientAuthConfig() throws AuthException { - return (ClientAuthConfig) getAuthConfig(false); - } - - public ServerAuthConfig getServerAuthConfig() throws AuthException { - return (ServerAuthConfig) getAuthConfig(true); - } - - public ClientAuthContext getClientAuthContext(MessageInfo info, Subject clientSubject) throws AuthException { - ClientAuthConfig clientConfig = (ClientAuthConfig) getAuthConfig(false); - if (clientConfig != null) { - return clientConfig.getAuthContext(clientConfig.getAuthContextID(info), clientSubject, map); - } - - return null; - } - - public ServerAuthContext getServerAuthContext(MessageInfo info, Subject serviceSubject) throws AuthException { - ServerAuthConfig serverAuthConfig = (ServerAuthConfig) getAuthConfig(true); - if (serverAuthConfig != null) { - return serverAuthConfig.getAuthContext(serverAuthConfig.getAuthContextID(info), serviceSubject, map); - } - - return null; - } - - protected AuthConfig getAuthConfig(AuthConfigProvider authConfigProvider, boolean isServer) throws AuthException { - AuthConfig authConfig = null; - - if (authConfigProvider != null) { - if (isServer) { - authConfig = authConfigProvider.getServerAuthConfig(layer, appCtxt, callbackHandler); - } else { - authConfig = authConfigProvider.getClientAuthConfig(layer, appCtxt, callbackHandler); - } - } - - return authConfig; - } - - protected AuthConfig getAuthConfig(boolean isServer) throws AuthException { - - ConfigData configData = null; - AuthConfig authConfig = null; - boolean disabled = false; - AuthConfigProvider lastConfigProvider = null; - - try { - readLock.lock(); - disabled = !listenerWrapper.isEnabled(); - if (!disabled) { - configData = listenerWrapper.getConfigData(); - if (configData != null) { - authConfig = isServer ? configData.getServerConfig() : configData.getClientConfig(); - lastConfigProvider = configData.getProvider(); - } - } - - } finally { - readLock.unlock(); - if (disabled || authConfig != null || (configData != null && lastConfigProvider == null)) { - return authConfig; - } - } - - // d == null || (d != null && lastP != null && c == null) - if (configData == null) { - try { - writeLock.lock(); - if (listenerWrapper.getConfigData() == null) { - AuthConfigProvider nextConfigProvider = factory.getConfigProvider(layer, appCtxt, getRegistrationListener()); - - if (nextConfigProvider != null) { - listenerWrapper.setConfigData(new ConfigData(nextConfigProvider, getAuthConfig(nextConfigProvider, isServer))); - } else { - listenerWrapper.setConfigData(new ConfigData()); - } - } - configData = listenerWrapper.getConfigData(); - } finally { - writeLock.unlock(); - } - } - - return isServer ? configData.getServerConfig() : configData.getClientConfig(); - } - - /** - * Check if there is a provider register for a given layer and appCtxt. - */ - protected boolean hasExactMatchAuthProvider() { - boolean exactMatch = false; - - AuthConfigProvider configProvider = factory.getConfigProvider(layer, appCtxt, null); - - if (configProvider != null) { - for (String registrationId : factory.getRegistrationIDs(configProvider)) { - RegistrationContext registrationContext = factory.getRegistrationContext(registrationId); - if (layer.equals(registrationContext.getMessageLayer()) && appCtxt.equals(registrationContext.getAppContext())) { - exactMatch = true; - break; - } - } - } - - return exactMatch; - } - - /** - * Get the callback default handler - */ - protected CallbackHandler getCallbackHandler() { - return null; - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java deleted file mode 100644 index b593a72f2fc..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - - -public interface RegistrationWrapperRemover { - - /** - * remove the registration of the argument listener from the Pipe - * - * @param listener - */ - void removeListener(AuthConfigRegistrationWrapper listener); - -} diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java index 80b2cc68850..253eb82236e 100644 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java +++ b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package test.com.sun.jaspic.config; import java.util.concurrent.TimeUnit; @@ -48,9 +48,6 @@ import java.util.ArrayList; import java.util.List; import com.sun.jaspic.config.factory.EntryInfo; -import com.sun.jaspic.config.factory.AuthConfigFileFactory; -import com.sun.jaspic.config.factory.BaseAuthConfigFactory; -import com.sun.jaspic.config.factory.RegStoreFileParser; import java.security.Security; import org.junit.After; import java.util.HashMap; diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java index 038205a47a1..c8eefa5cb4a 100644 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java +++ b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java @@ -37,10 +37,9 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package test.com.sun.jaspic.config; -import com.sun.jaspic.config.factory.AuthConfigFileFactory; import com.sun.jaspic.config.servlet.JAASServletAuthConfigProvider; import java.io.IOException; import java.util.HashMap; @@ -59,6 +58,7 @@ import jakarta.security.auth.message.config.RegistrationListener; import jakarta.security.auth.message.config.ServerAuthConfig; import jakarta.security.auth.message.config.ServerAuthContext; +import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; /** * diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java index 67d9670a191..006e6423399 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package com.sun.web.security.realmadapter; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.AUTH_TYPE; @@ -93,7 +93,7 @@ import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.security.SecurityContext; -import com.sun.enterprise.security.jaspic.config.PayaraJaspicServletServices; +import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServletServices; import com.sun.enterprise.security.web.integration.WebPrincipal; import com.sun.jaspic.config.servlet.HttpMessageInfo; import com.sun.logging.LogDomains; @@ -130,7 +130,7 @@ public class JaspicRealm { private Container virtualServer; - private PayaraJaspicServletServices jaspicServices; + private PayaraEpicyroServletServices jaspicServices; private AtomicBoolean initialised = new AtomicBoolean(); public JaspicRealm(String realmName, boolean isSystemApp, WebBundleDescriptor webDescriptor, RequestTracingService requestTracing) { @@ -291,11 +291,11 @@ private ServerAuthContext getServerAuthContext(MessageInfo messageInfo) throws A /** * This must be invoked after virtualServer is set. */ - private PayaraJaspicServletServices getConfigHelper(ServletContext servletContext) { + private PayaraEpicyroServletServices getConfigHelper(ServletContext servletContext) { Map map = new HashMap<>(); map.put(WEB_BUNDLE, webDescriptor); - return new PayaraJaspicServletServices( + return new PayaraEpicyroServletServices( getAppContextID(servletContext), map, null, // null handler realmName, isSystemApp, jaspicSystemConfigProviderID); } diff --git a/appserver/security/webservices.security/pom.xml b/appserver/security/webservices.security/pom.xml index 490f94c6001..a14995ec401 100644 --- a/appserver/security/webservices.security/pom.xml +++ b/appserver/security/webservices.security/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -144,5 +144,15 @@ logging-annotation-processor true + + org.glassfish.epicyro + epicyro + + + fish.payara.server.internal.security + appclient.security + ${project.version} + true + diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java index 1bd4684ad53..08b59322298 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java @@ -37,17 +37,19 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jauth.jaspic.provider.config; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getMessageSecurityBinding; import static com.sun.enterprise.security.webservices.PipeConstants.BINDING; import static com.sun.enterprise.security.webservices.PipeConstants.ENDPOINT; import static com.sun.enterprise.security.webservices.PipeConstants.SEI_MODEL; import static com.sun.enterprise.security.webservices.PipeConstants.SERVICE_ENDPOINT; -import static com.sun.enterprise.security.webservices.PipeConstants.SOAP_LAYER; import static com.sun.xml.ws.api.SOAPVersion.SOAP_11; +import com.sun.enterprise.security.appclient.ConfigXMLParser; +import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; +import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; +import jakarta.security.auth.message.MessagePolicy; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; @@ -55,6 +57,8 @@ import java.security.PrivilegedExceptionAction; import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import jakarta.security.auth.message.AuthException; @@ -72,6 +76,8 @@ import org.glassfish.api.invocation.ComponentInvocation; import org.glassfish.api.invocation.InvocationManager; import org.glassfish.deployment.common.ModuleDescriptor; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; import org.glassfish.internal.api.Globals; import com.sun.enterprise.deployment.Application; @@ -88,10 +94,9 @@ import com.sun.enterprise.security.common.ClientSecurityContext; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; import com.sun.enterprise.security.ee.authorize.EJBPolicyContextDelegate; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; import com.sun.enterprise.security.jaspic.config.HandlerContext; -import com.sun.enterprise.security.jaspic.config.PayaraJaspicServices; +import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServices; import com.sun.enterprise.security.webservices.PipeConstants; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.io.FileUtils; @@ -106,7 +111,7 @@ import com.sun.xml.ws.api.model.wsdl.WSDLPort; import com.sun.xml.ws.api.server.WSEndpoint; -public class PipeHelper extends PayaraJaspicServices { +public class PipeHelper extends PayaraEpicyroServices { protected static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(PipeConstants.class); @@ -118,7 +123,7 @@ public class PipeHelper extends PayaraJaspicServices { private EJBPolicyContextDelegate ejbDelegate; public PipeHelper(String layer, Map properties, CallbackHandler callbackHandler) { - init(layer, getAppCtxt(properties), properties, callbackHandler, Globals.get(WebServicesDelegate.class)); + init(layer, getAppCtxt(properties), properties, callbackHandler, (RegistrationWrapperRemover) Globals.get(WebServicesDelegate.class)); isEjbEndpoint = processSunDeploymentDescriptor(); seiModel = (SEIModel) properties.get(SEI_MODEL); @@ -402,24 +407,44 @@ public String getRealmName() { } private boolean processSunDeploymentDescriptor() { - if (factory == null) { + if (authConfigFactory == null) { return false; } - MessageSecurityBindingDescriptor binding = getMessageSecurityBinding(SOAP_LAYER, map); + MessageSecurityBindingDescriptor binding = AuthMessagePolicy.getMessageSecurityBinding(com.sun.xml.wss.provider.wsit.PipeConstants.SOAP_LAYER, map); + + Function authContextIdGenerator = + e -> Globals.get(WebServicesDelegate.class).getAuthContextID(e); + + BiFunction, MessagePolicy[]> soapPolicyGenerator = + (authContextId, properties) -> AuthMessagePolicy.getSOAPPolicies( + AuthMessagePolicy.getMessageSecurityBinding("SOAP", properties), + authContextId, true); + + String authModuleId = AuthMessagePolicy.getProviderID(binding); + + map.put("authContextIdGenerator", authContextIdGenerator); + map.put("soapPolicyGenerator", soapPolicyGenerator); + + if (authModuleId != null) { + map.put("authModuleId", authModuleId); + } if (binding != null) { if (!hasExactMatchAuthProvider()) { - String jaspicProviderRegisID = factory.registerConfigProvider( - new GFServerConfigProvider(null, null), - layer, appCtxt, "GF AuthConfigProvider bound by Sun Specific Descriptor"); - - setRegistrationId(jaspicProviderRegisID); + String jmacProviderRegisID = authConfigFactory.registerConfigProvider( + new GFServerConfigProvider( + map, + isACC()? new ConfigXMLParser() : new ConfigDomainParser(), + authConfigFactory), + messageLayer, appContextId, + "GF AuthConfigProvider bound by Sun Specific Descriptor"); + + setRegistrationId(jmacProviderRegisID); } } WebServiceEndpoint webServiceEndpoint = (WebServiceEndpoint) map.get(SERVICE_ENDPOINT); - return webServiceEndpoint == null ? false : webServiceEndpoint.implementedByEjbComponent(); } @@ -538,4 +563,8 @@ private String ejbName() { WebServiceEndpoint wSE = (WebServiceEndpoint) getProperty(PipeConstants.SERVICE_ENDPOINT); return (wSE == null ? "unknown" : wSE.getEjbComponentImpl().getName()); } + + private static boolean isACC() { + return SecurityServicesUtil.getInstance() == null || SecurityServicesUtil.getInstance().isACC(); + } } diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java index 162a55e99f3..62c7771236a 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static java.util.Collections.synchronizedMap; @@ -47,7 +47,7 @@ import java.util.WeakHashMap; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.jaspic.services.AuthConfigRegistrationWrapper; +import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; public class ClientPipeCloser { diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java index a0421be7125..f06686cfe72 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2022] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static com.sun.enterprise.security.webservices.PipeConstants.ASSEMBLER_CONTEXT; @@ -53,7 +53,7 @@ import java.util.HashMap; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.jaspic.services.AuthConfigRegistrationWrapper; +import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; import com.sun.xml.ws.api.pipe.ClientPipeAssemblerContext; import com.sun.xml.ws.api.pipe.Pipe; import com.sun.xml.ws.assembler.metro.dev.ClientPipelineHook; diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java index 554546d1ce7..e0145fad991 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import java.util.Iterator; @@ -63,11 +63,11 @@ import com.sun.enterprise.deployment.ServiceRefPortInfo; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; import com.sun.enterprise.security.jauth.AuthParam; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.SOAPAuthParam; -import com.sun.jaspic.services.AuthConfigRegistrationWrapper; +import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; import com.sun.xml.ws.api.message.Message; import com.sun.xml.ws.api.message.Packet; import com.sun.xml.ws.api.model.wsdl.WSDLBoundOperation; diff --git a/core/core-parent/pom.xml b/core/core-parent/pom.xml index b8f77ac8617..dcaa351d5e0 100644 --- a/core/core-parent/pom.xml +++ b/core/core-parent/pom.xml @@ -617,6 +617,8 @@ io.opentelemetry.extension io.opentelemetry.instrumentation fish.payara.shaded + com.sun.enterprise.security + com.sun.jaspic.services diff --git a/core/pom.xml b/core/pom.xml index 0b6fe24f0cb..6e852701dac 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -123,6 +123,7 @@ 1.0 4.12.0 2.0.21 + 3.1.0 3.2.3.payara-p1 @@ -913,6 +914,11 @@ jakarta.authentication-api ${jakarta.authentication-api.version} + + org.glassfish.epicyro + epicyro + ${epyciro.version} + jakarta.persistence jakarta.persistence-api diff --git a/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java b/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java index 84705677cb5..de361201707 100644 --- a/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java +++ b/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019] Payara Foundation and/or affiliates +// Portions Copyright [2019-2024] Payara Foundation and/or affiliates package org.glassfish.deployment.common; @@ -88,11 +88,11 @@ public void addExtraAttribute(String name, Object value) { * @param name the attribute name * @return the attribute value of null of non existent */ - public Object getExtraAttribute(String name) { + public T getExtraAttribute(String name) { if (dynamicAttributes == null) { return null; } - return dynamicAttributes.get(name); + return (T) dynamicAttributes.get(name); } /** diff --git a/nucleus/security/core/pom.xml b/nucleus/security/core/pom.xml index c103175bcf2..c80ae0d20fd 100644 --- a/nucleus/security/core/pom.xml +++ b/nucleus/security/core/pom.xml @@ -39,7 +39,7 @@ only if the new code is made subject to such option by the copyright holder. - Portions Copyright [2019-2022] [Payara Foundation and/or its affiliates] + Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] --> logging-annotation-processor true + + org.glassfish.epicyro + epicyro + org.javassist javassist diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java index 677f8758199..6d6b8b22368 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; import static com.sun.enterprise.security.SecurityLoggerInfo.noPwdCredentialProvidedError; @@ -58,10 +58,10 @@ import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; - +import org.glassfish.epicyro.config.helper.CallerPrincipal; import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; + import com.sun.enterprise.security.auth.login.LoginCallbackHandler; import com.sun.enterprise.security.auth.login.common.PasswordCredential; @@ -98,7 +98,7 @@ public abstract class BasePasswordLoginModule implements LoginModule { // the authentication status protected boolean _succeeded; protected boolean _commitSucceeded; - protected PrincipalImpl _userPrincipal; + protected CallerPrincipal _userPrincipal; protected String[] _groupsList; /** @@ -169,7 +169,7 @@ public boolean commit() throws LoginException { if (factory != null) { _userPrincipal = factory.getPrincipalInstance(getUsername(), realmName); } else { - _userPrincipal = new PrincipalImpl(getUsername()); + _userPrincipal = new CallerPrincipal(getUsername()); } Set principals = _subject.getPrincipals(); @@ -444,7 +444,7 @@ public boolean isCommitSucceeded() { /** * @return the UserPrincipal - for backward compatibility */ - public PrincipalImpl getUserPrincipal() { + public CallerPrincipal getUserPrincipal() { return _userPrincipal; } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java index 01ecb60710c..54b50e11022 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java @@ -37,11 +37,11 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2017-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.epicyro.config.helper.CallerPrincipal; import org.jvnet.hk2.annotations.Contract; /** @@ -50,7 +50,7 @@ @Contract public interface PrincipalGroupFactory { - PrincipalImpl getPrincipalInstance(String name, String realm); + CallerPrincipal getPrincipalInstance(String name, String realm); Group getGroupInstance(String name, String realm); } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java index 56a48d9063a..7c790c0aff9 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2021] Payara Services Ltd. +// Portions Copyright [2021-2024] Payara Services Ltd. package com.sun.enterprise.security.audit; @@ -193,7 +193,6 @@ public void loadAuditModules() { * Add the given audit module to the list of loaded audit module. * Adding the same name twice will override previous one. * @param name of auditModule - * @param am an instance of a class extending BaseAuditModule that has been * successfully loaded into the system. * @exception */ @@ -284,7 +283,6 @@ public Logger getLogger() { /** * logs the authentication call for all the loaded modules. - * @see com.sun.appserv.security.BaseAuditModule.authentication */ @Override public void authentication(final String user, final String realm, final boolean success){ diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java index 4ea09f6432c..b1706ca12f1 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.common; import java.security.Principal; @@ -74,8 +74,8 @@ public final class ClientSecurityContext extends AbstractSecurityContext { /** * This creates a new ClientSecurityContext object. * - * @param The name of the user. - * @param The Credentials of the user. + * @param username name of the user. + * @param subject Credentials of the user. */ public ClientSecurityContext(String username, Subject subject) { this.callerPrincipal = new PrincipalImpl(username); @@ -101,7 +101,6 @@ public static ClientSecurityContext getCurrent() { /** * This method sets the SecurityContext to be stored here. * - * @param The Security Context that should be stored. */ public static void setCurrent(ClientSecurityContext clientSecurityContext) { if (isPerThreadAuth) { From 5627fea71225eeecb5ead9da5bdc7e1998e79cf0 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Thu, 14 Nov 2024 22:27:02 -0600 Subject: [PATCH 04/34] FISH-8925: introducing epicyro for jakarta authentication in payara 7 --- .../glassfish/ejb/startup/EjbDeployer.java | 2 +- appserver/packager/appserver-core/pom.xml | 4 - .../registration/glassfish/ModuleMap.java | 95 +- appserver/security/appclient.security/pom.xml | 6 +- appserver/security/core-ee/pom.xml | 4 - .../security/ee/JavaEESecurityLifecycle.java | 2 +- .../jakarta/WebServicesDelegate.java | 16 +- .../jacc/JaccWebAuthorizationManager.java | 2 +- .../security/jacc/package-info.java | 2 +- .../security/jaspic/package-info.java | 2 +- .../enterprise/security/jauth/AuthConfig.java | 291 ----- .../security/jauth/AuthContext.java | 265 ----- .../security/jauth/AuthException.java | 71 -- .../enterprise/security/jauth/AuthParam.java | 52 - .../enterprise/security/jauth/AuthPolicy.java | 268 ----- .../security/jauth/ClientAuthContext.java | 147 --- .../security/jauth/ClientAuthModule.java | 144 --- .../jauth/DependentCallbackHandler.java | 56 - .../security/jauth/FailureException.java | 73 -- .../security/jauth/HttpServletAuthParam.java | 158 --- .../security/jauth/PendingException.java | 74 -- .../security/jauth/ServerAuthContext.java | 170 --- .../security/jauth/ServerAuthModule.java | 146 --- .../jauth/callback/CertStoreCallback.java | 71 -- .../jauth/callback/KerberosKeyCallback.java | 95 -- .../callback/PasswordValidationCallback.java | 64 -- .../jauth/callback/PrivateKeyCallback.java | 168 --- .../jauth/callback/SecretKeyCallback.java | 110 -- .../jauth/callback/SignatureKeyCallback.java | 115 -- .../jauth/callback/TrustStoreCallback.java | 66 -- .../security/permissionsxml/server.policy | 3 +- .../jaspic-provider-framework/auth.conf | 0 .../jaspic-provider-framework/osgi.bundle | 48 - .../jaspic-provider-framework/pom.xml | 91 -- .../delegate/MessagePolicyDelegate.java | 62 - .../factory/DefaultAuthConfigProvider.java | 116 -- .../factory/DefaultServerAuthConfig.java | 95 -- .../factory/DefaultServerAuthContext.java | 65 -- .../sun/jaspic/config/factory/EntryInfo.java | 198 ---- .../factory/RegistrationContextImpl.java | 114 -- .../config/helper/BaseAuthConfigImpl.java | 245 ---- .../config/helper/BaseAuthConfigProvider.java | 245 ---- .../config/helper/BaseAuthContextImpl.java | 169 --- .../config/helper/ClientAuthConfigImpl.java | 220 ---- .../jaspic/config/helper/EpochCarrier.java | 95 -- .../config/helper/JASPICLogManager.java | 58 - .../config/helper/ServerAuthConfigImpl.java | 221 ---- .../config/jaas/ExtendedConfigFile.java | 151 --- .../config/jaas/JAASAuthConfigProvider.java | 156 --- .../config/jaas/JAASAuthContextHelper.java | 344 ------ .../config/servlet/HttpMessageInfo.java | 85 -- .../JAASServletAuthConfigProvider.java | 142 --- .../jaspic/security/LogStrings.properties | 49 - .../com/sun/jaspic/config/FactoryTest.java | 1013 ----------------- .../sun/jaspic/config/RuntimeSurrogate.java | 339 ------ .../jaspic/config/SampleClientAuthModule.java | 78 -- .../jaspic/config/SampleServerAuthModule.java | 78 -- .../security/realmadapter/JaspicRealm.java | 2 +- .../security/webservices.security/pom.xml | 2 +- .../jauth/jaspic/provider/BaseAuthConfig.java | 608 ---------- .../jaspic/provider/ClientAuthConfig.java | 121 -- .../jauth/jaspic/provider/SOAPAuthParam.java | 5 +- .../jaspic/provider/ServerAuthConfig.java | 122 -- ...er.java => SoapAuthenticationService.java} | 4 +- .../webservices/ClientSecurityPipe.java | 12 +- ...or.java => ClientSecurityPipeCreator.java} | 44 +- .../webservices/ClientSecurityTube.java | 10 +- .../webservices/CommonServerSecurityPipe.java | 10 +- .../webservices/CommonServerSecurityTube.java | 10 +- .../webservices/SecurityServiceImpl.java | 64 +- ...or.java => ServerSecurityPipeCreator.java} | 26 +- .../webservices/WebServicesDelegateImpl.java | 33 +- .../webservices/SecurityService.java | 10 +- core/core-bom/pom.xml | 10 +- core/pom.xml | 2 - .../src/main/resources/config/server.policy | 1 + .../internal/notification/EventLevel.java | 85 ++ .../enterprise/security}/PolicyLoader.java | 3 +- .../src/main/resources/config/server.policy | 1 + nucleus/security/services/pom.xml | 6 +- 80 files changed, 247 insertions(+), 8163 deletions(-) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthConfig.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthContext.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthException.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthParam.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthPolicy.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthContext.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthModule.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/DependentCallbackHandler.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/FailureException.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/HttpServletAuthParam.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/PendingException.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthContext.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthModule.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/CertStoreCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/KerberosKeyCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PasswordValidationCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PrivateKeyCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SecretKeyCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SignatureKeyCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/TrustStoreCallback.java delete mode 100644 appserver/security/jaspic-provider-framework/auth.conf delete mode 100644 appserver/security/jaspic-provider-framework/osgi.bundle delete mode 100644 appserver/security/jaspic-provider-framework/pom.xml delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/delegate/MessagePolicyDelegate.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultAuthConfigProvider.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthConfig.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthContext.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/EntryInfo.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegistrationContextImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigProvider.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthContextImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ClientAuthConfigImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/EpochCarrier.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/JASPICLogManager.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ServerAuthConfigImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/ExtendedConfigFile.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthContextHelper.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/HttpMessageInfo.java delete mode 100755 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/JAASServletAuthConfigProvider.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/resources/com/sun/logging/enterprise/system/jaspic/security/LogStrings.properties delete mode 100644 appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java delete mode 100644 appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java delete mode 100644 appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleClientAuthModule.java delete mode 100644 appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleServerAuthModule.java delete mode 100644 appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/BaseAuthConfig.java delete mode 100644 appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ClientAuthConfig.java delete mode 100644 appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ServerAuthConfig.java rename appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/{PipeHelper.java => SoapAuthenticationService.java} (99%) rename appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/{ClientPipeCreator.java => ClientSecurityPipeCreator.java} (79%) rename appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/{GFServerPipeCreator.java => ServerSecurityPipeCreator.java} (88%) rename {appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize => nucleus/security/core/src/main/java/com/sun/enterprise/security}/PolicyLoader.java (99%) diff --git a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java index 207f4258b46..46326ada624 100644 --- a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java +++ b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java @@ -89,7 +89,7 @@ import com.sun.enterprise.deployment.Application; import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.module.bootstrap.StartupContext; -import com.sun.enterprise.security.ee.authorize.PolicyLoader; +import com.sun.enterprise.security.PolicyLoader; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.util.IASSecurityException; import com.sun.enterprise.util.LocalStringManagerImpl; diff --git a/appserver/packager/appserver-core/pom.xml b/appserver/packager/appserver-core/pom.xml index ad610afd20d..d670ffc22a9 100644 --- a/appserver/packager/appserver-core/pom.xml +++ b/appserver/packager/appserver-core/pom.xml @@ -164,10 +164,6 @@ jacc.provider.inmemory ${project.version} - - fish.payara.server.core.security - jaspic.provider.framework - fish.payara.server.core.packager libpam4j-repackaged diff --git a/appserver/registration/glassfish-registration/src/main/java/com/sun/enterprise/registration/glassfish/ModuleMap.java b/appserver/registration/glassfish-registration/src/main/java/com/sun/enterprise/registration/glassfish/ModuleMap.java index 898269ed028..992e58e488b 100644 --- a/appserver/registration/glassfish-registration/src/main/java/com/sun/enterprise/registration/glassfish/ModuleMap.java +++ b/appserver/registration/glassfish-registration/src/main/java/com/sun/enterprise/registration/glassfish/ModuleMap.java @@ -282,54 +282,53 @@ public class ModuleMap { put("fish.payara.server.internal.security.appclient.security", 223); put("fish.payara.server.internal.security.ejb.security", 224); put("fish.payara.server.internal.security.inmemory.jacc.provider", 225); - put("fish.payara.server.core.security.jaspic.provider.framework", 226); - put("fish.payara.server.internal.security.jakarta.security.auth.message", 227); - put("fish.payara.server.internal.security.jakarta.security.jacc", 228); - put("fish.payara.server.core.security.ssl-impl", 229); - put("fish.payara.server.core.security.websecurity", 230); - put("fish.payara.server.internal.security.webservices.security", 231); - put("fish.payara.server.internal.transaction.internal-api", 232); - put("fish.payara.server.internal.transaction.jakarta.transaction", 233); - put("fish.payara.server.internal.transaction.jta", 234); - put("fish.payara.server.internal.transaction.jts", 235); - put("fish.payara.server.internal.web.cli", 236); - put("fish.payara.server.internal.web.core", 237); - put("fish.payara.server.core.web.gf-web-connector", 238); - put("fish.payara.server.core.web.glue", 239); - put("fish.payara.server.internal.web.gui-plugin-common", 240); - put("fish.payara.server.internal.web.ha", 241); - put("fish.payara.server.internal.web.jsf-connector", 242); - put("fish.payara.server.internal.web.jspcaching-connector", 243); - put("fish.payara.server.internal.web.jstl-connector", 244); - put("fish.payara.server.internal.web.naming", 245); - put("fish.payara.server.core.web.war-util", 246); - put("fish.payara.server.core.web.web-embed.api", 247); - put("fish.payara.server.internal.web.web-embed.impl", 248); - put("fish.payara.server.internal.web.weld-integration", 249); - put("fish.payara.server.internal.web.weld-integration-fragment", 250); - put("fish.payara.server.internal.webservices.connector", 251); - put("fish.payara.server.internal.webservices.jsr109-impl", 252); - put("fish.payara.server.internal.webservices.metro-glue", 253); - put("fish.payara.server.internal.webservices.soap-tcp", 254); - put("org.glassfish.metro.webservices-api-osgi", 255); - put("org.glassfish.metro.webservices-extra-jdk-packages", 256); - put("org.glassfish.metro.webservices-osgi", 257); - put("org.glassfish.web.el-impl", 258); - put("org.glassfish.web.jsp-impl", 259); - put("org.glassfish.web.jstl-impl", 260); - put("org.jboss.weld.osgi-bundle", 261); - put("org.jvnet.mimepull", 262); - put("org.shoal.cache", 263); - put("org.shoal.gms-api", 264); - put("org.shoal.gms-impl", 265); - put("stax2-api", 266); - put("woodstox-core-asl", 267); - put("com.fasterxml.jackson.dataformat.xml", 268); - put("org.objectweb.asm", 269); - put("org.objectweb.asm.commons", 270); - put("org.objectweb.asm.tree", 271); - put("org.objectweb.asm.tree.analysis", 272); - put("org.objectweb.asm.util", 273); + put("fish.payara.server.internal.security.jakarta.security.auth.message", 226); + put("fish.payara.server.internal.security.jakarta.security.jacc", 227); + put("fish.payara.server.core.security.ssl-impl", 228); + put("fish.payara.server.core.security.websecurity", 229); + put("fish.payara.server.internal.security.webservices.security", 230); + put("fish.payara.server.internal.transaction.internal-api", 231); + put("fish.payara.server.internal.transaction.jakarta.transaction", 232); + put("fish.payara.server.internal.transaction.jta", 233); + put("fish.payara.server.internal.transaction.jts", 234); + put("fish.payara.server.internal.web.cli", 235); + put("fish.payara.server.internal.web.core", 236); + put("fish.payara.server.core.web.gf-web-connector", 237); + put("fish.payara.server.core.web.glue", 238); + put("fish.payara.server.internal.web.gui-plugin-common", 239); + put("fish.payara.server.internal.web.ha", 240); + put("fish.payara.server.internal.web.jsf-connector", 241); + put("fish.payara.server.internal.web.jspcaching-connector", 242); + put("fish.payara.server.internal.web.jstl-connector", 243); + put("fish.payara.server.internal.web.naming", 244); + put("fish.payara.server.core.web.war-util", 245); + put("fish.payara.server.core.web.web-embed.api", 246); + put("fish.payara.server.internal.web.web-embed.impl", 247); + put("fish.payara.server.internal.web.weld-integration", 248); + put("fish.payara.server.internal.web.weld-integration-fragment", 249); + put("fish.payara.server.internal.webservices.connector", 250); + put("fish.payara.server.internal.webservices.jsr109-impl", 251); + put("fish.payara.server.internal.webservices.metro-glue", 252); + put("fish.payara.server.internal.webservices.soap-tcp", 253); + put("org.glassfish.metro.webservices-api-osgi", 254); + put("org.glassfish.metro.webservices-extra-jdk-packages", 255); + put("org.glassfish.metro.webservices-osgi", 256); + put("org.glassfish.web.el-impl", 257); + put("org.glassfish.web.jsp-impl", 258); + put("org.glassfish.web.jstl-impl", 259); + put("org.jboss.weld.osgi-bundle", 260); + put("org.jvnet.mimepull", 261); + put("org.shoal.cache", 262); + put("org.shoal.gms-api", 263); + put("org.shoal.gms-impl", 264); + put("stax2-api", 265); + put("woodstox-core-asl", 266); + put("com.fasterxml.jackson.dataformat.xml", 267); + put("org.objectweb.asm", 268); + put("org.objectweb.asm.commons", 269); + put("org.objectweb.asm.tree", 270); + put("org.objectweb.asm.tree.analysis", 271); + put("org.objectweb.asm.util", 272); }}); public ModuleMap() { diff --git a/appserver/security/appclient.security/pom.xml b/appserver/security/appclient.security/pom.xml index c76a04ce5b7..62d291ffaff 100644 --- a/appserver/security/appclient.security/pom.xml +++ b/appserver/security/appclient.security/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -117,5 +117,9 @@ fish.payara.server.core.orb orb-connector + + org.glassfish.epicyro + epicyro + diff --git a/appserver/security/core-ee/pom.xml b/appserver/security/core-ee/pom.xml index 3172d64f9c3..a8ce5bb84fe 100644 --- a/appserver/security/core-ee/pom.xml +++ b/appserver/security/core-ee/pom.xml @@ -232,10 +232,6 @@ jakarta.security.enterprise jakarta.security.enterprise-api provided - - - fish.payara.server.core.security - jaspic.provider.framework fish.payara.server.core.common diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java index fb41dad5358..9e4887308d5 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java @@ -44,7 +44,7 @@ import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; -import com.sun.enterprise.security.ee.authorize.PolicyLoader; +import com.sun.enterprise.security.PolicyLoader; import com.sun.logging.LogDomains; import jakarta.inject.Inject; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java index 7951de32a2f..e34465247d3 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java @@ -49,7 +49,6 @@ import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.security.jauth.AuthParam; import org.glassfish.epicyro.services.RegistrationWrapperRemover; /** @@ -88,18 +87,5 @@ public interface WebServicesDelegate extends RegistrationWrapperRemover { * @return the AuthContextID computed from the argument MessageInfo */ String getAuthContextID(MessageInfo messageInfo); - - /** - * @param messageInfo TheMessageInfo - * @return a new instance of SOAPAuthParam - */ - AuthParam newSOAPAuthParam(MessageInfo messageInfo); - - /** - * Return the SOAP Message from the invocation, to be used by JACC PolicyContextHandler - * - * @param componentInvocation the invocation - * @return the SOAP Message - */ - Object getSOAPMessage(ComponentInvocation componentInvocation); + } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java index 84bec4504fd..cfb5d113599 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java @@ -49,7 +49,7 @@ import com.sun.enterprise.deployment.runtime.common.wls.SecurityRoleAssignment; import com.sun.enterprise.deployment.runtime.web.SunWebApp; import com.sun.enterprise.deployment.web.LoginConfiguration; -import com.sun.enterprise.security.ee.authorize.PolicyLoader; +import com.sun.enterprise.security.PolicyLoader; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityRoleMapperFactoryGen; import com.sun.enterprise.security.SecurityServicesUtil; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java index 96c34b3ef69..4fa54399e1c 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java @@ -59,7 +59,7 @@ * *

* The pluggable JACC components are loaded by a class in nucleus: - * {@link com.sun.enterprise.security.ee.authorize.PolicyLoader} + * {@link com.sun.enterprise.security.PolicyLoader} * */ package com.sun.enterprise.security.jacc; \ No newline at end of file diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java index 0938890cbf7..f980089d138 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java @@ -52,7 +52,7 @@ * *

* Code in this package builds upon the general (server independent) JASPIC Provider - * Framework Reference Implementation (org.glassfish.main.security:jaspic.provider.framework). + * Framework Reference Implementation. * It adds to this framework by implementing the Payara specific bits. * *

diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthConfig.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthConfig.java deleted file mode 100644 index c4ccbafd8c5..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthConfig.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import javax.security.auth.callback.CallbackHandler; - -/** - * This class manages the configuration AuthModules. - * - *

- * An AuthModule represents a pluggable component for performing security-related request and response processing, and - * can be configured for a particular interception point and provider ID. The provider ID is an administrator-defined - * value. The standard interception points include: - * - *

    - *
  • HTTP - *
  • EJB - *
  • SOAP - *
- * - *

- * Information may be associated with a configured module, including its fully qualified class name (so it can be - * instantiated), and module options (which help tune the behavior of the module). It is the responsibility of the - * AuthConfig implementation to load any required module information. - * - *

- * Callers do not operate on AuthModules directly. Instead they rely on a ClientAuthContext or ServerAuthContext to - * manage the invocation of modules. A caller obtains an instance of ClientAuthContext or ServerAuthContext by calling - * the getClientAuthContext or getServerAuthContext method, respectively. Each method takes as - * arguments an intercept, an id, a requestPolicy, and a responsePolicy. - * - *

- * An AuthConfig implementation determines the modules to be invoked via the intercept and id values. It - * then encapsulates those modules in a ClientAuthContext or ServerAuthContext instance, and returns that instance. The - * returned object is responsible for instantiating, initializing, and invoking the configured modules (when called - * upon). - * - *

- * The module initializion step involves calling each configured module's AuthModule.initialize method. The - * received requestPolicy and responsePolicy are passed to this method. It is then the modules' - * responsibility, when invoked, to enforce these policies. - * - *

- * A system-wide AuthConfig instance can be retrieved by invoking getConfig. A default implementation is - * provided, and can be replaced by setting the value of the "authconfig.provider" security property (in the Java - * security properties file) to the fully qualified name of the desired implementation class. The Java security - * properties file is located in the file named <JAVA_HOME>/lib/security/java.security, where <JAVA_HOME> - * refers to the directory where the JDK was installed. - * - * @version %I%, %G% - * @see ClientAuthContext - * @see ServerAuthContext - */ -public abstract class AuthConfig { - - /** - * HTTP interception point. - */ - public static final String HTTP = "HTTP"; - - /** - * EJB interception point. - */ - public static final String EJB = "EJB"; - - /** - * SOAP interception point. - */ - public static final String SOAP = "SOAP"; - - // security property to replace default AuthConfig implementation - private static final String AUTHCONFIG_PROPERTY = "authconfig.provider"; - - // class name of default AuthConfig implementation - private static final String DEFAULT_CLASS = "com.sun.enterprise.security.jauth.ConfigFile"; - - private static AuthConfig config; - - // package private for ConfigFile - static ClassLoader getClassLoader() { - - final ClassLoader rvalue; - - rvalue = (ClassLoader) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() { - @Override - public Object run() { - return Thread.currentThread().getContextClassLoader(); - } - }); - - return rvalue; - }; - - /** - * Sole constructor. (For invocation by subclass constructors, typically implicit.) - */ - protected AuthConfig() { - } - - /** - * Get a system-wide module configuration. - * - *

- * If an AuthConfig object was set via the setAuthConfig method, then that object is returned. Otherwise, - * an instance of the AuthConfig object configured in the authconfig.provider security property is returned. If - * that property is not set, a default implementation is returned. - * - * @return a system-wide AuthConfig instance. - * - * @exception SecurityException if the caller does not have permission to retrieve the configuration. - */ - public static synchronized AuthConfig getAuthConfig() { - /** - * XXX security check? SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new - * AuthPermission("getAuthConfig")); - */ - - if (config == null) { - String config_class = null; - config_class = (String) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() { - @Override - public Object run() { - return java.security.Security.getProperty(AUTHCONFIG_PROPERTY); - } - }); - if (config_class == null) { - config_class = DEFAULT_CLASS; - } - - try { - final String finalClass = config_class; - config = (AuthConfig) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws ClassNotFoundException, - InstantiationException, - IllegalAccessException { - return Class.forName(finalClass, - true, - getClassLoader()).newInstance(); - } - }); - } catch (java.security.PrivilegedActionException e) { - throw (SecurityException) new SecurityException().initCause(e.getException()); - } - } - return config; - } - - /** - * Set a system-wide module configuration. - * - * @param config the new configuration. - * - * @exception SecurityException if the caller does not have permission to set the configuration. - */ - public static void setAuthConfig(AuthConfig config) { - /** - * XXX security check? SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new - * AuthPermission("setAuthConfig")); } - */ - - AuthConfig.config = config; - } - - /** - * Get a ClientAuthContext. - * - *

- * The modules configured for the returned ClientAuthContext are determined by the intercept and provider - * id input parameters. The returned ClientAuthContext may be null, which signifies that there are no modules - * configured. - * - *

- * The returned ClientAuthContext encapsulates both the configured modules, as well as the module invocation semantics - * (for example the order modules are to be invoked, and whether certain modules must succeed). Individual - * ClientAuthContext implementations may enforce custom module invocation semantics. - * - * @param intercept the interception point used to determine the modules configured for the returned ClientAuthContext. - * Standard values include: - *

    - *
  • HTTP - *
  • EJB - *
  • SOAP - *
- * - * @param id the provider id used to determine the modules configured for the returned ClientAuthContext, or null. If - * null, a default ID may be used. - * - * @param requestPolicy the application request policy to be enfored by the modules, or null. If null, a default request - * policy may be used. - * - * @param responsePolicy the application response policy to be enfored by the modules, or null. If null, a default - * response policy may be used. - * - * @param handler the CallbackHandler to associate with the returned ClientAuthContext for use by configured modules to - * request information from the caller, or null. If null, a default handler may be used. - * - * @return a ClientAuthContext, or null. - */ - public abstract ClientAuthContext getClientAuthContext(String intercept, - String id, - AuthPolicy requestPolicy, - AuthPolicy responsePolicy, - CallbackHandler handler) - throws AuthException; - - /** - * Get a ServerAuthContext. - * - *

- * The modules configured for the returned ServerAuthContext are determined by the intercept and provider - * id, input parameters. The returned ServerAuthContext may be null, which signifies that there are no modules - * configured. - * - *

- * The returned ServerAuthContext encapsulates both the configured modules, as well as the module invocation semantics - * (for example the order modules are to be invoked, and whether certain modules must succeed). Individual - * ServerAuthContext implementations may enforce custom module invocation semantics. - * - * @param intercept the interception point used to determine the modules configured for the returned ServerAuthContext. - * Standard values include: - *

    - *
  • HTTP - *
  • EJB - *
  • SOAP - *
- * - * @param id the provider id used to determine the modules configured for the returned ClientAuthContext, or null. If - * null, a default id may be used. - * - * @param requestPolicy the application request policy to be enfored by the modules, or null. If null, a default request - * policy may be used. - * - * @param responsePolicy the application response policy to be enfored by the modules, or null. If null, a default - * response policy may be used. - * - * @param handler the CallbackHandler to associate with the returned ClientAuthContext, which can be used by configured - * modules to request information from the caller, or null. If null, a default handler may be used. - * - * @return a ServerAuthContext, or null. - */ - public abstract ServerAuthContext getServerAuthContext(String intercept, - String id, - AuthPolicy requestPolicy, - AuthPolicy responsePolicy, - CallbackHandler handler) - throws AuthException; - - /** - * Refresh the internal representation of the active configuration by re-reading the provider configs. - */ - public abstract void refresh() throws AuthException; -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthContext.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthContext.java deleted file mode 100644 index a1ca1193e32..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthContext.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import java.util.*; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.login.AppConfigurationEntry; - -/** - * Shared logic from Client and ServerAuthContext reside here. - */ -final class AuthContext { - - static final String INIT = "initialize"; - static final String DISPOSE_SUBJECT = "disposeSubject"; - - static final String SECURE_REQUEST = "secureRequest"; - static final String VALIDATE_RESPONSE = "validateResponse"; - - static final String VALIDATE_REQUEST = "validateRequest"; - static final String SECURE_RESPONSE = "secureResponse"; - - // managesSessions method is implemented by looking for - // corresponding option value in module configuration - static final String MANAGES_SESSIONS = "managesSessions"; - static final String MANAGES_SESSIONS_OPTION = "managessessions"; - - private ConfigFile.Entry[] entries; - private Logger logger; - - AuthContext(ConfigFile.Entry[] entries, - Logger logger) throws AuthException { - - this.entries = entries; - this.logger = logger; - } - - /** - * Invoke modules according to configuration - */ - Object[] invoke(final String methodName, final Object[] args) - throws AuthException { - - // invoke modules in a doPrivileged - final Object rValues[] = new Object[entries.length]; - - try { - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws AuthException { - invokePriv(methodName, args, rValues); - return null; - } - }); - } catch (java.security.PrivilegedActionException pae) { - if (pae.getException() instanceof AuthException) { - throw (AuthException) pae.getException(); - } else { - AuthException ae = new AuthException(); - ae.initCause(pae.getException()); - throw ae; - } - } - return rValues; - } - - void invokePriv(String methodName, Object[] args, Object[] rValues) - throws AuthException { - - // special treatment for managesSessions until the module - // interface can be extended. - if (methodName.equals(AuthContext.MANAGES_SESSIONS)) { - for (int i = 0; i < entries.length; i++) { - Map options = entries[i].getOptions(); - String mS = (String) options.get(AuthContext.MANAGES_SESSIONS_OPTION); - rValues[i] = Boolean.valueOf(mS); - } - return; - } - - boolean success = false; - AuthException firstRequiredError = null; - AuthException firstError = null; - - // XXX no way to reverse module invocation - - for (int i = 0; i < entries.length; i++) { - - // get initialized module instance - - Object module = entries[i].module; - - // invoke the module - - try { - Method[] mArray = module.getClass().getMethods(); - for (int j = 0; j < mArray.length; j++) { - if (mArray[j].getName().equals(methodName)) { - - // invoke module - rValues[i] = mArray[j].invoke(module, args); - - // success - - // return if SUFFICIENT and no previous REQUIRED errors - - if (firstRequiredError == null && - entries[i].getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT) { - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " SUFFICIENT success"); - } - - return; - } - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " success"); - } - - success = true; - break; - } - } - - if (!success) { - // PLEASE NOTE: - // this exception will be thrown if any module - // in the context does not support the method. - NoSuchMethodException nsme = new NoSuchMethodException("module " + - module.getClass().getName() + - " does not implement " + - methodName); - AuthException ae = new AuthException(); - ae.initCause(nsme); - throw ae; - } - } catch (IllegalAccessException iae) { - AuthException ae = new AuthException(); - ae.initCause(iae); - throw ae; - } catch (InvocationTargetException ite) { - - // failure cases - - AuthException ae; - - if (ite.getCause() instanceof AuthException) { - ae = (AuthException) ite.getCause(); - } else { - ae = new AuthException(); - ae.initCause(ite.getCause()); - } - - if (entries[i].getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.REQUISITE) { - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " REQUISITE failure"); - } - - // immediately throw exception - - if (firstRequiredError != null) { - throw firstRequiredError; - } else { - throw ae; - } - - } else if (entries[i].getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.REQUIRED) { - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " REQUIRED failure"); - } - - // save exception and continue - - if (firstRequiredError == null) { - firstRequiredError = ae; - } - - } else { - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " OPTIONAL failure"); - } - - // save exception and continue - - if (firstError == null) { - firstError = ae; - } - } - } - } - - // done invoking entire stack of modules - - if (firstRequiredError != null) { - throw firstRequiredError; - } else if (firstError != null && !success) { - throw firstError; - } - - // if no errors, return gracefully - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("overall " + methodName + " success"); - } - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthException.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthException.java deleted file mode 100644 index 2dac232f1a2..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthException.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * A generic authentication exception. - * - * @version %I%, %G% - */ -public class AuthException extends jakarta.security.auth.message.AuthException { - - private static final long serialVersionUID = -1156951780670243758L; - - /** - * Constructs a AuthException with no detail message. A detail message is a String that describes this particular - * exception. - */ - public AuthException() { - super(); - } - - /** - * Constructs a AuthException with the specified detail message. A detail message is a String that describes this - * particular exception. - * - *

- * - * @param msg the detail message. - */ - public AuthException(String msg) { - super(msg); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthParam.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthParam.java deleted file mode 100644 index e2aabb1a542..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthParam.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * An authentication parameter used to encapsulate a request and response objects. - * - *

- * This is a marker interface for container-specific authentication parameters. - * - * @version %I%, %G% - */ -public interface AuthParam { -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthPolicy.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthPolicy.java deleted file mode 100644 index 71df8df6079..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthPolicy.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2021] Payara Foundation and/or affiliates - -package com.sun.enterprise.security.jauth; - -import jakarta.security.auth.message.MessagePolicy; - -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy; -import static jakarta.security.auth.message.MessagePolicy.TargetPolicy; - -/* - * This class is used to define the message authentication policy that informs - * the actions of AuthModules. - * - *

This class is used to define source and recipient authentication - * policies. Source authentication is used to establish the identity of - * either the message sender or the party that established the message contents. - * Recipient authentication is used to establish the identity of the receiver - * of the message before it is sent. - * - *

This class is used used by the AuthConfig class to define the request and - * response authentication policies associated with Client and Server - * AuthModules. - * - * @version %I%, %G% - * @see AuthConfig - * @see ClientAuthModule - * @see ServerAuthModule - */ -//Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -public class AuthPolicy { - - public static final int SOURCE_AUTH_NONE = 0; - public static final int SOURCE_AUTH_SENDER = 1; - public static final int SOURCE_AUTH_CONTENT = 2; - - public static final String SENDER = "sender"; - public static final String CONTENT = "content"; - public static final String BEFORE_CONTENT = "before-content"; - public static final String AFTER_CONTENT = "after-content"; - - private int authenticateSource = SOURCE_AUTH_NONE; - private boolean authenticateRecipient = false; - private boolean recipientBeforeContent = false; - - private void setAuthenticationType(int sourceAuthType) { - switch (sourceAuthType) { - case SOURCE_AUTH_NONE: - case SOURCE_AUTH_SENDER: - case SOURCE_AUTH_CONTENT: - this.authenticateSource = sourceAuthType; - break; - default: - break; - } - } - - public AuthPolicy() { - } - - public AuthPolicy(int sourceAuthenticationType, - boolean authenticateRecipient, boolean beforeContent) { - setAuthenticationType(sourceAuthenticationType); - this.authenticateRecipient = authenticateRecipient; - this.recipientBeforeContent = beforeContent; - } - - public AuthPolicy(MessagePolicy messagePolicy) { - if (messagePolicy != null) { - TargetPolicy[] targetPolicies = messagePolicy.getTargetPolicies(); - if (targetPolicies != null && targetPolicies.length > 0) { - int contentInd = -1; - int recipientInd = -1; - for (int i = 0; i < targetPolicies.length; i++) { - ProtectionPolicy pp = targetPolicies[i].getProtectionPolicy(); - - if (ProtectionPolicy.AUTHENTICATE_RECIPIENT.equals( - pp.getID())) { - recipientInd = i; - this.authenticateRecipient = true; - } else if (ProtectionPolicy.AUTHENTICATE_SENDER.equals( - pp.getID())) { - contentInd = i; - setAuthenticationType(SOURCE_AUTH_SENDER); - } else if (ProtectionPolicy.AUTHENTICATE_CONTENT.equals( - pp.getID())) { - contentInd = i; - setAuthenticationType(SOURCE_AUTH_CONTENT); - } - } - - if (authenticateRecipient && contentInd >= 0) { - this.recipientBeforeContent = (recipientInd < contentInd); - } - } - } - } - - public void setSourceAuth(int sourceAuthenticationType) { - setAuthenticationType(sourceAuthenticationType); - } - - /* - * Set the source of the message content authentication policy. - * @param required boolean value. When true authentication of the source of the message content is required. When false, - * content authentication will not be required and if authentication of the message sender is required it will remain - * so. - */ - public void setContentAuth(boolean required) { - if (required) { - this.setSourceAuth(SOURCE_AUTH_CONTENT); - } else if (!isSenderAuthRequired()) { - this.setSourceAuth(SOURCE_AUTH_NONE); - } - } - - /* - * Set the message sender authentication policy. - * @param required boolean value. When true authentication of the message sender is required. When false, sender - * authentication will not be required and if authentication of the message content is required it will remain so. - */ - public void setSenderAuth(boolean required) { - if (required) { - this.setSourceAuth(SOURCE_AUTH_SENDER); - } else if (!isContentAuthRequired()) { - this.setSourceAuth(SOURCE_AUTH_NONE); - } - } - - public void setRecipientAuth(boolean required, boolean beforeContent) { - this.authenticateRecipient = required; - this.recipientBeforeContent = beforeContent; - } - - public int getSourceAuth() { - return this.authenticateSource; - } - - public boolean authRequired() { - return this.isSourceAuthRequired() || this.isRecipientAuthRequired(); - } - - public boolean isSourceAuthRequired() { - return this.authenticateSource == 0 ? false : true; - } - - public boolean isSenderAuthRequired() { - return (this.isSourceAuthRequired() ? (this.getSourceAuth() == SOURCE_AUTH_SENDER ? true : false) : false); - } - - public boolean isContentAuthRequired() { - return (this.isSourceAuthRequired() ? (this.getSourceAuth() == SOURCE_AUTH_CONTENT ? true : false) : false); - } - - public boolean isRecipientAuthRequired() { - return this.authenticateRecipient; - } - - // This method interprets order from the perspective of the - // message sender. The value returned by this method, is only - // relevant when recipientAuth is required. - public boolean isRecipientAuthBeforeContent() { - return this.recipientBeforeContent; - } - - // When orderForValidation is true, returns true if validator must - // validate recipient auth (e.g. decrypt) before content auth (e.g. verify - // signature); in which case msg sender did content auth before recipient auth. - // Behaves same as noArg variant when orderForValidation is false. In either - // case, the returned value is only relevant when recipientAuth is required. - public boolean isRecipientAuthBeforeContent(boolean orderForValidation) { - return (orderForValidation ? !this.recipientBeforeContent : this.recipientBeforeContent); - } - - @Override - public String toString() { - - // wait for 1.5 - // StringBuilder sb = new StringBuilder(); - StringBuilder sb = new StringBuilder(); - switch (authenticateSource) { - case SOURCE_AUTH_NONE: - sb.append("source-auth-type = SOURCE_AUTH_NONE"); - break; - case SOURCE_AUTH_SENDER: - sb.append("source-auth-type = SOURCE_AUTH_SENDER"); - break; - case SOURCE_AUTH_CONTENT: - sb.append("source-auth-type = SOURCE_AUTH_CONTENT"); - break; - default: - break; - } - - if (authenticateRecipient) { - sb.append("\n\tauthenticate-recipient=true" + - "\n\tbeforeContent=" + recipientBeforeContent); - } else { - sb.append("\n\tauthenticate-recipient=false"); - } - return sb.toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (!(o instanceof AuthPolicy)) { - return false; - } - - AuthPolicy that = (AuthPolicy) o; - if (this.authenticateSource == that.authenticateSource && - this.authenticateRecipient == that.authenticateRecipient && - this.recipientBeforeContent == that.recipientBeforeContent) { - return true; - } - - return false; - } - - @Override - public int hashCode() { - return authenticateSource + - (authenticateRecipient ? 5 : 0) + - (recipientBeforeContent ? 10 : 0); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthContext.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthContext.java deleted file mode 100644 index 5da320ce0eb..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthContext.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * This ClientAuthContext class manages AuthModules that may be used to secure requests made as a client. A caller - * typically uses this class in the following manner: - * - *

    - *
  1. Retrieve an instance of this class via AuthConfig.getClientAuthContext. - *
  2. Invoke secureRequest.
    - * ClientAuthContext implementation invokes configured plug-in modules. Modules attach credentials to initial request - * object (for example, a username and password), and/or secure the request (for example, sign and encrypt the request). - *
  3. Issue request. - *
  4. Receive response and pass it to validateResponse.
    - * ClientAuthContext implementation invokes configured plug-in modules. Modules verify or decrypt response as necessary. - *
  5. The disposeSubject method may be invoked if necessary to clean up any authentication state in the Subject. - *
- * - *

- * An instance may reuse module instances it previously created. As a result a single module instance may be used to - * issue different requests as different clients. It is the module implementation's responsibility to properly store and - * restore any necessary state. A module that does not need to do so may remain completely stateless. - * - *

- * Instances of this class have custom logic to determine what modules to invoke, and in what order. In addition, this - * custom logic may control whether subsequent modules are invoked based on the success or failure of previously invoked - * modules. - * - *

- * The caller is responsible for passing in a state Map that can be used by underlying modules to save state across a - * sequence of calls from secureRequest to validateResponse to disposeSubject. - * The same Map instance must be passed to all methods in the call sequence. Furthermore, each call sequence should be - * passed its own unique shared state Map instance. - * - * @version %I%, %G% - * @see AuthConfig - * @see SOAPAuthParam - */ -public interface ClientAuthContext { - - /** - * Secure a request message. - * - *

- * Attach authentication credentials to an initial request, sign/encrypt a request, or respond to a server challenge, - * for example. - * - *

- * This method invokes configured modules to secure the request. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to obtain Principals and credentials necessary to secure - * the request, or null. If null, the module may use a CallbackHandler to obtain any information necessary to secure the - * request. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void secureRequest(AuthParam param, - javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * Validate received response. - * - *

- * Validation may include verifying signature in response, or decrypting response contents, for example. - * - *

- * This method invokes configured modules to validate the response. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to store the Principals and credentials related to the - * identity validated in the response. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void validateResponse(AuthParam param, - javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * Dispose of the Subject (remove Principals or credentials from the Subject object that were stored during - * validateResponse). - * - *

- * This method invokes configured modules to dispose the Subject. - * - * @param subject the subject to be disposed. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void disposeSubject(javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthModule.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthModule.java deleted file mode 100644 index 624748ec5c0..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthModule.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; - -/** - * This interface describes a module that can be configured for a ClientAuthContext. The main purpose of this module is - * to secure requests and to validate received responses. - * - *

- * A module implementation must assume it may be used to issue different requests as different clients. It is the module - * implementation's responsibility to properly store and restore any state as necessary. A module that does not need to - * do so may remain completely stateless. - * - *

- * Modules are passed a shared state Map that can be used to save state across a sequence of calls from - * secureRequest to validateResponse to disposeSubject. The same Map instance is - * guaranteed to be passed to all methods in the call sequence. Furthermore, it should be assumed that each call - * sequence is passed its own unique shared state Map instance. - * - * @version %I%, %G% - */ -public interface ClientAuthModule { - - /** - * Initialize this module with a policy to enforce, a CallbackHandler, and administrative options. - * - *

- * Either the the request policy or the response policy (or both) must be non-null. - * - * @param requestPolicy the request policy this module is to enforce, which may be null. - * - * @param responsePolicy the response policy this module is to enforce, which may be null. - * - * @param handler CallbackHandler used to request information from the caller. - * - * @param options administrative options. - */ - void initialize(AuthPolicy requestPolicy, - AuthPolicy responsePolicy, - CallbackHandler handler, - Map options); - - /** - * Secure a request message. - * - *

- * Attach authentication credentials to an initial request, sign/encrypt a request, or respond to a server challenge, - * for example. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to obtain Principals and credentials necessary to secure - * the request, or null. If null, the module may use a CallbackHandler to obtain any information necessary to secure the - * request. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void secureRequest(AuthParam param, - Subject subject, - Map sharedState) - throws AuthException; - - /** - * Validate received response. - * - *

- * Validation may include verifying signature in response, or decrypting response contents, for example. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to store the Principals and credentials related to the - * identity validated in the response. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void validateResponse(AuthParam param, - Subject subject, - Map sharedState) - throws AuthException; - - /** - * Dispose of the Subject. - * - *

- * Remove Principals or credentials from the Subject object that were stored during validateResponse. - * - * @param subject Subject instance to be disposed. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void disposeSubject(Subject subject, Map sharedState) - throws AuthException; -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/DependentCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/DependentCallbackHandler.java deleted file mode 100644 index bafec7e8b76..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/DependentCallbackHandler.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * A marker interface that may be implemented by a CallBackHandler. - *

- * When a CallbackHandler that implements this interface, is passed as an argument to the getServerAuthContext or - * getClientAuthContext methods of the AuthConfig class, the AuthConfig system will wrap the handler in a special - * internal CallbackHandler that will delegate any unsupported Callbacks to the default CallbackHandler of the - * AuthConfig system. The modules of the context will receive this wrapping handler at initialization, and the effect - * will be to allow systems to extend or override the callbacks handled by the default handler of the config system with - * those handled by the wrapped handler. - * - * @version %I%, %G% - */ -public interface DependentCallbackHandler { -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/FailureException.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/FailureException.java deleted file mode 100644 index 827caf61726..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/FailureException.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * Authentication failed. - * - *

- * This exception is thrown by an AuthModule when authentication failed. This exception is only thrown when the module - * has updated the response message in the AuthParam. - * - * @version %I%, %G% - */ -public class FailureException extends AuthException { - - private static final long serialVersionUID = -6634814390418917726L; - - /** - * Constructs a FailureException with no detail message. A detail message is a String that describes this particular - * exception. - */ - public FailureException() { - super(); - } - - /** - * Constructs a FailureException with the specified detail message. A detail message is a String that describes this - * particular exception. - * - * @param msg the detail message. - */ - public FailureException(String msg) { - super(msg); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/HttpServletAuthParam.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/HttpServletAuthParam.java deleted file mode 100644 index 05621e80bc6..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/HttpServletAuthParam.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import jakarta.security.auth.message.MessageInfo; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -/** - * An HTTP Servlet authentication parameter that encapsulates HTTP Servlet request and response objects. - * - *

- * HttpServletAuthParam may be created with null request or response objects. The following table describes when it is - * appropriate to pass null: - * - *

- *                                        Request   Response
- *                                        -------   --------
- *
- * ClientAuthModule.secureRequest         non-null  null
- * ClientAuthModule.validateResponse      null      non-null
- *
- * ServerAuthModule.validateRequest       non-null  null
- * ServerAuthModule.secureResponse        null      non-null
- * 
- * - *

- * As noted above, in the case of ServerAuthModule.validateRequest the module receives a null response - * object. If the implementation of validateRequest encounters an authentication error, it may construct - * the appropriate response object itself and set it into the HttpServletAuthParam via the setResponse - * method. - * - * @version %I%, %G% - */ -public class HttpServletAuthParam implements AuthParam { - - private HttpServletRequest request; - private HttpServletResponse response; - // private static final MessageLayer layer = - // new MessageLayer(MessageLayer.HTTP_SERVLET); - - /** - * Create an HttpServletAuthParam with HTTP request and response objects. - * - * @param request the HTTP Servlet request object, or null. - * @param response the HTTP Servlet response object, or null. - */ - public HttpServletAuthParam(HttpServletRequest request, - HttpServletResponse response) { - this.request = request; - this.response = response; - } - - /** - * Create an HttpServletAuthParam with MessageInfo object. - * - * @param messageInfo - * - */ - public HttpServletAuthParam(MessageInfo messageInfo) { - this.request = (HttpServletRequest) messageInfo.getRequestMessage(); - this.response = (HttpServletResponse) messageInfo.getResponseMessage(); - } - - /** - * Get the HTTP Servlet request object. - * - * @return the HTTP Servlet request object, or null. - */ - public HttpServletRequest getRequest() { - return this.request; - } - - /** - * Get the HTTP Servlet response object. - * - * @return the HTTP Servlet response object, or null. - */ - public HttpServletResponse getResponse() { - return this.response; - } - - /** - * Set a new HTTP Servlet response object. - * - *

- * If a response has already been set (it is non-null), this method returns. The original response is not overwritten. - * - * @param response the HTTP Servlet response object. - * - * @exception IllegalArgumentException if the specified response is null. - */ - public void setResponse(HttpServletResponse response) { - if (response == null) { - throw new IllegalArgumentException("invalid null response"); - } - - if (this.response == null) { - this.response = response; - } - } - - /** - * Get a MessageLayer instance that identifies HttpServlet as the message layer. - * - * @return a MessageLayer instance that identifies HttpServlet as the message layer. - */ - // public MessageLayer getMessageLayer() { - // return layer; - // }; - - /** - * Get the operation related to the encapsulated HTTP Servlet request and response objects. - * - * @return the operation related to the encapsulated request and response objects, or null. - */ - public String getOperation() { - return null; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/PendingException.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/PendingException.java deleted file mode 100644 index 62e0d0fa039..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/PendingException.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * Authentication is pending. - * - *

- * This exception can be thrown by an AuthModule issuing a challenge, for example. - * - * @version %I%, %G% - */ -public class PendingException extends AuthException { - - private static final long serialVersionUID = 1735672964915327465L; - - /** - * Constructs a PendingException with no detail message. A detail message is a String that describes this particular - * exception. - */ - public PendingException() { - super(); - } - - /** - * Constructs a PendingException with the specified detail message. A detail message is a String that describes this - * particular exception. - * - *

- * - * @param msg the detail message. - */ - public PendingException(String msg) { - super(msg); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthContext.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthContext.java deleted file mode 100644 index 800f836cb8c..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthContext.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * This ServerAuthContext class manages AuthModules that may be used to validate client requests. A caller typically - * uses this class in the following manner: - * - *

    - *
  1. Retrieve an instance of this class via AuthConfig.getServerAuthContext. - *
  2. Receive initial client request and pass it to validateRequest.
    - * Configured plug-in modules validate credentials present in request (for example, decrypt and verify a signature). If - * credentials valid and sufficient, return. Otherwise throw an AuthException. - *
  3. Authentication complete.
    - * Perform authorization check on authenticated identity and, if successful, dispatch to requested service application. - *
  4. Service application finished. - *
  5. Invoke secureResponse.
    - * Configured modules secure response (sign and encrypt it, for example). - *
  6. Send final response to client. - *
  7. The disposeSubject method may be invoked it necessary to clean up any authentication state in the Subject. - *
- * - *

- * An instance may reuse module instances it previous created. As a result a single module instance may be used to - * process different requests from different clients. It is the module implementation's responsibility to properly store - * and restore any state necessary to associate new requests with previous responses. A module that does not need to do - * so may remain completely stateless. - * - *

- * Instances of this class have custom logic to determine what modules to invoke, and in what order. In addition, this - * custom logic may control whether subsequent modules are invoked based on the success or failure of previously invoked - * modules. - * - *

- * The caller is responsible for passing in a state Map that can be used by underlying modules to save state across a - * sequence of calls from validateRequest to secureResponse to disposeSubject. - * The same Map instance must be passed to all methods in the call sequence. Furthermore, each call sequence should be - * passed its own unique shared state Map instance. - * - * @version %I%, %G% - * @see AuthConfig - * @see SOAPAuthParam - */ -public interface ServerAuthContext { - - /** - * Authenticate a client request. (decrypt the message and verify a signature, for exmaple). - * - *

- * This method invokes configured modules to authenticate the request. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to store and Principals and credentials validated in the - * request. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception PendingException if the operation is pending (for example, when a module issues a challenge). The module - * must have updated the response object in the AuthParam input parameter. - * - * @exception FailureException if the authentication failed. The module must have updated the response object in the - * AuthParam input parameter. - * - * @exception AuthException if the operation failed. - */ - void validateRequest(AuthParam param, - javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * Secure the response to the client (sign and encrypt the response, for example). - * - *

- * This method invokes configured modules to secure the response. - * - * @param param an authentication parameter that encapsulates the client request and server response objects - * - * @param subject the subject may be used by configured modules to obtain credentials needed to secure the response, or - * null. If null, the module may use a CallbackHandler to obtain the necessary information. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void secureResponse(AuthParam param, - javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * Dispose of the Subject (remove Principals or credentials from the Subject object that were stored during - * validateRequest). - * - *

- * This method invokes configured modules to dispose the Subject. - * - * @param subject the subject to be disposed. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void disposeSubject(javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * modules manage sessions used by calling container to determine if it should delegate session management (including - * the mapping of requests to authentication results established from previous requests) to the underlying - * authentication modules of the context. - *

- * When this method returns true, the container should call validate on every request, and as such may depend on the - * invoked modules to determine when a request pertains to an existing authentication session. - *

- * When this method returns false, the container may employ is own session management functionality, and may use this - * functionality to recognize when an exiting request is to be interpretted in the context of an existing authentication - * session. - * - * @return true if the context should be allowed to manage sessions, and false if session management (if it is to occur) - * must be performed by the container. - * - * @exception AuthException if the operation failed. - */ - boolean managesSessions(java.util.Map sharedState) - throws AuthException; - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthModule.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthModule.java deleted file mode 100644 index c7515e443dc..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthModule.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; - -/** - * This interface describes a module that can be configured for a ServerAuthContext. The main purpose of this module is - * to validate client requests and to secure responses back to the client. - * - *

- * A module implementation must assume it may be shared across different requests from different clients. It is the - * module implementation's responsibility to properly store and restore any state necessary to associate new requests - * with previous responses. A module that does not need to do so may remain completely stateless. - * - *

- * Modules are passed a shared state Map that can be used to save state across a sequence of calls from - * validateRequest to secureResponse to disposeSubject. The same Map instance is - * guaranteed to be passed to all methods in the call sequence. Furthermore, it should be assumed that each call - * sequence is passed its own unique shared state Map instance. - * - * @version %I%, %G% - */ -public interface ServerAuthModule { - - /** - * Initialize this module with a policy to enforce, a CallbackHandler, and administrative options. - * - *

- * Either the the request policy or the response policy (or both) must be non-null. - * - * @param requestPolicy the request policy this module is to enforce, which may be null. - * - * @param responsePolicy the response policy this module is to enforce, which may be null. - * - * @param handler CallbackHandler used to request information from the caller. - * - * @param options administrative options. - */ - void initialize(AuthPolicy requestPolicy, - AuthPolicy responsePolicy, - CallbackHandler handler, - Map options); - - /** - * Authenticate a client request. - * - *

- * The AuthParam input parameter encapsulates the client request and server response objects. This ServerAuthModule - * validates the client request object (decrypts content and verifies a signature, for example). - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to store and Principals and credentials validated in the - * request. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception PendingException if the operation is pending (for example, when a module issues a challenge). The module - * must have updated the response object in the AuthParam. - * - * @exception FailureException if the authentication failed. The module must have updated the response object in the - * AuthParam. - * - * @exception AuthException if the operation failed. - */ - void validateRequest(AuthParam param, - Subject subject, - Map sharedState) - throws AuthException; - - /** - * Secure the response to the client (sign and encrypt the response, for example). - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to obtain credentials needed to secure the response, or - * null. If null, the module may use a CallbackHandler to obtain the necessary information. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void secureResponse(AuthParam param, - Subject subject, - Map sharedState) - throws AuthException; - - /** - * Dispose of the Subject. - * - *

- * Remove Principals or credentials from the Subject object that were stored during validateRequest. - * - * @param subject the Subject instance to be disposed. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void disposeSubject(Subject subject, Map sharedState) - throws AuthException; -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/CertStoreCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/CertStoreCallback.java deleted file mode 100644 index fd48ab23dd3..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/CertStoreCallback.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.security.KeyStore; -import java.security.cert.CertStore; -import javax.security.auth.callback.Callback; - -/** - * Callback for CertStore. - * - *

A CertStore is a generic repository for certificates. - * CertStores may be searched to locate public key certificates, - * as well as to put together certificate chains. - * Such a search may be necessary when the caller needs to - * verify a signature. - * - * @version %I%, %G% - */ -public class CertStoreCallback extends - jakarta.security.auth.message.callback.CertStoreCallback { - - /** - * Set the CertStore. - * - * @param certStore the certificate store, which may be null - * If null, the requester is assumed to already have - * access to the relevant certificate and/or chain. - */ - public void setStore(CertStore certStore) { - setCertStore(certStore); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/KerberosKeyCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/KerberosKeyCallback.java deleted file mode 100644 index 550999f79c7..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/KerberosKeyCallback.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import javax.security.auth.Subject; -import javax.security.auth.kerberos.*; -import javax.security.auth.callback.Callback; - -/** - * Callback for Kerberos Key. - * - * @version 1.4, 03/03/04 - */ -public class KerberosKeyCallback implements Callback { - - private KerberosPrincipal owner; - private KerberosKey key; - - /** - * Constructs this KerberosSubjectCallback with a KerberosPrincipal. - * - *

The owner input parameter - * specifies the owner of the KerberosKey to be returned. - * - * @param owner the owner of the KerberosKey to be returned - */ - public KerberosKeyCallback(KerberosPrincipal owner) { - this.owner = owner; - } - - /** - * Get the owner. - * - * @return the owner - */ - public KerberosPrincipal getOwner() { - return owner; - } - - /** - * Set the requested Kerberos key. - * - * @param key the Kerberos key - */ - public void setKey(KerberosKey key) { - this.key = key; - } - - /** - * Get the requested Kerberos key. - * - * @return the Kerberos key - */ - public KerberosKey getKey() { - return key; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PasswordValidationCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PasswordValidationCallback.java deleted file mode 100644 index 86b77dd5871..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PasswordValidationCallback.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import javax.security.auth.callback.Callback; -import java.util.Arrays; - -/** - * Callback for PasswordValidation. - * - * @version %I%, %G% - */ -public class PasswordValidationCallback extends - jakarta.security.auth.message.callback.PasswordValidationCallback { - - /** - * Create a PasswordValidationCallback. - * - * @param username the username to authenticate - * - * @param password the user's password, which may be null. - */ - public PasswordValidationCallback(String username, char[] password) { - super(null, username, password); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PrivateKeyCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PrivateKeyCallback.java deleted file mode 100644 index bbb8c51756c..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PrivateKeyCallback.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.math.BigInteger; -import java.security.PrivateKey; -import java.security.cert.Certificate; -import javax.security.auth.callback.Callback; -import javax.security.auth.x500.X500Principal; - -/** - * Callback for private key and corresponding certificate chain. - * - * @version %I%, %G% - */ -public class PrivateKeyCallback - extends jakarta.security.auth.message.callback.PrivateKeyCallback { - - /** - * Marker interface for private key request types. - */ - public static interface Request extends - jakarta.security.auth.message.callback.PrivateKeyCallback.Request { }; - - /** - * Request type for private keys that are identified via an alias. - */ - public static class AliasRequest extends - jakarta.security.auth.message.callback.PrivateKeyCallback.AliasRequest - implements Request { - - /** - * Construct an AliasRequest with an alias. - * - *

The alias is used to directly identify the private key - * to be returned. The corresponding certificate chain for the - * private key is also returned. - * - *

If the alias is null, - * the handler of the callback relies on its own default. - * - * @param alias name identifier for the private key, or null. - */ - public AliasRequest(String alias) { - super(alias); - } - } - - /** - * Request type for private keys that are identified via a SubjectKeyID - */ - public static class SubjectKeyIDRequest extends - jakarta.security.auth.message.callback.PrivateKeyCallback.SubjectKeyIDRequest - implements Request { - - /** - * Construct a SubjectKeyIDRequest with an subjectKeyID. - * - *

The subjectKeyID is used to directly identify the private key - * to be returned. The corresponding certificate chain for the - * private key is also returned. - * - *

If the subjectKeyID is null, - * the handler of the callback relies on its own default. - * - * @param subjectKeyID identifier for the private key, or null. - */ - public SubjectKeyIDRequest(byte[] subjectKeyID) { - super(subjectKeyID); - } - } - - /** - * Request type for private keys that are identified via an - * issuer/serial number. - */ - public static class IssuerSerialNumRequest extends - jakarta.security.auth.message.callback.PrivateKeyCallback.IssuerSerialNumRequest - implements Request { - - /** - * Constructs a IssuerSerialNumRequest with an issuer/serial number. - * - *

The issuer/serial number are used to identify a - * public key certificate. The corresponding private key - * is returned in the callback. The corresponding certificate chain - * for the private key is also returned. - * - * If the issuer/serialNumber parameters are null, - * the handler of the callback relies on its own defaults. - * - * @param issuer the X500Principal name of the certificate issuer, - * or null. - * - * @param serialNumber the serial number of the certificate, - * or null. - */ - public IssuerSerialNumRequest(X500Principal issuer, - BigInteger serialNumber) { - super(issuer, serialNumber); - } - } - - /** - * Constructs this PrivateKeyCallback with a private key Request object. - * - *

The request object identifies the private key - * to be returned. The corresponding certificate chain for the - * private key is also returned. - * - *

If the request object is null, - * the handler of the callback relies on its own default. - * - * @param request identifier for the private key, or null. - */ - public PrivateKeyCallback(Request request) { - super(request); - } - - /** - * Get the Request object which identifies the private key to be returned. - * - * @return the Request object which identifies the private key - * to be returned, or null. If null, the handler of the callback - * relies on its own default. - */ - public Request getRequest() { - return (Request)super.getRequest(); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SecretKeyCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SecretKeyCallback.java deleted file mode 100644 index b69af5715e7..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SecretKeyCallback.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.math.BigInteger; -import java.security.Principal; -import javax.crypto.SecretKey; -import javax.security.auth.callback.Callback; - -/** - * Callback for private key and corresponding certificate chain. - * - * @version %I%, %G% - */ -public class SecretKeyCallback - extends jakarta.security.auth.message.callback.SecretKeyCallback { - - /** - * Marker interface for private key request types. - */ - public static interface Request extends - jakarta.security.auth.message.callback.SecretKeyCallback.Request { }; - - /** - * Request type for secret keys that are identified via an alias. - */ - public static class AliasRequest extends - jakarta.security.auth.message.callback.SecretKeyCallback.AliasRequest - implements Request { - - /** - * Construct an AliasRequest with an alias. - * - *

The alias is used to directly identify the secret key - * to be returned. - * - *

If the alias is null, - * the handler of the callback relies on its own default. - * - * @param alias name identifier for the secret key, or null. - */ - public AliasRequest(String alias) { - super(alias); - } - } - - /** - * Constructs this SecretKeyCallback with a secret key Request object. - * - *

The request object identifies the secret key - * to be returned. - * - * If the alias is null, the handler of the callback - * relies on its own default. - * - * @param request request object identifying the secret key, or null. - */ - public SecretKeyCallback(Request request) { - super(request); - } - - /** - * Get the Request object which identifies the secret key to be returned. - * - * @return the Request object which identifies the private key - * to be returned, or null. If null, the handler of the callback - * relies on its own deafult. - */ - public Request getRequest() { - return (Request)super.getRequest(); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SignatureKeyCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SignatureKeyCallback.java deleted file mode 100644 index 01ec9bf8554..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SignatureKeyCallback.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.security.KeyStore; -import java.security.PrivateKey; -import javax.crypto.SecretKey; -import java.security.cert.Certificate; -import javax.security.auth.callback.Callback; -import javax.security.auth.x500.X500Principal; - -/** - * Callback for Signing Key. - * - * @version 1.8, 03/03/04 - */ -public class SignatureKeyCallback implements Callback { - - private PrivateKey key; - private X500Principal authority; - private Certificate[] chain; - - /** - * Constructs this SignatureKeyCallback with an authority. - * - *

Both a PrivateKey and corresponding certificate chain - * will be returned. The authority input parameter - * specifies the X500Principal name of the root CA - * certificate returned in the chain. - * An authority does not have to be specified. - * - * @param authority the X500Principal name of the root CA - * certificate returned in the requested chain, - * or null - */ - public SignatureKeyCallback(X500Principal authority) { - this.authority = authority; - } - - /** - * Get the authority. - * - * @return the authority, or null - */ - public X500Principal getAuthority() { - return authority; - } - - /** - * Set the requested signing key. - * - * @param key the signing key - * @param chain the corresponding certificate chain - */ - public void setKey(PrivateKey key, Certificate[] chain) { - this.key = key; - this.chain = chain; - } - - /** - * Get the requested signing key. - * - * @return the signing key - */ - public PrivateKey getKey() { - return key; - } - - /** - * Get the certificate chain. - * - * @return the certificate chain - */ - public Certificate[] getChain() { - return chain; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/TrustStoreCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/TrustStoreCallback.java deleted file mode 100644 index bc51540c0c6..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/TrustStoreCallback.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.security.KeyStore; -import javax.security.auth.callback.Callback; - -/** - * Callback for trusted certificate KeyStore. - * - *

A trusted certificate KeyStore may be used to determine - * whether a given certificate chain can be trusted. - * - * @version %I%, %G% - */ -public class TrustStoreCallback - extends jakarta.security.auth.message.callback.TrustStoreCallback { - - /** - * Set the trusted certificate KeyStore. - * - * @param trustStore the trusted certificate KeyStore, - * which must already be loaded. - */ - public void setStore(KeyStore trustStore) { - setTrustStore(trustStore); - } -} diff --git a/appserver/security/core-ee/src/test/resources/com/sun/enterprise/security/permissionsxml/server.policy b/appserver/security/core-ee/src/test/resources/com/sun/enterprise/security/permissionsxml/server.policy index e66e53c943b..ef2e0a82fe0 100644 --- a/appserver/security/core-ee/src/test/resources/com/sun/enterprise/security/permissionsxml/server.policy +++ b/appserver/security/core-ee/src/test/resources/com/sun/enterprise/security/permissionsxml/server.policy @@ -118,7 +118,8 @@ grant { // Following needed for CTS to pass with SM on, bug 16344201 permission java.lang.RuntimePermission "closeClassLoader"; permission java.io.SerializablePermission "enableSubstitution"; - permission java.security.SecurityPermission "getProperty.package.definition"; + permission java.security.SecurityPermission "getProperty.package.definition"; + permission java.security.SecurityPermission "getProperty.authconfigprovider.factory.providers"; }; // Following grant block is only required by Connectors. If Connectors diff --git a/appserver/security/jaspic-provider-framework/auth.conf b/appserver/security/jaspic-provider-framework/auth.conf deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/appserver/security/jaspic-provider-framework/osgi.bundle b/appserver/security/jaspic-provider-framework/osgi.bundle deleted file mode 100644 index 46a378460ef..00000000000 --- a/appserver/security/jaspic-provider-framework/osgi.bundle +++ /dev/null @@ -1,48 +0,0 @@ -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. -# -# Copyright (c) 2010-2011 Oracle and/or its affiliates. All rights reserved. -# -# The contents of this file are subject to the terms of either the GNU -# General Public License Version 2 only ("GPL") or the Common Development -# and Distribution License("CDDL") (collectively, the "License"). You -# may not use this file except in compliance with the License. You can -# obtain a copy of the License at -# https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html -# or packager/legal/LICENSE.txt. See the License for the specific -# language governing permissions and limitations under the License. -# -# When distributing the software, include this License Header Notice in each -# file and include the License file at packager/legal/LICENSE.txt. -# -# GPL Classpath Exception: -# Oracle designates this particular file as subject to the "Classpath" -# exception as provided by Oracle in the GPL Version 2 section of the License -# file that accompanied this code. -# -# Modifications: -# If applicable, add the following below the License Header, with the fields -# enclosed by brackets [] replaced by your own identifying information: -# "Portions Copyright [year] [name of copyright owner]" -# -# Contributor(s): -# If you wish your version of this file to be governed by only the CDDL or -# only the GPL Version 2, indicate your decision by adding "[Contributor] -# elects to include this software in this distribution under the [CDDL or GPL -# Version 2] license." If you don't indicate a single choice of license, a -# recipient has the option to distribute your version of this file under -# either the CDDL, the GPL Version 2 or to extend the choice of license to -# its licensees as provided above. However, if you add GPL Version 2 code -# and therefore, elected the GPL Version 2 license, then the option applies -# only if the new code is made subject to such option by the copyright -# holder. -# -# Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] --exportcontents: \ - com.sun.jaspic.config.delegate; \ - com.sun.jaspic.config.factory; \ - com.sun.jaspic.config.jaas; \ - com.sun.jaspic.config.servlet; \ - com.sun.logging.enterprise.system.jaspic.security; \ - com.sun.jaspic.config.helper; version=${project.osgi.version} - diff --git a/appserver/security/jaspic-provider-framework/pom.xml b/appserver/security/jaspic-provider-framework/pom.xml deleted file mode 100644 index e923a2c6615..00000000000 --- a/appserver/security/jaspic-provider-framework/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - 4.0.0 - - - fish.payara.server.core - core-parent - 7.0.0.Alpha3-SNAPSHOT - ../../../core/core-parent - - - fish.payara.server.core.security - jaspic.provider.framework - glassfish-jar - - Jaspic Provider Framework - - JASPIC (JSR-196) Provider Framework Reference Implementation. - - This module contains a Payara/GlassFish independent partial reference implementation - of JASPIC. Due to the way JASPIC works this does not implement a full RI, as JASPIC - is not so much an independent library but an SPI for Servlet and SOAP container to call - out to external authentication mechanisms. - - Despite that, this module's goal is to implement as much JASPIC general reference functionality - without any server specific dependencies. - - - - - - jakarta.authentication - jakarta.authentication-api - - - jakarta.servlet - jakarta.servlet-api - - - org.glassfish.soteria - jakarta.security.enterprise - - - org.glassfish.epicyro - epicyro - - - diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/delegate/MessagePolicyDelegate.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/delegate/MessagePolicyDelegate.java deleted file mode 100644 index 245656b4e0f..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/delegate/MessagePolicyDelegate.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.jaspic.config.delegate; - -import java.util.Map; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; - -/** - * - * @author ronmonzillo - */ -public interface MessagePolicyDelegate { - - MessagePolicy getRequestPolicy(String authContextID, Map properties); - - MessagePolicy getResponsePolicy(String authContextID, Map properties); - - Class[] getMessageTypes(); - - String getAuthContextID(MessageInfo messageInfo); - - boolean isProtected(); -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultAuthConfigProvider.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultAuthConfigProvider.java deleted file mode 100644 index 2565cd4b8a7..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultAuthConfigProvider.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2015, 2020 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.jaspic.config.factory; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * This class functions as a kind of factory-factory for {@link ServerAuthConfig} instances, which are by themselves factories - * for {@link ServerAuthContext} instances, which are delegates for the actual {@link ServerAuthModule} (SAM) that we're after. - * - * @author Arjan Tijms - */ -public class DefaultAuthConfigProvider implements AuthConfigProvider { - - private static final String CALLBACK_HANDLER_PROPERTY_NAME = "authconfigprovider.client.callbackhandler"; - - private Map providerProperties; - private ServerAuthModule sam; - - public DefaultAuthConfigProvider(ServerAuthModule sam) { - this.sam = sam; - } - - /** - * Constructor with signature and implementation that's required by API. - * - * @param properties provider properties - * @param factory the auth config factory - */ - public DefaultAuthConfigProvider(Map properties, AuthConfigFactory factory) { - this.providerProperties = properties; - - // API requires self registration if factory is provided. Not clear - // where the "layer" (2nd parameter) - // and especially "appContext" (3rd parameter) values have to come from - // at this place. - if (factory != null) { - // If this method ever gets called, it may throw a SecurityException. - // Don't bother with a PrivilegedAction as we don't expect to ever be - // constructed this way. - factory.registerConfigProvider(this, null, null, "Auto registration"); - } - } - - /** - * The actual factory method that creates the factory used to eventually obtain the delegate for a SAM. - */ - @Override - public ServerAuthConfig getServerAuthConfig( - String layer, String appContext, CallbackHandler handler) - throws AuthException, SecurityException { - return new DefaultServerAuthConfig( - layer, appContext, - handler == null ? createDefaultCallbackHandler() : handler, - providerProperties, sam - ); - } - - @Override - public ClientAuthConfig getClientAuthConfig( - String layer, String appContext, CallbackHandler handler) - throws AuthException, SecurityException { - return null; - } - - @Override - public void refresh() { - } - - /** - * Creates a default callback handler via the system property - * "authconfigprovider.client.callbackhandler", as seemingly required by the - * API (API uses wording "may" create default handler). TODO: Isn't - * "authconfigprovider.client.callbackhandler" JBoss specific? - * - * @return - * @throws AuthException - */ - private CallbackHandler createDefaultCallbackHandler() throws AuthException { - String callBackClassName = System.getProperty(CALLBACK_HANDLER_PROPERTY_NAME); - - if (callBackClassName == null) { - throw new AuthException("No default handler set via system property: " + CALLBACK_HANDLER_PROPERTY_NAME); - } - - try { - return (CallbackHandler) Thread.currentThread().getContextClassLoader().loadClass(callBackClassName).newInstance(); - } catch (Exception e) { - throw new AuthException(e.getMessage()); - } - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthConfig.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthConfig.java deleted file mode 100644 index a3b0cda4459..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthConfig.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2015, 2020 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.jaspic.config.factory; - -import java.util.Map; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * This class functions as a kind of factory for {@link ServerAuthContext} instances, which are delegates for the actual - * {@link ServerAuthModule} (SAM) that we're after. - * - * @author Arjan Tijms - */ -public class DefaultServerAuthConfig implements ServerAuthConfig { - - private String layer; - private String appContext; - private CallbackHandler handler; - private Map providerProperties; - private ServerAuthModule serverAuthModule; - - public DefaultServerAuthConfig(String layer, String appContext, CallbackHandler handler, - Map providerProperties, ServerAuthModule serverAuthModule) { - this.layer = layer; - this.appContext = appContext; - this.handler = handler; - this.providerProperties = providerProperties; - this.serverAuthModule = serverAuthModule; - } - - @Override - public ServerAuthContext getAuthContext(String authContextID, Subject serviceSubject, - @SuppressWarnings("rawtypes") Map properties) throws AuthException { - return new DefaultServerAuthContext(handler, serverAuthModule); - } - - // ### The methods below mostly just return what has been passed into the - // constructor. - // ### In practice they don't seem to be called - - @Override - public String getMessageLayer() { - return layer; - } - - /** - * It's not entirely clear what the difference is between the "application context identifier" (appContext) and the - * "authentication context identifier" (authContext). In early iterations of the specification, authContext was called - * "operation" and instead of the MessageInfo it was obtained by something called an "authParam". - */ - @Override - public String getAuthContextID(MessageInfo messageInfo) { - return appContext; - } - - @Override - public String getAppContext() { - return appContext; - } - - @Override - public void refresh() { - } - - @Override - public boolean isProtected() { - return false; - } - - public Map getProviderProperties() { - return providerProperties; - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthContext.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthContext.java deleted file mode 100644 index 3c15f6ba4ee..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthContext.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2015, 2020 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.jaspic.config.factory; - -import java.util.Collections; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.ServerAuth; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * The Server Authentication Context is an extra (required) indirection between the Application Server and the actual Server - * Authentication Module (SAM). This can be used to encapsulate any number of SAMs and either select one at run-time, invoke - * them all in order, etc. - *

- * Since this simple example only has a single SAM, we delegate directly to that one. Note that this {@link ServerAuthContext} - * and the {@link ServerAuthModule} (SAM) share a common base interface: {@link ServerAuth}. - * - * @author Arjan Tijms - */ -public class DefaultServerAuthContext implements ServerAuthContext { - - private final ServerAuthModule sam; - - public DefaultServerAuthContext(CallbackHandler handler, ServerAuthModule sam) throws AuthException { - this.sam = sam; - this.sam.initialize(null, null, handler, Collections.emptyMap()); - } - - @Override - public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) - throws AuthException { - return sam.validateRequest(messageInfo, clientSubject, serviceSubject); - } - - @Override - public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException { - return sam.secureResponse(messageInfo, serviceSubject); - } - - @Override - public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { - sam.cleanSubject(messageInfo, subject); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/EntryInfo.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/EntryInfo.java deleted file mode 100644 index 488e79b2355..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/EntryInfo.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; - -/** - * Each entry is either a constructor entry or a registration entry. Use nulls rather than empty Strings or Lists for - * fields that have no value. - * - * This class will not be used outside of its package. - * - * @author Bobby Bissett - */ -public final class EntryInfo { - - private final String className; - private final Map properties; - - private List registrationContexts; - - /* - * This will create a constructor entry. The className must not be null. ONLY CONSTRUCTOR that should be used used to - * construct defaultEntries (passed RegStoreFileParser construction). DO NOT USE OTHER CONSTRUCTORS to define - * defaultEntries because they can create persisted registration entries which are not appropriate as defaultEntries. - */ - public EntryInfo(String className) { - this(className, null); - } - - /* - * This will create a constructor entry. The className must not be null. ONLY OTHER CONSTRUCTOR that should be used used - * to construct defaultEntries (passed RegStoreFileParser construction). DO NOT USE OTHER CONSTRUCTORS to define - * defaultEntries because they can create persisted registration entries which are not appropriate as defaultEntries. - */ - public EntryInfo(String className, Map properties) { - if (className == null) { - throw new IllegalArgumentException("Class name for registration entry cannot be null"); - } - - this.className = className; - this.properties = properties; - } - - /* - * This will create a registration entry. The list of registration contexts must not be null or empty. Each registration - * context will contain at least a non-null layer or appContextId. - */ - EntryInfo(String className, Map properties, List ctxs) { - if (ctxs == null || ctxs.isEmpty()) { - throw new IllegalArgumentException("Registration entry must contain one or more registration contexts"); - } - - this.className = className; - this.properties = properties; - this.registrationContexts = ctxs; - } - - /* - * THIS METHOD MAY BE USED FOR CONSTRUCTOR OR REGISTRATION ENTRIES A helper method for creating a registration entry - * with one registration context. If the context is null, this entry is a constructor entry. - */ - EntryInfo(String className, Map properties, RegistrationContext registrationContext) { - this.className = className; - this.properties = properties; - - if (registrationContext != null) { - - RegistrationContext ctxImpl = new RegistrationContextImpl( - registrationContext.getMessageLayer(), - registrationContext.getAppContext(), - registrationContext.getDescription(), - registrationContext.isPersistent()); - - List newList = new ArrayList(1); - newList.add(ctxImpl); - this.registrationContexts = newList; - } - } - - EntryInfo(EntryInfo parent) { - this.className = parent.className; - this.properties = parent.properties; - - if (parent.registrationContexts != null) { - this.registrationContexts = new ArrayList(1); - - for (RegistrationContext registrationContext : parent.registrationContexts) { - this.registrationContexts.add(registrationContext); - } - } - } - - boolean isConstructorEntry() { - return registrationContexts == null; - } - - String getClassName() { - return className; - } - - Map getProperties() { - return properties; - } - - List getRegistrationContexts() { - return registrationContexts; - } - - /* - * Compares an entry info to this one. They are considered to match if: - they are both constructor or are both - * registration entries - the classnames are equal or are both null - the property maps are equal or are both null If - * the entry is a registration entry, registration contexts are not considered for our purposes. For instance, we may - * want to get a certain registration entry in order to add a registration context to it. - * @see com.sun.enterprise.security.jaspic.config.RegStoreFileParser - */ - boolean matchConstructors(EntryInfo target) { - if (target == null) { - return false; - } - - return (!(isConstructorEntry() ^ target.isConstructorEntry()) && matchStrings(className, target.getClassName()) - && matchMaps(properties, target.getProperties())); - } - - /* - * Utility method for comparing strings such that two null strings are considered "equal." - */ - static boolean matchStrings(String s1, String s2) { - if (s1 == null && s2 == null) { - return true; - } - - if (s1 == null || s2 == null) { - return false; - } - - return s1.equals(s2); - } - - /* - * Utility method for comparing maps such that two null maps are considered "equal." - */ - static boolean matchMaps(Map map1, Map map2) { - if (map1 == null && map2 == null) { - return true; - } - - if (map1 == null || map2 == null) { - return false; - } - - return map1.equals(map2); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegistrationContextImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegistrationContextImpl.java deleted file mode 100644 index 4d18a59e3cf..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegistrationContextImpl.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; - -/** - * Class used by {@link BaseAuthConfigFactory}, {@link EntryInfo} and {@link RegStoreFileParser} - * - * This class will *not* be used outside of its package. - */ -final class RegistrationContextImpl implements RegistrationContext { - - private final String messageLayer; - private final String appContext; - private final String description; - private final boolean isPersistent; - - RegistrationContextImpl(String messageLayer, String appContext, String description, boolean persistent) { - this.messageLayer = messageLayer; - this.appContext = appContext; - this.description = description; - this.isPersistent = persistent; - } - - // helper method to create impl class - RegistrationContextImpl(RegistrationContext registrationContext) { - this.messageLayer = registrationContext.getMessageLayer(); - this.appContext = registrationContext.getAppContext(); - this.description = registrationContext.getDescription(); - this.isPersistent = registrationContext.isPersistent(); - } - - @Override - public String getMessageLayer() { - return messageLayer; - } - - @Override - public String getAppContext() { - return appContext; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public boolean isPersistent() { - return isPersistent; - } - - @Override - public boolean equals(Object o) { - if (o == null || !(o instanceof RegistrationContext)) { - return false; - } - - RegistrationContext target = (RegistrationContext) o; - - return (EntryInfo.matchStrings(messageLayer, target.getMessageLayer()) && - EntryInfo.matchStrings(appContext, target.getAppContext()) && - isPersistent() == target.isPersistent()); - } - - @Override - public int hashCode() { - int hash = 7; - hash = 17 * hash + (this.messageLayer != null ? this.messageLayer.hashCode() : 0); - hash = 17 * hash + (this.appContext != null ? this.appContext.hashCode() : 0); - hash = 17 * hash + (this.isPersistent ? 1 : 0); - - return hash; - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigImpl.java deleted file mode 100644 index b1161a96d9f..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigImpl.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.helper; - -import static java.util.logging.Level.FINE; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; - -/** - * Base class for the {@link ClientAuthConfigImpl} and {@link ServerAuthConfigImpl}. - * - * @author Ron Monzillo - */ -public abstract class BaseAuthConfigImpl { - - String loggerName; - EpochCarrier providerEpoch; - long epoch; - MessagePolicyDelegate policyDelegate; - String layer; - String appContext; - CallbackHandler callbackHandler; - - private ReentrantReadWriteLock instanceReadWriteLock = new ReentrantReadWriteLock(); - private Lock instanceReadLock = instanceReadWriteLock.readLock(); - private Lock instanceWriteLock = instanceReadWriteLock.writeLock(); - - public BaseAuthConfigImpl(String loggerName, EpochCarrier providerEpoch, MessagePolicyDelegate mpDelegate, String layer, - String appContext, CallbackHandler cbh) throws AuthException { - this.loggerName = loggerName; - this.providerEpoch = providerEpoch; - this.policyDelegate = mpDelegate; - this.layer = layer; - this.appContext = appContext; - this.callbackHandler = cbh; - - initialize(); - } - - public String getMessageLayer() { - return layer; - } - - public String getAppContext() { - return appContext; - } - - public String getAuthContextID(MessageInfo messageInfo) { - return policyDelegate.getAuthContextID(messageInfo); - } - - public void refresh() { - try { - initialize(); - } catch (AuthException ae) { - throw new RuntimeException(ae); - } - } - - private void initialize() throws AuthException { - instanceWriteLock.lock(); - try { - this.epoch = providerEpoch.getEpoch(); - initializeContextMap(); - } finally { - instanceWriteLock.unlock(); - } - } - - private void doRefreshIfNeeded() { - boolean hasChanged = false; - instanceReadLock.lock(); - try { - hasChanged = providerEpoch.hasChanged(epoch); - } finally { - instanceReadLock.unlock(); - } - - if (hasChanged) { - refresh(); - } - } - - private Integer getHashCode(Map properties) { - if (properties == null) { - return Integer.valueOf("0"); - } - - return Integer.valueOf(properties.hashCode()); - } - - private M getContextFromMap(Map> contextMap, String authContextID, Map properties) { - M context = null; - - Map internalMap = contextMap.get(authContextID); - if (internalMap != null) { - context = internalMap.get(getHashCode(properties)); - } - - if (context != null) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "AuthContextID found in Map: ", authContextID); - } - } - - return context; - } - - @SuppressWarnings("unchecked") - protected final M getContext(Map> contextMap, String authContextID, Subject subject, - Map properties) - throws AuthException { - - M context = null; - - doRefreshIfNeeded(); - - instanceReadLock.lock(); - try { - context = getContextFromMap(contextMap, authContextID, properties); - if (context != null) { - return context; - } - } finally { - instanceReadLock.unlock(); - } - - instanceWriteLock.lock(); - try { - context = getContextFromMap(contextMap, authContextID, properties); - if (context == null) { - - context = (M) createAuthContext(authContextID, properties); - - Map internalMap = contextMap.get(authContextID); - if (internalMap == null) { - internalMap = new HashMap(); - contextMap.put(authContextID, internalMap); - } - - internalMap.put(getHashCode(properties), context); - } - return context; - } finally { - instanceWriteLock.unlock(); - } - } - - protected boolean isLoggable(Level level) { - return Logger.getLogger(loggerName).isLoggable(level); - } - - protected void logIfLevel(Level level, Throwable t, String... msgParts) { - Logger logger = Logger.getLogger(loggerName); - - if (logger.isLoggable(level)) { - StringBuilder messageBuffer = new StringBuilder(""); - - for (String m : msgParts) { - messageBuffer.append(m); - } - - String msg = messageBuffer.toString(); - - if (!msg.isEmpty() && t != null) { - logger.log(level, msg, t); - } else if (!msg.isEmpty()) { - logger.log(level, msg); - } - } - } - - protected void checkMessageTypes(Class[] supportedMessageTypes) throws AuthException { - Class[] requiredMessageTypes = policyDelegate.getMessageTypes(); - for (Class requiredType : requiredMessageTypes) { - boolean supported = false; - for (Class supportedType : supportedMessageTypes) { - if (requiredType.isAssignableFrom(supportedType)) { - supported = true; - } - } - - if (!supported) { - throw new AuthException("module does not support message type: " + requiredType.getName()); - } - } - } - - /** - * Only called from initialize (while lock is held). - */ - protected abstract void initializeContextMap(); - - protected abstract M createAuthContext(String authContextID, Map properties) throws AuthException; -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigProvider.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigProvider.java deleted file mode 100644 index 9f889d8823f..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigProvider.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.helper; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; -import java.util.HashSet; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.module.ClientAuthModule; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * - * @author Ron Monzillo - */ -public abstract class BaseAuthConfigProvider implements AuthConfigProvider { - - public static final String LAYER_NAME_KEY = "message.layer"; - public static final String ALL_LAYERS = "*"; - public static final String LOGGER_NAME_KEY = "logger.name"; - public static final String AUTH_MODULE_KEY = "auth.module.type"; - public static final String SERVER_AUTH_MODULE = "server.auth.module"; - public static final String CLIENT_AUTH_MODULE = "client.auth.module"; - - private ReentrantReadWriteLock instanceReadWriteLock = new ReentrantReadWriteLock(); - private Lock writeLock = instanceReadWriteLock.writeLock(); - private HashSet selfRegistered = new HashSet<>(); - private EpochCarrier epochCarrier = new EpochCarrier(); - - @Override - public ClientAuthConfig getClientAuthConfig(String layer, String appContext, CallbackHandler callbackHandler) throws AuthException { - return new ClientAuthConfigImpl( - getLoggerName(), - epochCarrier, - getAuthContextHelper(appContext, true), - getMessagePolicyDelegate(appContext), - layer, - appContext, - getClientCallbackHandler(callbackHandler)); - } - - @Override - public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler callbackHandler) throws AuthException { - return new ServerAuthConfigImpl( - getLoggerName(), - epochCarrier, - getAuthContextHelper(appContext, true), - getMessagePolicyDelegate(appContext), - layer, - appContext, - getServerCallbackHandler(callbackHandler)); - } - - public boolean contextsAreEqual(RegistrationContext context1, RegistrationContext context2) { - if (context1 == null || context2 == null) { - return false; - } - - if (context1.isPersistent() != context2.isPersistent()) { - return false; - } - - if (!context1.getAppContext().equals(context2.getAppContext())) { - return false; - } - - if (!context1.getMessageLayer().equals(context2.getMessageLayer())) { - return false; - } - - if (!context1.getDescription().equals(context2.getDescription())) { - return false; - } - - return true; - } - - @Override - public void refresh() { - epochCarrier.increment(); - selfRegister(); - } - - public String getLoggerName() { - return getProperty(LOGGER_NAME_KEY, BaseAuthConfigProvider.class.getName()); - } - - protected final String getProperty(String key, String defaultValue) { - Map properties = getProperties(); - if (properties != null && properties.containsKey(key)) { - return (String) properties.get(key); - } - - return defaultValue; - } - - protected String getLayer() { - return getProperty(LAYER_NAME_KEY, ALL_LAYERS); - } - - protected Class[] getModuleTypes() { - Class[] moduleTypes = new Class[] { ServerAuthModule.class, ClientAuthModule.class }; - - Map properties = getProperties(); - if (properties.containsKey(AUTH_MODULE_KEY)) { - String keyValue = (String) properties.get(AUTH_MODULE_KEY); - - if (SERVER_AUTH_MODULE.equals(keyValue)) { - moduleTypes = new Class[] { ServerAuthModule.class }; - } else if (CLIENT_AUTH_MODULE.equals(keyValue)) { - moduleTypes = new Class[] { ClientAuthModule.class }; - } - } - - return moduleTypes; - } - - protected void selfRegister() { - if (getFactory() != null) { - writeLock.lock(); - try { - RegistrationContext[] contexts = getSelfRegistrationContexts(); - if (!selfRegistered.isEmpty()) { - HashSet toBeUnregistered = new HashSet(); - - // Get the current self-registrations - String[] registrationIDs = getFactory().getRegistrationIDs(this); - - for (String registrationId : registrationIDs) { - if (selfRegistered.contains(registrationId)) { - RegistrationContext context = getFactory().getRegistrationContext(registrationId); - if (context != null && !context.isPersistent()) { - toBeUnregistered.add(registrationId); - } - } - } - - // Remove self-registrations that already exist and should continue - for (String registrationId : toBeUnregistered) { - RegistrationContext context = getFactory().getRegistrationContext(registrationId); - for (int j = 0; j < contexts.length; j++) { - if (contextsAreEqual(contexts[j], context)) { - toBeUnregistered.remove(registrationId); - contexts[j] = null; - } - } - } - - // Unregister those that should not continue to exist - for (String registrationId : toBeUnregistered) { - selfRegistered.remove(registrationId); - getFactory().removeRegistration(registrationId); - } - } - - // Add new self-segistrations - for (RegistrationContext context : contexts) { - if (context != null) { - String id = getFactory().registerConfigProvider(this, context.getMessageLayer(), context.getAppContext(), - context.getDescription()); - selfRegistered.add(id); - } - } - } finally { - writeLock.unlock(); - } - - } - } - - protected CallbackHandler getClientCallbackHandler(CallbackHandler callbackHandler) throws AuthException { - if (callbackHandler == null) { - throw (AuthException) new AuthException("AuthConfigProvider does not support null Client Callbackhandler") - .initCause(new UnsupportedOperationException()); - } - - return callbackHandler; - } - - protected CallbackHandler getServerCallbackHandler(CallbackHandler callbackHandler) throws AuthException { - if (callbackHandler == null) { - throw (AuthException) new AuthException("AuthConfigProvider does not support null Server Callbackhandler") - .initCause(new UnsupportedOperationException()); - } - - return callbackHandler; - } - - public abstract Map getProperties(); - - public abstract AuthConfigFactory getFactory(); - - public abstract RegistrationContext[] getSelfRegistrationContexts(); - - public abstract BaseAuthContextImpl getAuthContextHelper(String appContext, boolean returnNullContexts) throws AuthException; - - public abstract MessagePolicyDelegate getMessagePolicyDelegate(String appContext) throws AuthException; - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthContextImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthContextImpl.java deleted file mode 100644 index 141cfc77a0e..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthContextImpl.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2021] Payara Foundation and/or affiliates - -package com.sun.jaspic.config.helper; - -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * - * @author Ron Monzillo - */ -public abstract class BaseAuthContextImpl { - - private String loggerName; - private boolean returnNullContexts; - - // Include this to force subclasses to call constructor with LoggerName - @SuppressWarnings("unused") - private BaseAuthContextImpl() { - - } - - protected BaseAuthContextImpl(String loggerName, boolean returnNullContexts) { - this.loggerName = loggerName; - this.returnNullContexts = returnNullContexts; - } - - protected boolean isLoggable(Level level) { - Logger logger = Logger.getLogger(loggerName); - return logger.isLoggable(level); - } - - protected void logIfLevel(Level level, Throwable t, String... msgParts) { - Logger logger = Logger.getLogger(loggerName); - if (logger.isLoggable(level)) { - StringBuilder msgB = new StringBuilder(""); - for (String m : msgParts) { - msgB.append(m); - } - String msg = msgB.toString(); - if (!msg.isEmpty() && t != null) { - logger.log(level, msg, t); - } else if (!msg.isEmpty()) { - logger.log(level, msg); - } - } - } - - /** - * - * @param level - * @return - */ - protected Logger getLogger(Level level) { - Logger rvalue = Logger.getLogger(loggerName); - if (rvalue.isLoggable(level)) { - return rvalue; - } - return null; - } - - protected abstract void refresh(); - - public boolean returnsNullContexts() { - return returnNullContexts; - } - - public boolean isProtected(M[] template, String authContextID) throws AuthException { - try { - if (returnNullContexts) { - return hasModules(template, authContextID); - } else { - return true; - } - } catch (AuthException ae) { - throw new RuntimeException(ae); - } - } - - /** - * - * @param - * @param template - * @param authContextID - * @return - * @throws AuthException - */ - public abstract boolean hasModules(M[] template, String authContextID) throws AuthException; - - /** - * - * @param - * @param template - * @param authContextID - * @return - * @throws AuthException - */ - public abstract M[] getModules(M[] template, String authContextID) throws AuthException; - - /** - * - * @param i - * @param properties - * @return - */ - public abstract Map getInitProperties(int i, Map properties); - - /** - * - * @param successValue - * @param i - * @param moduleStatus - * @return - */ - public abstract boolean exitContext(AuthStatus[] successValue, int i, AuthStatus moduleStatus); - - /** - * - * @param successValue - * @param defaultFailStatus - * @param status - * @param position - * @return - */ - public abstract AuthStatus getReturnStatus(AuthStatus[] successValue, AuthStatus defaultFailStatus, AuthStatus[] status, int position); -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ClientAuthConfigImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ClientAuthConfigImpl.java deleted file mode 100644 index 73642fde19e..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ClientAuthConfigImpl.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.helper; - -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; -import static jakarta.security.auth.message.AuthStatus.SEND_FAILURE; -import static jakarta.security.auth.message.AuthStatus.SEND_SUCCESS; -import static jakarta.security.auth.message.AuthStatus.SUCCESS; - -import java.util.HashMap; -import java.util.Map; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.module.ClientAuthModule; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; - -/** - * - * @author Ron Monzillo - */ -public class ClientAuthConfigImpl extends BaseAuthConfigImpl implements ClientAuthConfig { - - private final static AuthStatus[] validateResponseSuccessValues = { SUCCESS }; - private final static AuthStatus[] secureResponseSuccessValues = { SEND_SUCCESS }; - - private Map> contextMap; - private BaseAuthContextImpl authContextHelper; - - protected ClientAuthConfigImpl(String loggerName, EpochCarrier providerEpoch, BaseAuthContextImpl acHelper, - MessagePolicyDelegate mpDelegate, String layer, String appContext, CallbackHandler cbh) throws AuthException { - super(loggerName, providerEpoch, mpDelegate, layer, appContext, cbh); - - this.authContextHelper = acHelper; - } - - @Override - protected void initializeContextMap() { - contextMap = new HashMap<>(); - } - - protected void refreshContextHelper() { - authContextHelper.refresh(); - } - - @Override - @SuppressWarnings("unchecked") - protected M createAuthContext(String authContextID, Map properties) throws AuthException { - - if (!authContextHelper.isProtected(new ClientAuthModule[0], authContextID)) { - return null; - } - - ClientAuthContext context = new ClientAuthContext() { - - ClientAuthModule[] module = init(); - - ClientAuthModule[] init() throws AuthException { - - ClientAuthModule[] clientModules; - try { - clientModules = authContextHelper.getModules(new ClientAuthModule[0], authContextID); - } catch (AuthException ae) { - logIfLevel(SEVERE, ae, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "unable to load client auth modules"); - throw ae; - } - - MessagePolicy requestPolicy = policyDelegate.getRequestPolicy(authContextID, properties); - MessagePolicy responsePolicy = policyDelegate.getResponsePolicy(authContextID, properties); - - boolean noModules = true; - for (int i = 0; i < clientModules.length; i++) { - if (clientModules[i] != null) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "initializing module"); - } - - noModules = false; - checkMessageTypes(clientModules[i].getSupportedMessageTypes()); - - clientModules[i].initialize(requestPolicy, responsePolicy, callbackHandler, - authContextHelper.getInitProperties(i, properties)); - } - } - - if (noModules) { - logIfLevel(WARNING, null, "CLientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "contains no Auth Modules"); - } - - return clientModules; - } - - @Override - public AuthStatus validateResponse(MessageInfo arg0, Subject arg1, Subject arg2) throws AuthException { - AuthStatus[] status = new AuthStatus[module.length]; - - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling vaidateResponse on module"); - } - - status[i] = module[i].validateResponse(arg0, arg1, arg2); - - if (authContextHelper.exitContext(validateResponseSuccessValues, i, status[i])) { - return authContextHelper.getReturnStatus(validateResponseSuccessValues, SEND_FAILURE, status, i); - } - } - - return authContextHelper.getReturnStatus(validateResponseSuccessValues, SEND_FAILURE, status, status.length - 1); - } - - @Override - public AuthStatus secureRequest(MessageInfo arg0, Subject arg1) throws AuthException { - AuthStatus[] status = new AuthStatus[module.length]; - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling secureResponse on module"); - } - - status[i] = module[i].secureRequest(arg0, arg1); - - if (authContextHelper.exitContext(secureResponseSuccessValues, i, status[i])) { - return authContextHelper.getReturnStatus(secureResponseSuccessValues, AuthStatus.SEND_FAILURE, status, i); - } - } - return authContextHelper.getReturnStatus(secureResponseSuccessValues, AuthStatus.SEND_FAILURE, status, status.length - 1); - } - - @Override - public void cleanSubject(MessageInfo arg0, Subject arg1) throws AuthException { - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling cleanSubject on module"); - } - - module[i].cleanSubject(arg0, arg1); - } - } - }; - - return (M) context; - } - - @Override - @SuppressWarnings("unchecked") - public ClientAuthContext getAuthContext(String authContextID, Subject subject, @SuppressWarnings("rawtypes") Map properties) - throws AuthException { - return super.getContext(contextMap, authContextID, subject, properties); - } - - @Override - public boolean isProtected() { - return !authContextHelper.returnsNullContexts() || policyDelegate.isProtected(); - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/EpochCarrier.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/EpochCarrier.java deleted file mode 100644 index 5c2d26c0d32..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/EpochCarrier.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.jaspic.config.helper; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * - * @author Ron Monzillo - */ - -public class EpochCarrier { - - private Lock instanceReadLock; - private Lock instanceWriteLock; - - private long epoch; - - public EpochCarrier() { - ReentrantReadWriteLock instanceReadWriteLock = new ReentrantReadWriteLock(); - instanceReadLock = instanceReadWriteLock.readLock(); - instanceWriteLock = instanceReadWriteLock.writeLock(); - epoch = 0L; - } - - public long increment() { - instanceWriteLock.lock(); - long before; - try { - before = epoch; - epoch = epoch + 1; - } finally { - instanceWriteLock.unlock(); - } - return before; - } - - public long getEpoch() { - instanceReadLock.lock(); - try { - return epoch; - } finally { - instanceReadLock.unlock(); - } - } - - public boolean hasChanged(long reference) { - instanceReadLock.lock(); - try { - return epoch != reference; - } finally { - instanceReadLock.unlock(); - } - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/JASPICLogManager.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/JASPICLogManager.java deleted file mode 100644 index 579a66a9223..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/JASPICLogManager.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.jaspic.config.helper; - -public class JASPICLogManager { - - /** - * PACKAGE_ROOT the prefix for the packages where logger resource bundles reside. - */ - public static final String PACKAGE_ROOT = "com.sun.logging."; - - /** - * RESOURCE_BUNDLE the name of the logging resource bundles. - */ - public static final String RESOURCE_BUNDLE = "LogStrings"; - - public static final String JASPIC_LOGGER = "enterprise.system.jaspic.security"; - - public static final String RES_BUNDLE = PACKAGE_ROOT + JASPIC_LOGGER + "." + RESOURCE_BUNDLE; -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ServerAuthConfigImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ServerAuthConfigImpl.java deleted file mode 100644 index e21a55aeab2..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ServerAuthConfigImpl.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.helper; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; - -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; -import static jakarta.security.auth.message.AuthStatus.SEND_FAILURE; -import static jakarta.security.auth.message.AuthStatus.SEND_SUCCESS; -import static jakarta.security.auth.message.AuthStatus.SUCCESS; - -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * - * @author Ron Monzillo - */ -public class ServerAuthConfigImpl extends BaseAuthConfigImpl implements ServerAuthConfig { - - private final static AuthStatus[] validateRequestSuccessValues = { SUCCESS, SEND_SUCCESS }; - private final static AuthStatus[] secureResponseSuccessValues = { SEND_SUCCESS }; - - private Map> contextMap; - private BaseAuthContextImpl authContextHelperHelper; - - protected ServerAuthConfigImpl(String loggerName, EpochCarrier providerEpoch, BaseAuthContextImpl authContextHelper, - MessagePolicyDelegate policyDelegate, String layer, String appContext, CallbackHandler cbh) throws AuthException { - - super(loggerName, providerEpoch, policyDelegate, layer, appContext, cbh); - - this.authContextHelperHelper = authContextHelper; - this.policyDelegate = policyDelegate; - } - - @Override - protected void initializeContextMap() { - contextMap = new HashMap<>(); - } - - @Override - @SuppressWarnings("unchecked") - protected M createAuthContext(String authContextID, Map properties) throws AuthException { - - if (!authContextHelperHelper.isProtected(new ServerAuthModule[0], authContextID)) { - return null; - } - - // Need to coordinate calls to CallerPrincipalCallback; especially optional - // modules that might reset the result of a required module - return (M) new ServerAuthContext() { - - ServerAuthModule[] module = init(); - - ServerAuthModule[] init() throws AuthException { - ServerAuthModule[] serverAuthModules; - - try { - serverAuthModules = authContextHelperHelper.getModules(new ServerAuthModule[0], authContextID); - } catch (AuthException ae) { - logIfLevel(SEVERE, ae, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "unable to load server auth modules"); - throw ae; - } - - MessagePolicy requestPolicy = policyDelegate.getRequestPolicy(authContextID, properties); - MessagePolicy responsePolicy = policyDelegate.getResponsePolicy(authContextID, properties); - - boolean noModules = true; - for (int i = 0; i < serverAuthModules.length; i++) { - if (serverAuthModules[i] != null) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "initializing module"); - } - noModules = false; - checkMessageTypes(serverAuthModules[i].getSupportedMessageTypes()); - - serverAuthModules[i].initialize( - requestPolicy, responsePolicy, - callbackHandler, authContextHelperHelper.getInitProperties(i, properties)); - } - } - - if (noModules) { - logIfLevel(WARNING, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "contains no Auth Modules"); - } - - return serverAuthModules; - } - - @Override - public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { - AuthStatus[] status = new AuthStatus[module.length]; - - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling vaidateRequest on module"); - } - - status[i] = module[i].validateRequest(messageInfo, clientSubject, serviceSubject); - - if (authContextHelperHelper.exitContext(validateRequestSuccessValues, i, status[i])) { - return authContextHelperHelper.getReturnStatus(validateRequestSuccessValues, SEND_FAILURE, status, i); - } - } - - return authContextHelperHelper.getReturnStatus(validateRequestSuccessValues, SEND_FAILURE, status, status.length - 1); - } - - @Override - public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException { - AuthStatus[] status = new AuthStatus[module.length]; - - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling secureResponse on module"); - } - - status[i] = module[i].secureResponse(messageInfo, serviceSubject); - - if (authContextHelperHelper.exitContext(secureResponseSuccessValues, i, status[i])) { - return authContextHelperHelper.getReturnStatus(secureResponseSuccessValues, SEND_FAILURE, status, i); - } - } - - return authContextHelperHelper.getReturnStatus(secureResponseSuccessValues, SEND_FAILURE, status, status.length - 1); - } - - @Override - public void cleanSubject(MessageInfo arg0, Subject arg1) throws AuthException { - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(Level.FINE)) { - logIfLevel(Level.FINE, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling cleanSubject on module"); - } - - module[i].cleanSubject(arg0, arg1); - } - } - }; - } - - @Override - @SuppressWarnings("unchecked") - public ServerAuthContext getAuthContext(String authContextID, Subject subject, @SuppressWarnings("rawtypes") Map properties) - throws AuthException { - return super.getContext(contextMap, authContextID, subject, properties); - } - - @Override - public boolean isProtected() { - return !authContextHelperHelper.returnsNullContexts() || policyDelegate.isProtected(); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/ExtendedConfigFile.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/ExtendedConfigFile.java deleted file mode 100644 index d3370ce17da..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/ExtendedConfigFile.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.jaas; - -import static com.sun.jaspic.config.helper.JASPICLogManager.JASPIC_LOGGER; -import static com.sun.jaspic.config.helper.JASPICLogManager.RES_BUNDLE; - -import java.lang.reflect.Field; -import java.net.URI; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.HashMap; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.login.AppConfigurationEntry; - -import com.sun.security.auth.login.ConfigFile; - -/** - * - * @author Ron Monzillo - */ -public class ExtendedConfigFile extends ConfigFile { - - private static final Logger logger = Logger.getLogger(JASPIC_LOGGER, RES_BUNDLE); - // may be more than one delegate for a given jaas config file - - public ExtendedConfigFile() { - } - - /** - * - * @param uri - */ - public ExtendedConfigFile(URI uri) { - super(uri); - } - - /** - * The ExtendedConfigFile subclass was created because the Configuration interface does not provide a way to do what - * this method does; i.e. get all the app names from the config. - * - * @param authModuleClass an Array of Class objects or null. When this parameter is not null, the appnames are filtered - * by removing all names that are not associated via an AppConfigurationEntry with at least one LoginModule that - * implements an authModuleClass. - * @return String[] containing all the AppNames appearing in the config file. - * @throws SecurityException - */ - public String[] getAppNames(final Class[] authModuleClass) { - - final Set nameSet; - try { - nameSet = (Set) AccessController.doPrivileged(new PrivilegedExceptionAction() { - - @Override - public Object run() throws Exception { - HashMap map; - Field field = ConfigFile.class.getDeclaredField("configuration"); - field.setAccessible(true); - map = (HashMap) field.get(ExtendedConfigFile.this); - return map.keySet(); - } - }); - - } catch (PrivilegedActionException pae) { - throw new SecurityException(pae.getCause()); - } - - // remove any modules that don't implement specified interface - if (authModuleClass != null) { - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - - @Override - public Object run() throws Exception { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - String[] names = nameSet.toArray(new String[nameSet.size()]); - for (String id : names) { - boolean hasAuthModule = false; - AppConfigurationEntry[] entry = getAppConfigurationEntry(id); - for (int i = 0; i < entry.length && !hasAuthModule; i++) { - String clazz = entry[i].getLoginModuleName(); - try { - Class c = Class.forName(clazz, true, loader); - for (Class required : authModuleClass) { - if (required.isAssignableFrom(c)) { - hasAuthModule = true; - break; - } - } - } catch (Throwable t) { - String msg = "skipping unloadable class: " + clazz + " of entry: " + id; - logger.log(Level.WARNING, msg); - } - } - if (!hasAuthModule) { - nameSet.remove(id); - } - } - return null; - } - }); - } catch (java.security.PrivilegedActionException pae) { - throw new SecurityException(pae.getCause()); - } - - } - return nameSet.toArray(new String[nameSet.size()]); - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java deleted file mode 100644 index 3b912b34a44..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.jaspic.config.jaas; - -import com.sun.jaspic.config.helper.BaseAuthContextImpl; -import com.sun.jaspic.config.helper.BaseAuthConfigProvider; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Locale; -import java.util.Map; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; - -/** - * - * @author Ron Monzillo - */ -public abstract class JAASAuthConfigProvider extends BaseAuthConfigProvider { - - private static final String CONFIG_FILE_NAME_KEY = "config.file.name"; - private static final String DEFAULT_JAAS_APP_NAME = "other"; - private static final String ALL_APPS = "*"; - - private String configFileName; - private ExtendedConfigFile jaasConfig; - - private Map properties; - private AuthConfigFactory factory; - - public JAASAuthConfigProvider(Map properties, AuthConfigFactory factory) { - this.properties = properties; - this.factory = factory; - - configFileName = getProperty(CONFIG_FILE_NAME_KEY, null); - - if (configFileName == null) { - jaasConfig = new ExtendedConfigFile(); - } else { - try { - URI uri = new URI(configFileName); - jaasConfig = new ExtendedConfigFile(uri); - } catch (URISyntaxException use) { - IllegalArgumentException iae = new IllegalArgumentException(use); - throw iae; - } - } - selfRegister(); - } - - @Override - public Map getProperties() { - return properties; - } - - @Override - public AuthConfigFactory getFactory() { - return factory; - } - - private RegistrationContext getRegistrationContext(String id) { - - final String layer = getLayer(); - final String appContext; - if (id.toLowerCase(Locale.getDefault()).equals(DEFAULT_JAAS_APP_NAME)) { - appContext = ALL_APPS; - } else { - appContext = id; - } - - return new RegistrationContext() { - - final String description = "JAAS AuthConfig: " + appContext; - - @Override - public String getMessageLayer() { - return layer; - } - - @Override - public String getAppContext() { - return appContext; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public boolean isPersistent() { - return false; - } - }; - } - - @Override - public AuthConfigFactory.RegistrationContext[] getSelfRegistrationContexts() { - final String[] appContexts = jaasConfig.getAppNames(getModuleTypes()); - RegistrationContext[] rvalue = new RegistrationContext[appContexts.length]; - for (int i = 0; i < appContexts.length; i++) { - rvalue[i] = getRegistrationContext(appContexts[i]); - } - return rvalue; - } - - @Override - public BaseAuthContextImpl getAuthContextHelper(String appContext, boolean returnNullContexts) throws AuthException { - return new JAASAuthContextHelper(getLoggerName(), returnNullContexts, jaasConfig, properties, appContext); - } - - @Override - public void refresh() { - jaasConfig.refresh(); - super.refresh(); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthContextHelper.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthContextHelper.java deleted file mode 100644 index aa05064363e..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthContextHelper.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.jaas; - -import com.sun.jaspic.config.helper.BaseAuthContextImpl; - -import static java.security.AccessController.doPrivileged; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.INFO; -import static javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL; -import static javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; -import static javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.REQUISITE; -import static javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.logging.Level; -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; - -/** - * - * @author Ron Monzillo - */ -public class JAASAuthContextHelper extends BaseAuthContextImpl { - - private static final String DEFAULT_ENTRY_NAME = "other"; - private static final Class[] PARAMS = {}; - private static final Object[] ARGS = {}; - - // may be more than one delegate for a given jaas config file - private ReentrantReadWriteLock instanceReadWriteLock = new ReentrantReadWriteLock(); - private Lock instanceWriteLock = instanceReadWriteLock.writeLock(); - private ExtendedConfigFile jaasConfig; - private final String appContext; - private AppConfigurationEntry[] entry; - private Constructor[] constructors; - - public JAASAuthContextHelper(String loggerName, boolean returnNullContexts, ExtendedConfigFile jaasConfig, Map properties, - String appContext) throws AuthException { - super(loggerName, returnNullContexts); - this.jaasConfig = jaasConfig; - this.appContext = appContext; - - initialize(); - } - - private void initialize() { - boolean found = false; - boolean foundDefault = false; - instanceWriteLock.lock(); - try { - entry = jaasConfig.getAppConfigurationEntry(appContext); - if (entry == null) { - - // NEED TO MAKE SURE THIS LOOKUP only occurs when registered for * - entry = jaasConfig.getAppConfigurationEntry(DEFAULT_ENTRY_NAME); - if (entry == null) { - entry = new AppConfigurationEntry[0]; - } else { - foundDefault = true; - } - } else { - found = true; - } - constructors = null; - } finally { - instanceWriteLock.unlock(); - } - - if (!found) { - if (!foundDefault) { - logIfLevel(INFO, null, "JAASAuthConfig no entries matched appContext (", appContext, ") or (", DEFAULT_ENTRY_NAME, - ")"); - } else { - logIfLevel(INFO, null, "JAASAuthConfig appContext (", appContext, ") matched (", DEFAULT_ENTRY_NAME, ")"); - } - } - } - - private void loadConstructors(M[] template, String authContextID) throws AuthException { - if (constructors == null) { - try { - final Class moduleType = template.getClass().getComponentType(); - constructors = (Constructor[]) AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - - @Override - public Object run() - throws java.lang.ClassNotFoundException, java.lang.NoSuchMethodException, java.lang.InstantiationException, - java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException { - Constructor[] ctor = new Constructor[entry.length]; - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - for (int i = 0; i < entry.length; i++) { - ctor[i] = null; - String clazz = entry[i].getLoginModuleName(); - try { - Class c = Class.forName(clazz, true, loader); - if (moduleType.isAssignableFrom(c)) { - ctor[i] = c.getConstructor(PARAMS); - } - - } catch (Throwable t) { - logIfLevel(Level.WARNING, null, "skipping unloadable class: ", clazz, " of appCOntext: ", appContext); - } - } - return ctor; - } - }); - } catch (java.security.PrivilegedActionException pae) { - AuthException ae = new AuthException(); - ae.initCause(pae.getCause()); - throw ae; - } - } - } - - @Override - protected final void refresh() { - jaasConfig.refresh(); - initialize(); - } - - /** - * This implementation does not depend on authContextID - * - * @param - * @param template - * @param authContextID (ignored by this context system) - * @return - * @throws AuthException - */ - @Override - public boolean hasModules(M[] template, String authContextID) throws AuthException { - loadConstructors(template, authContextID); - - for (Constructor constructor : constructors) { - if (constructor != null) { - return true; - } - } - - return false; - } - - /** - * this implementation does not depend on authContextID - * - * @param - * @param template - * @param authContextID (ignored by this context system) - * @return - * @throws AuthException - */ - @Override - public M[] getModules(M[] template, String authContextID) throws AuthException { - loadConstructors(template, authContextID); - ArrayList list = new ArrayList(); - - for (int i = 0; i < constructors.length; i++) { - if (constructors[i] == null) { - list.add(i, null); - } else { - final int j = i; - try { - list.add(j, doPrivileged(new PrivilegedExceptionAction() { - - @Override - @SuppressWarnings("unchecked") - public M run() - throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - return (M) constructors[j].newInstance(ARGS); - } - })); - } catch (PrivilegedActionException pae) { - throw (AuthException) new AuthException().initCause(pae.getCause()); - } - } - } - - return list.toArray(template); - } - - @Override - public Map getInitProperties(int i, Map properties) { - Map initProperties = new HashMap<>(); - - if (entry[i] != null) { - if (properties != null && !properties.isEmpty()) { - initProperties.putAll(properties); - } - - @SuppressWarnings("unchecked") - Map options = (Map) entry[i].getOptions(); - if (options != null && !options.isEmpty()) { - initProperties.putAll(options); - } - } - - return initProperties; - } - - @Override - public boolean exitContext(AuthStatus[] successValue, int i, AuthStatus moduleStatus) { - if (entry[i] != null && constructors[i] != null) { - LoginModuleControlFlag flag = entry[i].getControlFlag(); - - if (REQUISITE.equals(flag)) { - for (AuthStatus authStatus : successValue) { - if (moduleStatus == authStatus) { - return false; - } - } - - return true; - } else if (SUFFICIENT.equals(flag)) { - for (AuthStatus s : successValue) { - if (moduleStatus == s) { - return true; - } - } - - return false; - } - } - - return false; - } - - @Override - public AuthStatus getReturnStatus(AuthStatus[] successValue, AuthStatus defaultFailStatus, AuthStatus[] status, int position) { - AuthStatus returnStatus = null; - - for (int i = 0; i <= position; i++) { - if (entry[i] != null && constructors[i] != null) { - - LoginModuleControlFlag flag = entry[i].getControlFlag(); - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "getReturnStatus - flag: ", flag.toString()); - } - - if (flag == REQUIRED || flag == REQUISITE) { - boolean isSuccessValue = false; - for (AuthStatus authStatus : successValue) { - if (status[i] == authStatus) { - isSuccessValue = true; - } - } - - if (isSuccessValue) { - if (returnStatus == null) { - returnStatus = status[i]; - } - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ReturnStatus - REQUIRED or REQUISITE failure: ", status[i].toString()); - } - return status[i]; - } else if (flag == SUFFICIENT) { - if (exitContext(successValue, i, status[i])) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ReturnStatus - Sufficient success: ", status[i].toString()); - } - - return status[i]; - } - - } else if (flag == OPTIONAL) { - if (returnStatus == null) { - for (AuthStatus authStatus : successValue) { - if (status[i] == authStatus) { - returnStatus = status[i]; - } - } - } - } - } - } - - if (returnStatus != null) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ReturnStatus - result: ", returnStatus.toString()); - } - - return returnStatus; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ReturnStatus - Default faiure status: ", defaultFailStatus.toString()); - } - - return defaultFailStatus; - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/HttpMessageInfo.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/HttpMessageInfo.java deleted file mode 100644 index 02006a40788..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/HttpMessageInfo.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDLGPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.servlet; - -import java.util.HashMap; -import java.util.Map; - -import jakarta.security.auth.message.MessageInfo; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -public class HttpMessageInfo implements MessageInfo { - - private HttpServletRequest request = null; - private HttpServletResponse response = null; - private Map map = new HashMap<>(); - - public HttpMessageInfo(HttpServletRequest request, HttpServletResponse response) { - this.request = request; - this.response = response; - } - - @Override - public HttpServletRequest getRequestMessage() { - return request; - } - - @Override - public HttpServletResponse getResponseMessage() { - return response; - } - - @Override - public void setRequestMessage(Object request) { - this.request = (HttpServletRequest) request; - } - - @Override - public void setResponseMessage(Object response) { - this.response = (HttpServletResponse) response; - } - - @Override - public Map getMap() { - return map; - } -} \ No newline at end of file diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/JAASServletAuthConfigProvider.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/JAASServletAuthConfigProvider.java deleted file mode 100755 index 19b96ba9593..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/JAASServletAuthConfigProvider.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.servlet; - -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_SENDER; - -import java.util.Map; - -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.MessagePolicy.TargetPolicy; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.module.ServerAuthModule; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; -import com.sun.jaspic.config.helper.BaseAuthContextImpl; -import com.sun.jaspic.config.jaas.JAASAuthConfigProvider; - -/** - * - * @author Ron Monzillo - */ -public class JAASServletAuthConfigProvider extends JAASAuthConfigProvider { - - private static final String HTTP_SERVLET_LAYER = "HttpServlet"; - private static final String MANDATORY_KEY = "jakarta.security.auth.message.MessagePolicy.isMandatory"; - private static final String MANDATORY_AUTH_CONTEXT_ID = "mandatory"; - private static final String OPTIONAL_AUTH_CONTEXT_ID = "optional"; - - private static final Class[] moduleTypes = new Class[] { ServerAuthModule.class }; - private static final Class[] messageTypes = new Class[] { HttpServletRequest.class, HttpServletResponse.class }; - - private static final MessagePolicy mandatoryPolicy = new MessagePolicy( - new TargetPolicy[] { - new TargetPolicy( - null, - () -> AUTHENTICATE_SENDER) - }, - true); - - private static final MessagePolicy optionalPolicy = new MessagePolicy( - new TargetPolicy[] { - new TargetPolicy( - null, - () -> AUTHENTICATE_SENDER) - }, - false); - - public JAASServletAuthConfigProvider(Map properties, AuthConfigFactory factory) { - super(properties, factory); - } - - @Override - public MessagePolicyDelegate getMessagePolicyDelegate(String appContext) throws AuthException { - - return new MessagePolicyDelegate() { - - @Override - public MessagePolicy getRequestPolicy(String authContextID, Map properties) { - return MANDATORY_AUTH_CONTEXT_ID.equals(authContextID) ? mandatoryPolicy : optionalPolicy; - } - - @Override - public MessagePolicy getResponsePolicy(String authContextID, Map properties) { - return null; - } - - @Override - public Class[] getMessageTypes() { - return messageTypes; - } - - @Override - public String getAuthContextID(MessageInfo messageInfo) { - return messageInfo.getMap().containsKey(MANDATORY_KEY) ? MANDATORY_AUTH_CONTEXT_ID : OPTIONAL_AUTH_CONTEXT_ID; - } - - @Override - public boolean isProtected() { - return true; - } - - }; - } - - @Override - protected Class[] getModuleTypes() { - return moduleTypes; - } - - @Override - protected String getLayer() { - return HTTP_SERVLET_LAYER; - } - - @Override - public BaseAuthContextImpl getAuthContextHelper(String appContext, boolean returnNullContexts) throws AuthException { - // overrides returnNullContexts to false (as required by Servlet Profile) - return super.getAuthContextHelper(appContext, false); - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/resources/com/sun/logging/enterprise/system/jaspic/security/LogStrings.properties b/appserver/security/jaspic-provider-framework/src/main/resources/com/sun/logging/enterprise/system/jaspic/security/LogStrings.properties deleted file mode 100644 index c6d9307ab72..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/resources/com/sun/logging/enterprise/system/jaspic/security/LogStrings.properties +++ /dev/null @@ -1,49 +0,0 @@ -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. -# -# Copyright (c) 2004-2011 Oracle and/or its affiliates. All rights reserved. -# -# The contents of this file are subject to the terms of either the GNU -# General Public License Version 2 only ("GPL") or the Common Development -# and Distribution License("CDDL") (collectively, the "License"). You -# may not use this file except in compliance with the License. You can -# obtain a copy of the License at -# https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html -# or packager/legal/LICENSE.txt. See the License for the specific -# language governing permissions and limitations under the License. -# -# When distributing the software, include this License Header Notice in each -# file and include the License file at packager/legal/LICENSE.txt. -# -# GPL Classpath Exception: -# Oracle designates this particular file as subject to the "Classpath" -# exception as provided by Oracle in the GPL Version 2 section of the License -# file that accompanied this code. -# -# Modifications: -# If applicable, add the following below the License Header, with the fields -# enclosed by brackets [] replaced by your own identifying information: -# "Portions Copyright [year] [name of copyright owner]" -# -# Contributor(s): -# If you wish your version of this file to be governed by only the CDDL or -# only the GPL Version 2, indicate your decision by adding "[Contributor] -# elects to include this software in this distribution under the [CDDL or GPL -# Version 2] license." If you don't indicate a single choice of license, a -# recipient has the option to distribute your version of this file under -# either the CDDL, the GPL Version 2 or to extend the choice of license to -# its licensees as provided above. However, if you add GPL Version 2 code -# and therefore, elected the GPL Version 2 license, then the option applies -# only if the new code is made subject to such option by the copyright -# holder. -# -# Portions Copyright [2019] [Payara Foundation and/or its affiliates] - -# JASPIC: start at 1200 : security/core has some of these as duplicates need to cleanup -jaspic.factory_unable_to_load_provider=SEC1203: GFAuthConfigFactory unable to load Provider: {0}, exception : {1}, cause : {2}. -jaspic.factory_auth_config_loader_failure=SEC1204: GFAuthConfigFactory loader failure -jaspic.factory_cannot_write_file=SEC1205: Cannot write to file {0}. Updated provider list will not be persisted. -jaspic.factory_could_not_persist=SEC1206: Could not persist updated provider list due to {0}. Will use default providers when reloaded. -jaspic.factory_could_not_read=SEC1207: Could not read auth configuration file due to {0} Will use default providers. -jaspic.factory_file_not_found=SEC1208: Configuration file does not exist at {0}. Will use default providers. -jaspic.factory_creating_conf_file=SEC1210: Creating JASPIC Configuration file {0}. diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java deleted file mode 100644 index 253eb82236e..00000000000 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java +++ /dev/null @@ -1,1013 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] -package test.com.sun.jaspic.config; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.Future; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.ExecutorService; -import java.util.ArrayList; -import java.util.List; -import com.sun.jaspic.config.factory.EntryInfo; -import java.security.Security; -import org.junit.After; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.StringTokenizer; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.config.RegistrationListener; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; - -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Ron Monzillo - */ -public class FactoryTest { - - /** switch definition of default test factory to test native factory - * will also need to configure proper dependencies - */ - private static final String DEFAULT_TEST_FACTORY_CLASS_NAME = AuthConfigFileFactory.class.getName(); - private static String testFactoryClassName = DEFAULT_TEST_FACTORY_CLASS_NAME; - public static final String DEFAULT_FACTORY_SECURITY_PROPERTY = - "authconfigprovider.factory"; - public static final String USER_DIR_PROPERTY = "user.dir"; - static final String THREAD_COUNT_KEY = "test.thread.count"; - static final String MAX_JOIN_SECONDS_KEY = "test.max.join.seconds"; - static final String TEST_FACTORY_CLASS_NAME_KEY = "test.factory.class.name"; - static final int DEFAULT_THREAD_COUNT = 32; - static final int DEFAULT_MAX_JOIN_SECONDS = 600; - static final Logger logger = Logger.getLogger(FactoryTest.class.getName()); - private static String defaultFactoryClassName; - private static AuthConfigFactory testFactory; - static HashMap options = new HashMap(); - private static ExecutorService threadPool; - static int consumerCount; - static int activeConsumers; - static Random random = new Random(); - static final String[] layers = new String[4]; - static final String[] contexts = new String[16]; - - static { - layers[0] = null; - for (int i = 1; i < layers.length; i++) { - layers[i] = "layer" + Integer.toString(i); - } - contexts[0] = null; - for (int i = 1; i < contexts.length; i++) { - contexts[i] = "context" + Integer.toString(i); - } - } - static AuthConfigProvider[] providers = new AuthConfigProvider[4]; - - public FactoryTest() { - } - - public static String getStringOption(String key, String defaultValue) { - String s = options == null ? null : (String) options.get(key); - if (s == null) { - return defaultValue; - } - return s; - } - - public static int getIntOption(String key, int defaultValue) { - String s = options == null ? null : (String) options.get(key); - if (s == null) { - return defaultValue; - } - return Integer.valueOf(s).intValue(); - } - - public static boolean getbooleanOption(String key, boolean defaultValue) { - String s = options == null ? null : (String) options.get(key); - if (s == null) { - return defaultValue; - } - return Boolean.valueOf(s).booleanValue(); - } - - public static String[] splitStringOption(String s) { - if (s == null) { - return new String[0]; - } - return s.split(",|:| |;"); - } - - static Map getProviderProperties() { - return new HashMap(); - } - - static AuthConfigFactory loadFactory(final String className) { - AuthConfigFactory factory = null; - try { - factory = (AuthConfigFactory) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - - @Override - public Object run() - throws ClassNotFoundException, - InstantiationException, - IllegalAccessException { - ClassLoader loader = - Thread.currentThread(). - getContextClassLoader(); - - Class clazz = Class.forName(className, true, loader); - return clazz.newInstance(); - } - }); - } catch (java.security.PrivilegedActionException pae) { - throw new SecurityException(pae.getException()); - } finally { - assertNotNull("loadFactory returned null", factory); - } - return factory; - } - - public static void main(String[] args) { - - for (String s : args) { - StringTokenizer tokenizer = new StringTokenizer(s, "="); - if (tokenizer.countTokens() == 2) { - String key = tokenizer.nextToken(); - String value = tokenizer.nextToken(); - System.out.println("key: " + key + " value: " + value); - options.put(key, value); - } - } - - testFactoryClassName = getStringOption(TEST_FACTORY_CLASS_NAME_KEY, - DEFAULT_TEST_FACTORY_CLASS_NAME); - - new FactoryTest().beforeTest(); - new FactoryTest().testSetFactory(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testOverrideForDefaultEntries(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testRemoveRegistration(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testListeners(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().stressFactory( - getIntOption(THREAD_COUNT_KEY, DEFAULT_THREAD_COUNT), - getIntOption(MAX_JOIN_SECONDS_KEY, DEFAULT_MAX_JOIN_SECONDS)); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testRegistrationWithNonStringProperty(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testRegistrationWithNonStringPropertyAndPreviousRegistration(); - new FactoryTest().afterTest(); - } - - @Before - public void beforeTest() { - try { - defaultFactoryClassName = Security.getProperty(DEFAULT_FACTORY_SECURITY_PROPERTY); - logger.log(Level.INFO, "\n\tSecurity Manager is {0}\n\t{1} is {2}\n\t{3} is {4}\n\t{5} is {6}\n", - new Object[]{ - (System.getSecurityManager() == null ? "OFF" : "ON"), - DEFAULT_FACTORY_SECURITY_PROPERTY, defaultFactoryClassName, - "Test Factory Class Name", testFactoryClassName, - USER_DIR_PROPERTY, System.getProperty(USER_DIR_PROPERTY)}); - testFactory = loadFactory(testFactoryClassName); - AuthConfigFactory.setFactory(testFactory); - } catch (Throwable t) { - logger.log(Level.SEVERE, "Exception in test setup", t); - fail("exception in test setup: " + t.toString()); - } - assertNotNull("at exit of beforeTest getFactory returns null",AuthConfigFactory.getFactory()); - } - - @After - public void afterTest() { - AuthConfigFactory.setFactory(null); - } - - @Test - public void testSetFactory() { - logger.info("BEGIN Set FACTORY TEST"); - AuthConfigFactory.setFactory(null); - assertTrue(defaultFactoryClassName == null - ? AuthConfigFactory.getFactory() == null - : defaultFactoryClassName.equals(AuthConfigFactory.getFactory().getClass().getName())); - if (defaultFactoryClassName != null) { - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, testFactoryClassName); - AuthConfigFactory.setFactory(null); - assertTrue(testFactoryClassName.equals(AuthConfigFactory.getFactory().getClass().getName())); - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, defaultFactoryClassName); - AuthConfigFactory.setFactory(null); - assertTrue(defaultFactoryClassName.equals(AuthConfigFactory.getFactory().getClass().getName())); - } - AuthConfigFactory.setFactory(testFactory); - assertTrue(testFactoryClassName.equals(AuthConfigFactory.getFactory().getClass().getName())); - } - - @Test - public void testRegistrationWithNonStringProperty() { - logger.info("BEGIN Registration with NonString Property FACTORY TEST"); - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, testFactoryClassName); - String className = _AuthConfigProvider.class.getName(); - HashMap properties = new HashMap(); - ArrayList list = new ArrayList(); - list.add("larry was here"); - properties.put("test", list); - String layer = "HttpServlet"; - String appContext = "context"; - String description = null; - String regId = null; - try { - regId = AuthConfigFactory.getFactory().registerConfigProvider(className, properties, layer, appContext, description); - } catch (IllegalArgumentException iae) { - assertNull("Failed Registration Should Have Resulted in a NULL RegistrationID returned but did not.", regId); - } - AuthConfigProvider acp = null; - acp = AuthConfigFactory.getFactory().getConfigProvider(layer, appContext, null); - assertNull("Registration Should Have Failed and Therefore No ACP Should Have been Found.", acp); - } - - @Test - public void testRegistrationWithNonStringPropertyAndPreviousRegistration() { - logger.info("BEGIN Registration with NonString Property and Previous Registration FACTORY TEST"); - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, testFactoryClassName); - - // first register a valid acp configuration - String className = _AuthConfigProvider.class.getName(); - HashMap properties = null; - String layer = "HttpServlet"; - String appContext = "context"; - String description = null; - String regId = null; - regId = AuthConfigFactory.getFactory().registerConfigProvider(className, properties, layer, appContext, description); - assertNotNull("Registration Should Have Succeeded returning a nonNULL RegistrationID but did not.", regId); - AuthConfigProvider previousAcp = null; - previousAcp = AuthConfigFactory.getFactory().getConfigProvider(layer, appContext, null); - assertNotNull("Registration Should Have Succeeded returning a nonNULL ACP but did not.", previousAcp); - String previousRegId = regId; - - // now for an invalid configuration - properties = new HashMap(); - ArrayList list = new ArrayList(); - list.add("larry was here"); - properties.put("test", list); - layer = "HttpServlet"; - appContext = "context"; - description = null; - regId = null; - try { - regId = AuthConfigFactory.getFactory().registerConfigProvider(className, properties, layer, appContext, description); - } catch (IllegalArgumentException iae) { - assertNull("Failed Registration Should Have Resulted in a NULL RegistrationID returned but did not.", regId); - } - AuthConfigProvider acp = null; - acp = AuthConfigFactory.getFactory().getConfigProvider(layer, appContext, null); - assertTrue("Registration Should Have Failed for Invalid Config and Therefore returned the Previously Registered ACP", previousAcp == acp); - - assertTrue("Failed to remove the previously registered provider.", AuthConfigFactory.getFactory().removeRegistration(previousRegId)); - } - - @Test - public void testOverrideForDefaultEntries() { - logger.info("BEGIN overrideGetDefaultEntries TEST"); - AuthConfigFactory f = new _ExtendsBaseAuthConfigFactory(); - f = new _Extends_ExtendsAuthConfigFactory(); - } - - static class _ExtendsBaseAuthConfigFactory extends BaseAuthConfigFactory { - - // regStore MUST hide regStore of bade class - private static RegStoreFileParser regStore = null; - - /** - * To specialize the defaultEntries passed to the RegStoreFileParser, - * construct EntryInfo objects within this constructor. - * THE EentyInfo OBJECTS MUST ONLY BE CONSTRCTED USING THE FOLLOWING - * CONSTRUCTOR: EntryInfo(String className, Map properties) - * NO Entries are passed by this test, because to do so, the parent - * test class would need to import EntryInfo (which it can't). - */ - public _ExtendsBaseAuthConfigFactory() { - readLock.lock(); - try { - if (regStore != null) { - return; - } - } finally { - readLock.unlock(); - } - String userDir = System.getProperty("user.dir"); - writeLock.lock(); - try { - if (regStore == null) { - EntryInfo e = new EntryInfo(_AuthConfigProvider.class.getName(),null); - List defaultEntries = new ArrayList(); - defaultEntries.add(e); - regStore = new RegStoreFileParser(userDir, - BaseAuthConfigFactory.CONF_FILE_NAME,defaultEntries); - _loadFactory(); - } - } finally { - writeLock.unlock(); - } - RegStoreFileParser rS = getRegStore(); - assertTrue(rS == _ExtendsBaseAuthConfigFactory.regStore); - } - - @Override - protected RegStoreFileParser getRegStore() { - readLock.lock(); - try { - return regStore; - } finally { - readLock.unlock(); - } - } - } - - static class _Extends_ExtendsAuthConfigFactory extends _ExtendsBaseAuthConfigFactory { - - // regStore MUST hide regStore of base class - private static RegStoreFileParser regStore = null; - - /** - * To specialize the defaultEntries passed to the RegStoreFileParser, - * construct EntryInfo objects within this constructor. - * THE EentyInfo OBJECTS MUST ONLY BE CONSTRCTED USING THE FOLLOWING - * CONSTRUCTOR: EntryInfo(String className, Map properties) - * NO Entries are passed by this test, because to do so, the parent - * test class would need to import EntryInfo (which it can't). - */ - public _Extends_ExtendsAuthConfigFactory() { - readLock.lock(); - try { - if (regStore != null) { - return; - } - } finally { - readLock.unlock(); - } - String userDir = System.getProperty("user.dir"); - writeLock.lock(); - try { - if (regStore == null) { - EntryInfo e = new EntryInfo(_AuthConfigProvider.class.getName(),null); - List defaultEntries = new ArrayList(); - defaultEntries.add(e); - regStore = new RegStoreFileParser(userDir, - BaseAuthConfigFactory.CONF_FILE_NAME,defaultEntries); - _loadFactory(); - } - } finally { - writeLock.unlock(); - } - RegStoreFileParser rS = getRegStore(); - assertTrue(rS == _Extends_ExtendsAuthConfigFactory.regStore); - } - - @Override - protected RegStoreFileParser getRegStore() { - readLock.lock(); - try { - return regStore; - } finally { - readLock.unlock(); - } - } - } - - @Test - public void testRemoveRegistration() { - logger.info("BEGIN Remove Registration TEST"); - final AuthConfigFactory f = AuthConfigFactory.getFactory(); - f.refresh(); - // does self registration - AuthConfigProvider p = new _AuthConfigProvider(new HashMap(), f); - RegistrationContext rc; - String[] rids = f.getRegistrationIDs(p); - boolean removed; - assertTrue("provider did not self register", rids != null && rids.length > 0); - for (String i : rids) { - rc = f.getRegistrationContext(i); - removed = f.removeRegistration(i); - assertTrue("expected true from removeRegistration - rid: " + i, - rc != null && removed); - } - for (String i : rids) { - rc = f.getRegistrationContext(i); - removed = f.removeRegistration(i); - assertTrue("expected false from removeRegistration - rid: " + i, - rc == null && !removed); - } - - //testing registration and removal of null provider; - String rid = f.registerConfigProvider(null, null, null, "null registration"); - rc = f.getRegistrationContext(rid); - removed = f.removeRegistration(rid); - assertTrue("testing null provider - expected true from removeRegistration - rid: " + rid, - rc != null && removed); - //testing for interferece with null provider - rc = f.getRegistrationContext(rid); - removed = f.removeRegistration(rid); - assertTrue("testing null provider - expected false from removeRegistration - rid: " + rid, - rc == null && !removed); - rid = f.registerConfigProvider(null, null, null, "null registration"); - //temporary to force call to decomposeRegId in getEffectedListeners - p = f.getConfigProvider(null, null, new _Listener(null, null, false)); - rc = f.getRegistrationContext(rid); - assertTrue("testing null provider - getRegistrationContext - rid: " + rid, - rid != null); - String badRid = "someInvalidId"; - rc = f.getRegistrationContext(badRid); - removed = f.removeRegistration(badRid); - assertTrue("expected false from removeRegistration - rid: " + badRid, - rc == null && !removed); - rc = f.getRegistrationContext(rid); - removed = f.removeRegistration(rid); - assertTrue("testing null provider - expected true from removeRegistration - rid: " + rid, - rc != null && removed); - } - - @Test - public void testListeners() { - logger.info("BEGIN Listener TEST"); - final AuthConfigFactory f = AuthConfigFactory.getFactory(); - final AuthConfigProvider p = new _AuthConfigProvider(new HashMap(), null); - - String layer[] = {null, "11", "l2"}; - String context[] = {null, "c1", "c2"}; - String rid[] = new String[(layer.length - 1) * (context.length - 1)]; - String ridLayer[] = new String[rid.length]; - String ridContext[] = new String[rid.length]; - - int z = 0; - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 2; j++) { - ridLayer[z] = layer[i]; - ridContext[z] = context[j]; - rid[z] = f.registerConfigProvider(p, ridLayer[z], ridContext[z], - ridLayer[z] + ridContext[z]); - z++; - } - } - - _Listener listener[] = new _Listener[rid.length]; - - z = 0; - for (int i = 1; i < layer.length; i++) { - for (int j = 1; j < context.length; j++) { - listener[z] = new _Listener(layer[i], context[j], true); - f.getConfigProvider(layer[i], context[j], listener[z]); - z++; - } - } - - for (int i = 0; i < rid.length; i++) { - f.removeRegistration(rid[i]); - } - - - f.detachListener(listener[0], null, null); - f.detachListener(listener[1], listener[1].getLayer(), null); - f.detachListener(listener[2], null, listener[2].getAppContext()); - f.detachListener(listener[3], listener[3].getLayer(), listener[3].getAppContext()); - - //should not find any left to detach - for (int i = 0; i < listener.length; i++) { - f.detachListener(listener[i], listener[i].getLayer(), listener[i].getAppContext()); - } - - for (int i = 0; i < rid.length; i++) { - rid[i] = f.registerConfigProvider(p, ridLayer[i], ridContext[i], ridLayer[i] + ridContext[i]); - } - - z = 0; - for (int i = 1; i < layer.length; i++) { - for (int j = 1; j < context.length; j++) { - listener[z] = new _Listener(layer[i], context[j], false); - f.getConfigProvider(layer[i], context[j], listener[z]); - z++; - } - } - for (int i = 0; i < rid.length; i++) { - for (int j = 0; j < listener.length; j++) { - if (listener[j].notified) { - assertTrue("Test Setup Failure - listener could not be registered", - listener[j].register()); - } - } - f.removeRegistration(rid[i]); - - for (int j = 0; j < listener.length; j++) { - listener[j].check(ridLayer[i], ridContext[i]); - } - } - - //repeat with null provider registrations - for (int i = 0; i < rid.length; i++) { - rid[i] = f.registerConfigProvider(null, ridLayer[i], ridContext[i], ridLayer[i] + ridContext[i]); - } - - z = 0; - for (int i = 1; i < layer.length; i++) { - for (int j = 1; j < context.length; j++) { - listener[z] = new _Listener(layer[i], context[j], false); - f.getConfigProvider(layer[i], context[j], listener[z]); - z++; - } - } - for (int i = 0; i < rid.length; i++) { - for (int j = 0; j < listener.length; j++) { - if (listener[j].notified) { - assertTrue("Test Setup Failure - listener could not be registered", - listener[j].register()); - } - } - f.removeRegistration(rid[i]); - - for (int j = 0; j < listener.length; j++) { - listener[j].check(ridLayer[i], ridContext[i]); - } - } - } - - static class _Listener implements RegistrationListener { - - String layer; - String appContext; - boolean reRegister; - boolean notified; - - _Listener(String layer, String appContext, boolean reRegister) { - this.layer = layer; - this.appContext = appContext; - this.reRegister = reRegister; - this.notified = false; - } - - String getLayer() { - return layer; - } - - String getAppContext() { - return appContext; - } - - synchronized boolean register() { - boolean rvalue = false; - if (notified) { - notified = false; - rvalue = true; - AuthConfigFactory.getFactory().getConfigProvider(layer, appContext, this); - } - return rvalue; - } - - synchronized boolean notified() { - return notified; - } - - void check(String l, String c) { - boolean shouldHaveBeenNotified = false; - if ((l == null || layer.equals(l)) && (c == null || appContext.equals(c))) { - shouldHaveBeenNotified = true; - } - if (shouldHaveBeenNotified) { - String msg = "listener at layer,context: " + layer + "," + appContext + " should have been notified at: " - + l + "," + c; - assertTrue(msg, notified()); - } else { - String msg = "listener at layer,context: " + layer + "," + appContext + " should NOT have been notified at: " - + l + "," + c; - assertFalse(msg, notified()); - } - } - - @Override - public void notify(String l, String c) { - synchronized (this) { - notified = true; - } - boolean validNotification = (layer == l || layer.equals(l)) - && (appContext == c || appContext.equals(c)); - String msg = "listener notified at wrong layer: " + l + " or context: " + c; - assertTrue(msg, validNotification); - if (validNotification && reRegister) { - register(); - } - } - } - - @Test - public void stressFactory() { - stressFactory(DEFAULT_THREAD_COUNT, DEFAULT_MAX_JOIN_SECONDS); - } - - public void stressFactory(int threadCount, int maxJoinSeconds) { - - logger.info("BEGIN stress FACTORY TEST"); - AuthConfigFactory f = AuthConfigFactory.getFactory(); - f.refresh(); - providers[0] = null; - - for (int i = 1; i < providers.length; i++) { - providers[i] = new _AuthConfigProvider(getProviderProperties(), null); - } - threadPool = Executors.newFixedThreadPool(threadCount); - synchronized (_Thread.class) { - activeConsumers = threadCount; - consumerCount = threadCount; - } - - ArrayList> tasks = new ArrayList>(); - - for (int i = 0; i < threadCount; i++) { - _ResultCarrier carrier = new _ResultCarrier(); - Callable<_ResultCarrier> task = - Executors.callable(new _Thread(threadCount,carrier),carrier); - tasks.add(task); - } - - logger.log(Level.INFO, "STARTING {0} THREADS", threadCount); - try { - List> futures = threadPool.invokeAll(tasks,maxJoinSeconds,TimeUnit.SECONDS); - for (Future<_ResultCarrier> future : futures) { - if (future.isCancelled()) { - logger.log(Level.WARNING, - "try increasing maxJoinSeconds in {0}: test aborted because it did not terminate in {1} seconds", - new Object[]{this.getClass().getName(),maxJoinSeconds}); - fail("test did not terminate in: " + maxJoinSeconds + " seconds"); - } else if (future.isDone()) { - String errorMessage = future.get().getResult(); - if (errorMessage != null) { - logger.log(Level.SEVERE, errorMessage); - fail(errorMessage); - } - } - } - } catch (Throwable t) { - String exceptionMessage = "exception from invoking tasks or from invoked task"; - logger.log(Level.SEVERE, exceptionMessage,t); - fail(exceptionMessage + t.toString()); - } - - synchronized (_Thread.class) { - logger.log(Level.INFO, "ALL THREADS JOINED - producers: {0} consumers: {1}", - new Object[]{threadCount - consumerCount, consumerCount}); - } - - String[] rids = f.getRegistrationIDs(null); - for (String i : rids) { - RegistrationContext rc = f.getRegistrationContext(i); - f.removeRegistration(i); - } - logger.info("ALL REGISTRATIONS REMOVED"); - - f.refresh(); - } - - static class _ResultCarrier { - String result; - synchronized String getResult() { - return result; - } - synchronized void setResult(String result) { - this.result = result; - } - } - - static class _Thread extends Thread implements RegistrationListener { - - _ResultCarrier resultCarrier; - boolean runAsConsumer; - boolean stop; - - _Thread(int threadCount, _ResultCarrier carrier) { - this.resultCarrier = carrier; - synchronized (_Thread.class) { - if (consumerCount == threadCount) { - runAsConsumer = false; - } else { - runAsConsumer = (random.nextInt(10) != 1); - } - if (!runAsConsumer) { - consumerCount--; - activeConsumers--; - logger.log(Level.FINE, "creating producer, remaining consumers: {0}", consumerCount); - } - } - setResult(null); - stop = false; - } - - private void setResult(String result) { - resultCarrier.setResult(result); - } - - @Override - public void run() { - AuthConfigFactory f = AuthConfigFactory.getFactory(); - if (f == null) { - String msg = "new thread: " + getId() + " found null factory"; - logger.log(Level.SEVERE,msg); - setResult(msg); - } - else if (runAsConsumer) { - doConsumer(f, layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)]); - } else while (true) { - - synchronized (_Thread.class) { - if (activeConsumers == 0) { - setResult(null); - return; - } - } - - switch (random.nextInt(5)) { - case 0: - if (random.nextInt(25) == 1) { - try { - f.refresh(); - } catch (Exception e) { - String msg = "producer thread(refresh): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - } - } - break; - case 1: - if (random.nextInt(1000) == 1) { - try { - f = AuthConfigFactory.getFactory(); - if (f == null) { - String msg = "producer thread(get/set): " + getId() + " found null factory"; - logger.log(Level.SEVERE, msg); - setResult(msg); - return; - } - AuthConfigFactory.setFactory(f); - } catch (Exception e) { - String msg = "producer thread(get/setFactory): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - } - } - break; - case 2: - try { - f.registerConfigProvider( - _AuthConfigProvider.class.getName(), - getProviderProperties(), - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "persistent registration"); - } catch (Exception e) { - String msg = "producer thread(register persistent): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - } - break; - case 3: - try { - f.registerConfigProvider( - providers[random.nextInt(providers.length)], - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "transient registration"); - } catch (Exception e) { - String msg = "producer thread(register transient): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - } - break; - case 4: - try { - String[] rids = f.getRegistrationIDs( - providers[random.nextInt(providers.length)]); - int length = rids.length; - boolean removeNext = true; - for (String rid : rids) { - RegistrationContext rc = f.getRegistrationContext(rid); - if (rc == null) { - removeNext = true; - } else if (removeNext) { - f.removeRegistration(rid); - removeNext = false; - } else { - removeNext = true; - } - } - } catch (Exception e) { - String msg = "producer thread(remove registration): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - - } - break; - - } - } - } - - public void doConsumer(AuthConfigFactory f, String layer, String context) { - - String msg = null; - - synchronized (_Thread.class) { - logger.log(Level.FINE, "creating consumer"); - this.stop = false; - } - - try { - f.getConfigProvider(layer, context, this); - while (true) { - sleep(10); - synchronized (_Thread.class) { - if (this.stop) { - break; - } - } - } - f.detachListener(this, null, null); - } catch (Exception e) { - msg = "consumer thread: " + getId() + " caught exception"; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - } finally { - synchronized (_Thread.class) { - activeConsumers--; - logger.log(Level.INFO, "consumer thread: {0} stopping - remaining: {1}", - new Object[]{getId(), activeConsumers}); - } - } - } - - public void notify(String layer, String context) { - if (random.nextInt(100) == 1) { - synchronized (_Thread.class) { - setResult(null); - this.stop = true; - } - } else { - AuthConfigFactory factory = AuthConfigFactory.getFactory(); - if (factory != null) { - factory.getConfigProvider(layer, context, this); - } else { - synchronized (_Thread.class) { - setResult("factory is null in notify call on consumer"); - this.stop = true; - } - } - } - } - } - - - public static class _AuthConfigProvider implements AuthConfigProvider { - - public _AuthConfigProvider(Map properties, AuthConfigFactory f) { - if (f != null) { - f.registerConfigProvider(this, - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "self registration"); - } - } - - public ClientAuthConfig getClientAuthConfig(final String layer, - final String appCtxt, CallbackHandler ch) throws AuthException { - - return new ClientAuthConfig() { - - public ClientAuthContext getAuthContext(String string, Subject sbjct, Map map) throws AuthException { - throw new UnsupportedOperationException(); - } - - public String getMessageLayer() { - return layer; - } - - public String getAppContext() { - return appCtxt; - } - - public String getAuthContextID(MessageInfo mi) { - throw new UnsupportedOperationException(); - } - - public void refresh() { - } - - public boolean isProtected() { - throw new UnsupportedOperationException(); - } - }; - } - - public ServerAuthConfig getServerAuthConfig(final String layer, - final String appCtxt, CallbackHandler ch) throws AuthException { - - return new ServerAuthConfig() { - - public ServerAuthContext getAuthContext(String string, Subject sbjct, Map map) throws AuthException { - throw new UnsupportedOperationException(); - } - - public String getMessageLayer() { - return layer; - } - - public String getAppContext() { - return appCtxt; - } - - public String getAuthContextID(MessageInfo mi) { - throw new UnsupportedOperationException(); - } - - public void refresh() { - } - - public boolean isProtected() { - throw new UnsupportedOperationException(); - } - }; - } - - public void refresh() { - } - } - - - -} diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java deleted file mode 100644 index c8eefa5cb4a..00000000000 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] -package test.com.sun.jaspic.config; - -import com.sun.jaspic.config.servlet.JAASServletAuthConfigProvider; -import java.io.IOException; -import java.util.HashMap; -import java.util.Random; -import java.util.StringTokenizer; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.RegistrationListener; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; - -/** - * - * @author Ron Monzillo - */ -public class RuntimeSurrogate { - - static final Logger logger = Logger.getLogger(RuntimeSurrogate.class.getName()); - private static final String CONFIG_FILE_NAME_KEY = "config.file.name"; - static HashMap providerProperties = new HashMap(); - AuthConfigFactory factory; - AuthConfigProvider provider; - - public RuntimeSurrogate(AuthConfigProvider provider, AuthConfigFactory factory) { - String[] regIDS = factory.getRegistrationIDs(provider); - for (String i : regIDS) { - try { - RegistrationContext r = factory.getRegistrationContext(i); - System.out.println(contextToString(r)); - AuthConfigProvider p = factory.getConfigProvider(r.getMessageLayer(), r.getAppContext(), null); - ServerAuthConfig c = p.getServerAuthConfig(r.getMessageLayer(), r.getAppContext(), - new CallbackHandler() { - - public void handle(Callback[] clbcks) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedOperationException("Not supported yet."); - } - }); - ServerAuthContext s = c.getAuthContext("0", new Subject(), new HashMap()); - } catch (AuthException ex) { - Logger.getLogger(RuntimeSurrogate.class.getName()).log(Level.SEVERE, null, ex); - } - } - } - - public final String contextToString(RegistrationContext r) { - String rvalue = r.getDescription() + "\n\t" + r.getAppContext() + "\n\t" - + r.getMessageLayer() + "\n\t" + r.isPersistent() + "\n"; - return rvalue; - } - - public static void main(String[] args) { - System.out.println("Security Manager is " - + (System.getSecurityManager() == null ? "OFF" : "ON")); - System.out.println("user.dir: " + System.getProperty("user.dir")); - - for (String s : args) { - StringTokenizer tokenizer = new StringTokenizer(s, "="); - if (tokenizer.countTokens() == 2) { - String key = tokenizer.nextToken(); - String value = tokenizer.nextToken(); - System.out.println("key: " + key + " value: " + value); - providerProperties.put(key, value); - } - } - - AuthConfigFactory.setFactory(new AuthConfigFileFactory()); - final AuthConfigFactory f = AuthConfigFactory.getFactory(); - - final AuthConfigProvider p = new JAASServletAuthConfigProvider(providerProperties, f); - RuntimeSurrogate rS = new RuntimeSurrogate(p, f); - /* - p = new SpringServletAuthConfigProvider(properties, f); - rS = new RuntimeSurrogate(p, f); - */ - //listenertest - RegistrationListener listener = - new RegistrationListener() { - - public void notify(String layer, String context) { - System.out.println("listener notified - layer: " + layer + " context: " + context); - f.getConfigProvider(layer, context, this); - } - }; - - String rid1 = f.registerConfigProvider(p, "x", null, "test"); - String rid2 = f.registerConfigProvider(p, "x", "y1", "test"); - - f.getConfigProvider("x", "y1", listener); - f.getConfigProvider("x", "y2", listener); - - f.removeRegistration(rid2); - f.removeRegistration(rid1); - - providers[0] = null; - for (int i = 1; i < providers.length; i++) { - providers[i] = new JAASServletAuthConfigProvider(providerProperties, null); - } - f.detachListener(listener, null, null); - testFactory(); - } - static AuthConfigProvider[] providers = new AuthConfigProvider[4]; - static final TestThread[] threads = new TestThread[1024]; - - public static void testFactory() { - - AuthConfigFactory.setFactory(new AuthConfigFileFactory()); - - for (int i = 0; i < threads.length; i++) { - threads[i] = new TestThread(); - } - for (int i = 0; i < threads.length; i++) { - threads[i].start(); - } - for (TestThread t : threads) { - try { - t.join(); - } catch (InterruptedException ex) { - logger.log(Level.SEVERE, "thread: " + t.getId() + " caught exception", ex); - } finally { - logger.log(Level.INFO, "thread: {0} completed: {1}", new Object[]{t.getId(), t.runAsConsumer() ? "comsumer" : "producer"}); - } - } - logger.info("ALL THREADS JOINED"); - AuthConfigFactory f = AuthConfigFactory.getFactory(); - String[] rids = f.getRegistrationIDs(null); - for (String i : rids) { - RegistrationContext rc = f.getRegistrationContext(i); - logger.log(Level.INFO, "removing registration - layer: {0} appContext: {1} description: {2} persistent: {3}", - new Object[]{rc.getMessageLayer(), rc.getAppContext(), - rc.getDescription(), rc.isPersistent()}); - f.removeRegistration(i); - } - logger.info("ALL REGISTRATIONS REMOVED"); - } - - static class TestThread extends Thread implements RegistrationListener { - - static Random random = new Random(); - static String[] layers = new String[4]; - static String[] contexts = new String[16]; - static int consumerCount = threads.length; - boolean runAsConsumer = false; - boolean stop; - - static { - layers[0] = null; - for (int i = 1; i < layers.length; i++) { - layers[i] = "layer" + Integer.toString(i); - } - contexts[0] = null; - for (int i = 1; i < contexts.length; i++) { - contexts[i] = "context" + Integer.toString(i); - } - } - - @Override - public void run() { - synchronized (TestThread.class) { - if (consumerCount == threads.length) { - runAsConsumer = false; - } else { - runAsConsumer = (random.nextInt(threads.length / 10) != 1); - } - } - AuthConfigFactory f = AuthConfigFactory.getFactory(); - if (runAsConsumer) { - doConsumer(f, layers[random.nextInt(layers.length)], contexts[random.nextInt(contexts.length)]); - } else { - synchronized (TestThread.class) { - consumerCount--; - logger.log(Level.INFO, "creating producer, remaining consumers: " + consumerCount); - } - while (true) { - synchronized (TestThread.class) { - if (consumerCount == 0) { - return; - } - } - switch (random.nextInt(5)) { - case 0: - if (random.nextInt(25) == 1) { - try { - f.refresh(); - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - } - break; - case 1: - if (random.nextInt(1000) == 1) { - try { - f = AuthConfigFactory.getFactory(); - AuthConfigFactory.setFactory(f); - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - } - break; - case 2: - try { - f.registerConfigProvider( - "servlet.JAASServletAuthConfigProvider", providerProperties, - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "persistent registration"); - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - break; - case 3: - try { - f.registerConfigProvider( - providers[random.nextInt(providers.length)], - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "transient registration"); - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - break; - case 4: - try { - String[] rids = f.getRegistrationIDs( - providers[random.nextInt(providers.length)]); - int length = rids.length; - boolean removeNext = true; - for (String rid : rids) { - RegistrationContext rc = f.getRegistrationContext(rid); - if (rc == null) { - removeNext = true; - } else if (removeNext) { - f.removeRegistration(rid); - removeNext = false; - } else { - removeNext = true; - } - } - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - break; - - } - } - } - } - - public boolean runAsConsumer() { - return runAsConsumer; - } - - public void doConsumer(AuthConfigFactory f, String layer, String context) { - - synchronized (TestThread.class) { - logger.log(Level.INFO, "creating consumer"); - this.stop = false; - } - try { - while (true) { - f.getConfigProvider(layer, context, this); - sleep(100); - synchronized (TestThread.class) { - if (this.stop) { - break; - } - } - } - f.detachListener(this, null, null); - } catch (Exception e) { - logger.log(Level.SEVERE, "consumer thread: " + getId(), e); - } finally { - synchronized (TestThread.class) { - consumerCount--; - logger.log(Level.INFO, "consumer thread: " + getId() + "stopping - remaining: " + consumerCount); - } - } - } - - public void notify(String layer, String context) { - if (random.nextInt(100) == 1) { - synchronized (TestThread.class) { - this.stop = true; - } - } - } - } -} diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleClientAuthModule.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleClientAuthModule.java deleted file mode 100644 index 7a4c2c3087d..00000000000 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleClientAuthModule.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package test.com.sun.jaspic.config; - -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.module.ClientAuthModule; - -/** - * - * @author Ron Monzillo - */ -public class SampleClientAuthModule implements ClientAuthModule { - - public void initialize(MessagePolicy mp, MessagePolicy mp1, CallbackHandler ch, Map map) throws AuthException { - throw new UnsupportedOperationException("Not supported yet."); - } - - public Class[] getSupportedMessageTypes() { - throw new UnsupportedOperationException("Not supported yet."); - } - - public AuthStatus secureRequest(MessageInfo mi, Subject sbjct) throws AuthException { - throw new UnsupportedOperationException("Not supported yet."); - } - - public AuthStatus validateResponse(MessageInfo mi, Subject sbjct, Subject sbjct1) throws AuthException { - throw new UnsupportedOperationException("Not supported yet."); - } - - public void cleanSubject(MessageInfo mi, Subject sbjct) throws AuthException { - throw new UnsupportedOperationException("Not supported yet."); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleServerAuthModule.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleServerAuthModule.java deleted file mode 100644 index 2c2768b258b..00000000000 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleServerAuthModule.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package test.com.sun.jaspic.config; - -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.module.ServerAuthModule; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -/** - * - * @author Ron Monzillo - */ -public class SampleServerAuthModule implements ServerAuthModule { - - public void initialize(MessagePolicy mp, MessagePolicy mp1, CallbackHandler ch, Map map) throws AuthException { - } - - public Class[] getSupportedMessageTypes() { - return new Class[]{HttpServletRequest.class, HttpServletResponse.class}; - } - - public AuthStatus validateRequest(MessageInfo mi, Subject sbjct, Subject sbjct1) throws AuthException { - return AuthStatus.SUCCESS; - } - - public AuthStatus secureResponse(MessageInfo mi, Subject sbjct) throws AuthException { - return AuthStatus.SEND_SUCCESS; - } - - public void cleanSubject(MessageInfo mi, Subject sbjct) throws AuthException { - } -} - diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java index 006e6423399..df85a30a6d6 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java @@ -95,7 +95,6 @@ import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServletServices; import com.sun.enterprise.security.web.integration.WebPrincipal; -import com.sun.jaspic.config.servlet.HttpMessageInfo; import com.sun.logging.LogDomains; import com.sun.web.security.HttpRequestWrapper; import com.sun.web.security.HttpResponseWrapper; @@ -104,6 +103,7 @@ import fish.payara.notification.requesttracing.RequestTraceSpan; import fish.payara.nucleus.requesttracing.RequestTracingService; +import org.glassfish.epicyro.config.servlet.HttpMessageInfo; public class JaspicRealm { diff --git a/appserver/security/webservices.security/pom.xml b/appserver/security/webservices.security/pom.xml index a14995ec401..04749472473 100644 --- a/appserver/security/webservices.security/pom.xml +++ b/appserver/security/webservices.security/pom.xml @@ -52,7 +52,7 @@ webservices.security glassfish-jar - WebServices Security and JSR 196 implementation + WebServices Security and Jakarta Authentication implementation diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/BaseAuthConfig.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/BaseAuthConfig.java deleted file mode 100644 index 596cf0164a0..00000000000 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/BaseAuthConfig.java +++ /dev/null @@ -1,608 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth.jaspic.provider; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.xml.namespace.QName; -import jakarta.xml.soap.MimeHeaders; -import jakarta.xml.soap.Name; -import jakarta.xml.soap.SOAPBody; -import jakarta.xml.soap.SOAPElement; -import jakarta.xml.soap.SOAPEnvelope; -import jakarta.xml.soap.SOAPException; -import jakarta.xml.soap.SOAPMessage; -import jakarta.xml.soap.SOAPPart; -import jakarta.xml.ws.handler.MessageContext; -import jakarta.xml.ws.handler.soap.SOAPMessageContext; - -import com.sun.enterprise.deployment.MethodDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; -import com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor; -import com.sun.enterprise.security.jauth.AuthPolicy; -import com.sun.enterprise.security.webservices.LogUtils; - -/** - * This class is the container's base interface to the AuthConfig subsystem to get AuthContext - * objects on which to invoke message layer authentication providers. It is not intended to be layer - * or web services specific (see getMechanisms method at end). The ServerAuthConfig and - * ClientAuthConfig classes extend this class. - */ -public class BaseAuthConfig { - - private static final Logger logger = LogUtils.getLogger(); - - private Object defaultContext_; - - // holds protected msd that applies to all methods (if there is one) - private MessageSecurityDescriptor superMSD_; - private int superIndex_; - - private ArrayList contexts_; - - private List messageSecurityDescriptors_; - - private ArrayList contextsForOpcodes_; - - private HashMap contextsForOpNames_; - - private boolean onePolicy_; - - private final Object contextLock = new Object(); - - private ExplicitNull explicitNull = new ExplicitNull(); - - protected BaseAuthConfig(Object context) { - - defaultContext_ = context; - superMSD_ = null; - superIndex_ = -1; - - messageSecurityDescriptors_ = null; - contexts_ = null; - contextsForOpcodes_ = null; - contextsForOpNames_ = null; - - onePolicy_ = true; - - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: New BAC defaultContext: {0}", defaultContext_); - } - } - - protected BaseAuthConfig(List descriptors, ArrayList authContexts) { - - defaultContext_ = null; - superMSD_ = null; - superIndex_ = -1; - - messageSecurityDescriptors_ = descriptors; - contexts_ = authContexts; - contextsForOpcodes_ = null; - contextsForOpNames_ = null; - - onePolicy_ = true; - - for (int i = 0; i < descriptors.size(); i++) { - - MessageSecurityDescriptor msd = (MessageSecurityDescriptor) descriptors.get(i); - - // determine if all the different messageSecurityDesriptors have the - // same policy which will help us interpret the effective policy if - // we cannot determine the opcode of a request at runtime. - - for (int j = 0; j < descriptors.size(); j++) { - if (j != i && !policiesAreEqual(msd, ((MessageSecurityDescriptor) descriptors.get(j)))) { - onePolicy_ = false; - } - } - } - - for (int i = 0; defaultContext_ == null && i < descriptors.size(); i++) { - - MessageSecurityDescriptor msd = (MessageSecurityDescriptor) descriptors.get(i); - - AuthPolicy requestPolicy = getAuthPolicy(msd.getRequestProtectionDescriptor()); - AuthPolicy responsePolicy = getAuthPolicy(msd.getResponseProtectionDescriptor()); - - boolean noProtection = (!requestPolicy.authRequired() && !responsePolicy.authRequired()); - - // if there is one policy, and it is null set the associated context as the - // defaultContext used for all messages. - if (i == 0 && onePolicy_ && noProtection) { - defaultContext_ = explicitNull; - break; - } - - List mDs = msd.getMessageDescriptors(); - - for (int j = 0; mDs != null && j < mDs.size(); j++) { - - MessageDescriptor mD = (MessageDescriptor) mDs.get(j); - MethodDescriptor methD = mD.getMethodDescriptor(); - - // if any msd covers all methods and operations. - if ((mD.getOperationName() == null && methD == null) || (methD != null && methD.getStyle() == 1)) { - - if (onePolicy_) { - // if there is only one policy make it the default. - defaultContext_ = contexts_.get(i); - if (defaultContext_ == null) { - defaultContext_ = explicitNull; - } - break; - } else if (superIndex_ == -1) { - // if it has a noProtection policy make it the default. - if (noProtection) { - defaultContext_ = explicitNull; - } else { - superIndex_ = i; - } - } else if (!policiesAreEqual(msd, ((MessageSecurityDescriptor) descriptors.get(superIndex_)))) { - // if there are conflicting policies that cover all methods - // set the default policy to noProtection - defaultContext_ = explicitNull; - superIndex_ = -1; - break; - } - } - } - } - // if there is protected policy that applies to all methods remember the descriptor. - // Note that the corresponding policy is not null, and thus it is not the default. - // wherever there is a conflicting policy the effective policy will be noProtection. - if (superIndex_ >= 0) { - superMSD_ = (MessageSecurityDescriptor) descriptors.get(superIndex_); - } - - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: new BAC defaultContext_: {0} superMSD index: {1} onePolicy_: {2}", - new Object[] { defaultContext_, superIndex_, onePolicy_ }); - } - } - - protected static AuthPolicy getAuthPolicy(ProtectionDescriptor pd) { - int sourceAuthType = AuthPolicy.SOURCE_AUTH_NONE; - boolean recipientAuth = false; - boolean beforeContent = false; - if (pd != null) { - String source = pd.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); - if (source != null) { - if (source.equals(AuthPolicy.SENDER)) { - sourceAuthType = AuthPolicy.SOURCE_AUTH_SENDER; - } else if (source.equals(AuthPolicy.CONTENT)) { - sourceAuthType = AuthPolicy.SOURCE_AUTH_CONTENT; - } - } - String recipient = pd.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); - if (recipient != null) { - recipientAuth = true; - if (recipient.equals(AuthPolicy.BEFORE_CONTENT)) { - beforeContent = true; - } else if (recipient.equals(AuthPolicy.AFTER_CONTENT)) { - beforeContent = false; - } - } - } - - return new AuthPolicy(sourceAuthType, recipientAuth, beforeContent); - } - - private static boolean isMatchingMSD(MethodDescriptor targetMD, MessageSecurityDescriptor mSD) { - List messageDescriptors = mSD.getMessageDescriptors(); - if (messageDescriptors.isEmpty()) { - // If this happens the deployment descriptor is invalid. - // - // Unfortunately the deployment system does not catch such problems. - // This case will be treated the same as if there was an empty message - // element, and the deployment will be allowed to succeed. - return true; - } - - for (int i = 0; i < messageDescriptors.size(); i++) { - MessageDescriptor nextMD = (MessageDescriptor) messageDescriptors.get(i); - MethodDescriptor mD = nextMD.getMethodDescriptor(); - String opName = nextMD.getOperationName(); - - if (opName == null && (mD == null || mD.implies(targetMD))) { - return true; - } - } - - return false; - } - - private static boolean policiesAreEqual(MessageSecurityDescriptor reference, MessageSecurityDescriptor other) { - if (!getAuthPolicy(reference.getRequestProtectionDescriptor()).equals(getAuthPolicy(other.getRequestProtectionDescriptor())) || - - !getAuthPolicy(reference.getResponseProtectionDescriptor()) - .equals(getAuthPolicy(other.getResponseProtectionDescriptor()))) { - - return false; - } - return true; - } - - /* - * When method argument is null, returns the default AC if there is one, or the onePolicy shared by - * all methods if there is one, or throws an error. method is called with null argument when the - * method cannot be determined (e.g. when the message is encrypted) - */ - private Object getContextForMethod(Method m) { - Object rvalue = null; - synchronized (contextLock) { - if (defaultContext_ != null) { - rvalue = defaultContext_; - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForMethod returning default_context: {0}", rvalue); - } - return rvalue; - } - } - if (m != null) { - int match = -1; - MethodDescriptor targetMD = new MethodDescriptor(m); - for (int i = 0; i < messageSecurityDescriptors_.size(); i++) { - if (isMatchingMSD(targetMD, (MessageSecurityDescriptor) messageSecurityDescriptors_.get(i))) { - if (match < 0) { - match = i; - } else if (!policiesAreEqual((MessageSecurityDescriptor) messageSecurityDescriptors_.get(match), - (MessageSecurityDescriptor) messageSecurityDescriptors_.get(i))) { - - // set to unprotected because of conflicting policies - - rvalue = explicitNull; - match = -1; - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForMethod detected conflicting policies: {0}.{1}", new Object[] { match, i }); - } - break; - } - } - } - if (match >= 0) { - rvalue = contexts_.get(match); - if (rvalue == null) { - rvalue = explicitNull; - } - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForMethod returning matched context: {0}", rvalue); - } - } - } else if (onePolicy_ && contexts_.size() > 0) { - // ISSUE: since the method is undefined we will not be - // able to tell if the defined policy covers this method. - // We will be optimistic and try the policy, because - // the server will reject the call if the method is not - // covered by the policy. - // If the policy is not null, there remains a problem at the - // client on the response side, as it is possible that the - // client will enforce the wrong policy on the response. - // For this reason, messages in sun-application-client.xml - // should be keyed by operation-name. - - rvalue = contexts_.get(0); - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForMethod resorting to first context: {0}", rvalue); - } - - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("WSS: Unable to select policy for SOAP Message"); - } - throw new RuntimeException("Unable to select policy for Message"); - } - return rvalue; - } - - private static String getOpName(SOAPMessage message) { - - String rvalue = null; - - // first look for a SOAPAction header. - // this is what .net uses to identify the operation - - MimeHeaders headers = message.getMimeHeaders(); - if (headers != null) { - String[] actions = headers.getHeader("SOAPAction"); - if (actions != null && actions.length > 0) { - rvalue = actions[0]; - if (rvalue != null && rvalue.equals("\"\"")) { - rvalue = null; - } - } - } - - // if that doesn't work then we default to trying the name - // of the first child element of the SOAP envelope. - - if (rvalue == null) { - Name name = getName(message); - if (name != null) { - rvalue = name.getLocalName(); - } - } - - return rvalue; - } - - private static String getOpName(SOAPMessageContext soapMC) { - - String rvalue; - - // first look for a the property value in the context - QName qName = (QName) soapMC.get(MessageContext.WSDL_OPERATION); - if (qName != null) { - rvalue = qName.getLocalPart(); - } else { - rvalue = getOpName(soapMC.getMessage()); - } - - return rvalue; - } - - private Object getContextForOpName(String operation) { - - synchronized (contextLock) { - if (contextsForOpNames_ == null) { - - // one time initialization of the opName to authContext array. - - contextsForOpNames_ = new HashMap(); - for (int i = 0; messageSecurityDescriptors_ != null && i < messageSecurityDescriptors_.size(); i++) { - - MessageSecurityDescriptor mSD = (MessageSecurityDescriptor) messageSecurityDescriptors_.get(i); - - List mDs = mSD.getMessageDescriptors(); - - for (int j = 0; mDs != null && j < mDs.size(); j++) { - - MessageDescriptor mD = (MessageDescriptor) mDs.get(j); - String opName = mD.getOperationName(); - - if (opName != null) { - - if (contextsForOpNames_.containsKey(opName)) { - - Integer k = (Integer) contextsForOpNames_.get(opName); - if (k != null) { - - MessageSecurityDescriptor other = (MessageSecurityDescriptor) messageSecurityDescriptors_ - .get(k.intValue()); - - // set to null if different policies on operation - - if (!policiesAreEqual(mSD, other)) { - contextsForOpNames_.put(opName, null); - } - } - } else if (superMSD_ != null && !policiesAreEqual(mSD, superMSD_)) { - // set to null if operation policy differs from superPolicy - contextsForOpNames_.put(opName, null); - } else { - contextsForOpNames_.put(opName, Integer.valueOf(i)); - } - } - } - } - } - } - - Object rvalue = null; - if (operation != null) { - if (contextsForOpNames_.containsKey(operation)) { - Integer k = (Integer) contextsForOpNames_.get(operation); - if (k != null) { - rvalue = contexts_.get(k.intValue()); - } - } else if (superIndex_ >= 0) { - // if there is a msb that matches all methods, use the - // associatedContext - rvalue = contexts_.get(superIndex_); - } - - if (rvalue == null) { - // else return explicitNull under the assumption - // that methodName was known, and no match was found - rvalue = explicitNull; - } - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForOpName={0} context: {1}", new Object[] { operation, rvalue }); - } - } - return rvalue; - } - - // DO NOT CALL THIS ON THE SERVER SIDE, as it will return a null - // context if there is no default context and there isn't a message - // element defined with the corresponding operation name (even though the - // corresponding method may be protected). - // - // This method is intended to be used by clients where it serves as a - // work-around for not being able to map the message to the method (due - // to lack of access to a streaming handler equivalent). - // - // This method will not be called when the handler argument passed in - // a call to getContext or getContextForOpCode is not null. - // Thus, server-side calls to these methods must pass a non-null - // handler argument. - - private Object getContextForMessage(SOAPMessage message) { - - String opName = getOpName(message); - - Object rvalue = getContextForOpName(opName); - if (rvalue == null) { - - // opName is not mapped or msg body is encrypted, and the best - // we can do is try to return a policy that applies to all - // operations, if there is one. - - rvalue = getContextForMethod(null); - - } - return rvalue; - } - - // used by jaxws system handler delegates and handlers - protected Object getContext(SOAPMessageContext soapMC) { - - Object rvalue = null; - - synchronized (contextLock) { - if (defaultContext_ != null) { - rvalue = defaultContext_; - } - } - - if (rvalue == null) { - - Method m = getMethod(soapMC); - String opName = null; - - if (m != null) { - rvalue = getContextForMethod(m); - } - - if (rvalue == null) { - opName = getOpName(soapMC); - if (opName != null) { - rvalue = getContextForOpName(opName); - } - } - - if (rvalue == null && (m == null || opName == null)) { - - // we were unable to determine either method or - // opName, so lets see if one policy applies to all - - rvalue = getContextForMethod(null); - } - } - - if (rvalue != null && rvalue instanceof ExplicitNull) { - rvalue = null; - } - - return rvalue; - } - - private static Name getName(SOAPMessage message) { - Name rvalue = null; - SOAPPart soap = message.getSOAPPart(); - if (soap != null) { - try { - SOAPEnvelope envelope = soap.getEnvelope(); - if (envelope != null) { - SOAPBody body = envelope.getBody(); - if (body != null) { - Iterator it = body.getChildElements(); - while (it.hasNext()) { - Object o = it.next(); - if (o instanceof SOAPElement) { - rvalue = ((SOAPElement) o).getElementName(); - break; - } - } - } - } - } catch (SOAPException se) { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: Unable to get SOAP envelope", se); - } - } - } - - return rvalue; - } - - public static Method getMethod(SOAPMessageContext soapMC) { - - // It should never come here - return null; - } - - // each instance of AuthConfig maps to one provider - // configuration, either via a message-security-binding, or a default - // provider-config. - - // mechanisms are temporarily encapsulated here, until a method that - // returns the list of supported mechanisms is added to - // jauth.ServerAuthContext and jauth.ClientAuthContext. - public QName[] getMechanisms() { - return mechanisms; - } - - // WSS security header QName - private static QName mechanisms[] = new QName[] { - new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", "wsse") }; - - // internal class used to differentiate not protected from policy undefined or - // not determined. - - static class ExplicitNull { - - ExplicitNull() { - } - - @Override - public boolean equals(Object other) { - return (other != null && other instanceof ExplicitNull ? true : false); - } - - @Override - public int hashCode() { - return super.hashCode(); - } - - @Override - public String toString() { - return "ExplicitNull"; - } - } -} diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ClientAuthConfig.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ClientAuthConfig.java deleted file mode 100644 index bcd28dc59e1..00000000000 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ClientAuthConfig.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth.jaspic.provider; - -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; - -import java.util.ArrayList; -import java.util.List; - -import javax.security.auth.callback.CallbackHandler; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; -import com.sun.enterprise.security.jauth.AuthConfig; -import com.sun.enterprise.security.jauth.AuthException; -import com.sun.enterprise.security.jauth.AuthPolicy; -import com.sun.enterprise.security.jauth.ClientAuthContext; - -/** - * This class is the client container's interface to the AuthConfig subsystem to get AuthContext objects on which to - * invoke message layer authentication providers. It is not intended to be layer or web services specific (see - * getMechanisms method at end). - */ -public class ClientAuthConfig extends BaseAuthConfig { - - private ClientAuthConfig(ClientAuthContext defaultContext) { - super(defaultContext); - } - - private ClientAuthConfig(List descriptors, ArrayList authContexts) { - super(descriptors, authContexts); - } - - public static ClientAuthConfig getConfig(String authLayer, MessageSecurityBindingDescriptor binding, CallbackHandler cbh) throws AuthException { - ClientAuthConfig rvalue = null; - String provider = null; - List descriptors = null; - ClientAuthContext defaultContext = null; - if (binding != null) { - String layer = binding.getAttributeValue(AUTH_LAYER); - if (authLayer != null && layer.equals(authLayer)) { - provider = binding.getAttributeValue(PROVIDER_ID); - descriptors = binding.getMessageSecurityDescriptors(); - } - } - - if (descriptors == null || descriptors.size() == 0) { - defaultContext = getAuthContext(authLayer, provider, null, null, cbh); - if (defaultContext != null) { - rvalue = new ClientAuthConfig(defaultContext); - } - } else { - boolean hasPolicy = false; - ArrayList authContexts = new ArrayList(); - for (int i = 0; i < descriptors.size(); i++) { - MessageSecurityDescriptor msd = (MessageSecurityDescriptor) descriptors.get(i); - AuthPolicy requestPolicy = getAuthPolicy(msd.getRequestProtectionDescriptor()); - AuthPolicy responsePolicy = getAuthPolicy(msd.getResponseProtectionDescriptor()); - if (requestPolicy.authRequired() || responsePolicy.authRequired()) { - authContexts.add(getAuthContext(authLayer, provider, requestPolicy, responsePolicy, cbh)); - hasPolicy = true; - } else { - authContexts.add(null); - } - } - if (hasPolicy) { - rvalue = new ClientAuthConfig(descriptors, authContexts); - } - } - return rvalue; - } - - private static ClientAuthContext getAuthContext(String layer, String provider, AuthPolicy requestPolicy, AuthPolicy responsePolicy, CallbackHandler cbh) - throws AuthException { - AuthConfig authConfig = AuthConfig.getAuthConfig(); - return authConfig.getClientAuthContext(layer, provider, requestPolicy, responsePolicy, cbh); - } - - public ClientAuthContext getAuthContext(jakarta.xml.ws.handler.soap.SOAPMessageContext context) { - return (ClientAuthContext) getContext(context); - } - -} diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/SOAPAuthParam.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/SOAPAuthParam.java index be151e2d84c..904439b87d9 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/SOAPAuthParam.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/SOAPAuthParam.java @@ -37,10 +37,9 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jauth.jaspic.provider; -import com.sun.enterprise.security.jauth.AuthParam; import java.util.Map; import java.util.HashMap; import jakarta.xml.soap.*; @@ -64,7 +63,7 @@ * * @version 1.12, 06/08/04 */ -public class SOAPAuthParam implements AuthParam { +public class SOAPAuthParam { private HashMap infoMap; diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ServerAuthConfig.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ServerAuthConfig.java deleted file mode 100644 index 7d760d4647c..00000000000 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ServerAuthConfig.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth.jaspic.provider; - -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; - -import java.util.ArrayList; -import java.util.List; - -import javax.security.auth.callback.CallbackHandler; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; -import com.sun.enterprise.security.jauth.AuthConfig; -import com.sun.enterprise.security.jauth.AuthException; -import com.sun.enterprise.security.jauth.AuthPolicy; -import com.sun.enterprise.security.jauth.ServerAuthContext; - -/** - * This class is the client container's interface to the AuthConfig subsystem to get AuthContext objects on which to - * invoke message layer authentication providers. It is not intended to be layer or web services specific (see - * getMechanisms method at end). - */ -public class ServerAuthConfig extends BaseAuthConfig { - - private ServerAuthConfig(ServerAuthContext defaultContext) { - super(defaultContext); - } - - private ServerAuthConfig(List descriptors, ArrayList authContexts) { - super(descriptors, authContexts); - } - - public static ServerAuthConfig getConfig(String authLayer, MessageSecurityBindingDescriptor binding, CallbackHandler cbh) throws AuthException { - ServerAuthConfig rvalue = null; - String provider = null; - List descriptors = null; - ServerAuthContext defaultContext = null; - if (binding != null) { - String layer = binding.getAttributeValue(AUTH_LAYER); - if (authLayer != null && layer.equals(authLayer)) { - provider = binding.getAttributeValue(PROVIDER_ID); - descriptors = binding.getMessageSecurityDescriptors(); - } - } - - if (descriptors == null || descriptors.size() == 0) { - defaultContext = getAuthContext(authLayer, provider, null, null, cbh); - if (defaultContext != null) { - rvalue = new ServerAuthConfig(defaultContext); - } - } else { - boolean hasPolicy = false; - ArrayList authContexts = new ArrayList(); - for (int i = 0; i < descriptors.size(); i++) { - MessageSecurityDescriptor msd = (MessageSecurityDescriptor) descriptors.get(i); - AuthPolicy requestPolicy = getAuthPolicy(msd.getRequestProtectionDescriptor()); - AuthPolicy responsePolicy = getAuthPolicy(msd.getResponseProtectionDescriptor()); - if (requestPolicy.authRequired() || responsePolicy.authRequired()) { - authContexts.add(getAuthContext(authLayer, provider, requestPolicy, responsePolicy, cbh)); - hasPolicy = true; - } else { - authContexts.add(null); - } - } - - if (hasPolicy) { - rvalue = new ServerAuthConfig(descriptors, authContexts); - } - } - - return rvalue; - } - - private static ServerAuthContext getAuthContext(String layer, String provider, AuthPolicy requestPolicy, AuthPolicy responsePolicy, CallbackHandler cbh) throws AuthException { - AuthConfig authConfig = AuthConfig.getAuthConfig(); - return authConfig.getServerAuthContext(layer, provider, requestPolicy, responsePolicy, cbh); - } - - public ServerAuthContext getAuthContext(jakarta.xml.ws.handler.soap.SOAPMessageContext context) { - return (ServerAuthContext) getContext(context); - } - -} diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java similarity index 99% rename from appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java rename to appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java index 08b59322298..1397eb3e167 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java @@ -111,7 +111,7 @@ import com.sun.xml.ws.api.model.wsdl.WSDLPort; import com.sun.xml.ws.api.server.WSEndpoint; -public class PipeHelper extends PayaraEpicyroServices { +public class SoapAuthenticationService extends PayaraEpicyroServices { protected static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(PipeConstants.class); @@ -122,7 +122,7 @@ public class PipeHelper extends PayaraEpicyroServices { private InvocationManager invManager; private EJBPolicyContextDelegate ejbDelegate; - public PipeHelper(String layer, Map properties, CallbackHandler callbackHandler) { + public SoapAuthenticationService(String layer, Map properties, CallbackHandler callbackHandler) { init(layer, getAppCtxt(properties), properties, callbackHandler, (RegistrationWrapperRemover) Globals.get(WebServicesDelegate.class)); isEjbEndpoint = processSunDeploymentDescriptor(); diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipe.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipe.java index b9b43c0bc7a..ea5adb0e1e8 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipe.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipe.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static com.sun.enterprise.security.webservices.PipeConstants.SECURITY_PIPE; @@ -58,7 +58,7 @@ import com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; -import com.sun.enterprise.security.jauth.jaspic.provider.config.PipeHelper; +import com.sun.enterprise.security.jauth.jaspic.provider.config.SoapAuthenticationService; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.xml.ws.api.message.Message; import com.sun.xml.ws.api.message.Packet; @@ -74,7 +74,7 @@ */ public class ClientSecurityPipe extends AbstractFilterPipeImpl implements SecureConversationInitiator { - protected PipeHelper helper; + protected SoapAuthenticationService helper; protected static final Logger _logger = LogUtils.getLogger(); @@ -93,7 +93,7 @@ public ClientSecurityPipe(Map props, Pipe next) { props.put(WSDL_SERVICE, wsdlModel.getOwner().getName()); } - helper = new PipeHelper(SOAP_LAYER, props, null); + helper = new SoapAuthenticationService(SOAP_LAYER, props, null); } protected ClientSecurityPipe(ClientSecurityPipe that, PipeCloner cloner) { @@ -125,7 +125,7 @@ public final Pipe copy(PipeCloner cloner) { return new ClientSecurityPipe(this, cloner); } - public PipeHelper getPipeHelper() { + public SoapAuthenticationService getPipeHelper() { return helper; } @@ -226,7 +226,7 @@ private static Subject getClientSubject(Packet p) { if (s == null) { - s = PipeHelper.getClientSubject(); + s = SoapAuthenticationService.getClientSubject(); if (p != null) { p.invocationProperties.put(PipeConstants.CLIENT_SUBJECT, s); diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipeCreator.java similarity index 79% rename from appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java rename to appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipeCreator.java index f06686cfe72..7a360ee99b4 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipeCreator.java @@ -60,49 +60,49 @@ import com.sun.xml.ws.policy.PolicyMap; /** - * This is used by WSClientContainer to return proper JASPIC 196 security pipe to the + * This is used by WSClientContainer to return proper Jakarta Authentication security pipe to the * StandAlonePipeAssembler and TangoPipeAssembler */ -public class ClientPipeCreator extends ClientPipelineHook { +public class ClientSecurityPipeCreator extends ClientPipelineHook { - private ServiceReferenceDescriptor svcRef = null; + private ServiceReferenceDescriptor serviceReferenceDescriptor = null; - public ClientPipeCreator() { + public ClientSecurityPipeCreator() { } - public ClientPipeCreator(ServiceReferenceDescriptor ref) { - svcRef = ref; + public ClientSecurityPipeCreator(ServiceReferenceDescriptor ref) { + serviceReferenceDescriptor = ref; } @Override public Pipe createSecurityPipe(PolicyMap map, ClientPipeAssemblerContext ctxt, Pipe tail) { - HashMap props = new HashMap<>(); + HashMap properties = new HashMap<>(); - props.put(POLICY, map); - props.put(WSDL_MODEL, ctxt.getWsdlModel()); - props.put(SERVICE, ctxt.getService()); - props.put(BINDING, ctxt.getBinding()); - props.put(ENDPOINT_ADDRESS, ctxt.getAddress()); - if (svcRef != null) { - props.put(SERVICE_REF, svcRef); + properties.put(POLICY, map); + properties.put(WSDL_MODEL, ctxt.getWsdlModel()); + properties.put(SERVICE, ctxt.getService()); + properties.put(BINDING, ctxt.getBinding()); + properties.put(ENDPOINT_ADDRESS, ctxt.getAddress()); + if (serviceReferenceDescriptor != null) { + properties.put(SERVICE_REF, serviceReferenceDescriptor); } - props.put(NEXT_PIPE, tail); - props.put(CONTAINER, ctxt.getContainer()); - props.put(ASSEMBLER_CONTEXT, ctxt); - ClientSecurityPipe ret = new ClientSecurityPipe(props, tail); + properties.put(NEXT_PIPE, tail); + properties.put(CONTAINER, ctxt.getContainer()); + properties.put(ASSEMBLER_CONTEXT, ctxt); + ClientSecurityPipe clientSecurityPipe = new ClientSecurityPipe(properties, tail); - AuthConfigRegistrationWrapper listenerWrapper = ClientPipeCloser.getInstance().lookupListenerWrapper(svcRef); + AuthConfigRegistrationWrapper listenerWrapper = ClientPipeCloser.getInstance().lookupListenerWrapper(serviceReferenceDescriptor); // there is a 1-1 mapping between Service_Ref and a ListenerWrapper if (listenerWrapper != null) { // override the listener that was created by the ConfigHelper CTOR :if one was already registered listenerWrapper.incrementReference(); - ret.getPipeHelper().setRegistrationWrapper(listenerWrapper); + clientSecurityPipe.getPipeHelper().setRegistrationWrapper(listenerWrapper); } else { // register a new listener - ClientPipeCloser.getInstance().registerListenerWrapper(svcRef, ret.getPipeHelper().getRegistrationWrapper()); + ClientPipeCloser.getInstance().registerListenerWrapper(serviceReferenceDescriptor, clientSecurityPipe.getPipeHelper().getRegistrationWrapper()); } - return ret; + return clientSecurityPipe; } // @Override diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityTube.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityTube.java index d9b55359829..197f8cffd11 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityTube.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityTube.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static com.sun.enterprise.security.webservices.PipeConstants.SECURITY_TOKEN; @@ -55,7 +55,7 @@ import com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; -import com.sun.enterprise.security.jauth.jaspic.provider.config.PipeHelper; +import com.sun.enterprise.security.jauth.jaspic.provider.config.SoapAuthenticationService; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.xml.ws.api.message.Message; import com.sun.xml.ws.api.message.Packet; @@ -73,7 +73,7 @@ */ public class ClientSecurityTube extends AbstractFilterTubeImpl implements SecureConversationInitiator { - protected PipeHelper helper; + protected SoapAuthenticationService helper; protected static final Logger _logger = LogUtils.getLogger(); @@ -94,7 +94,7 @@ public ClientSecurityTube(Map props, Tube next) { if (wsdlModel != null) { props.put(PipeConstants.WSDL_SERVICE, wsdlModel.getOwner().getName()); } - this.helper = new PipeHelper(PipeConstants.SOAP_LAYER, props, null); + this.helper = new SoapAuthenticationService(PipeConstants.SOAP_LAYER, props, null); } @@ -203,7 +203,7 @@ private static Subject getClientSubject(Packet p) { if (s == null) { - s = PipeHelper.getClientSubject(); + s = SoapAuthenticationService.getClientSubject(); if (p != null) { p.invocationProperties.put(PipeConstants.CLIENT_SUBJECT, s); diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityPipe.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityPipe.java index d716e2b1033..5d029d927d7 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityPipe.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityPipe.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import java.security.PrivilegedActionException; @@ -54,7 +54,7 @@ import com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; -import com.sun.enterprise.security.jauth.jaspic.provider.config.PipeHelper; +import com.sun.enterprise.security.jauth.jaspic.provider.config.SoapAuthenticationService; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.xml.ws.api.message.Packet; import com.sun.xml.ws.api.pipe.Pipe; @@ -72,14 +72,14 @@ public class CommonServerSecurityPipe extends AbstractFilterPipeImpl { private final boolean isHttpBinding; - private PipeHelper helper; + private SoapAuthenticationService helper; private static final String WSIT_SERVER_AUTH_CONTEXT = "com.sun.xml.wss.provider.wsit.WSITServerAuthContext"; public CommonServerSecurityPipe(Map props, final Pipe next, boolean isHttpBinding) { super(next); props.put(PipeConstants.SECURITY_PIPE, this); - this.helper = new PipeHelper(PipeConstants.SOAP_LAYER, props, null); + this.helper = new SoapAuthenticationService(PipeConstants.SOAP_LAYER, props, null); this.isHttpBinding = isHttpBinding; } @@ -274,7 +274,7 @@ private static Subject getClientSubject(Packet p) { s = (Subject) p.invocationProperties.get(PipeConstants.CLIENT_SUBJECT); } if (s == null) { - s = PipeHelper.getClientSubject(); + s = SoapAuthenticationService.getClientSubject(); if (p != null) { p.invocationProperties.put(PipeConstants.CLIENT_SUBJECT, s); } diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityTube.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityTube.java index 2ad5346a2cf..dd3cd334677 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityTube.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityTube.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import java.security.PrivilegedActionException; @@ -54,7 +54,7 @@ import com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; -import com.sun.enterprise.security.jauth.jaspic.provider.config.PipeHelper; +import com.sun.enterprise.security.jauth.jaspic.provider.config.SoapAuthenticationService; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.xml.ws.api.message.Packet; import com.sun.xml.ws.api.pipe.NextAction; @@ -72,7 +72,7 @@ public class CommonServerSecurityTube extends AbstractFilterTubeImpl { protected static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(CommonServerSecurityTube.class); private final boolean isHttpBinding; - private PipeHelper helper; + private SoapAuthenticationService helper; // Introduced during Pipe to Tube conversion private ServerAuthContext sAC = null; @@ -82,7 +82,7 @@ public class CommonServerSecurityTube extends AbstractFilterTubeImpl { public CommonServerSecurityTube(Map props, final Tube next, boolean isHttpBinding) { super(next); props.put(PipeConstants.SECURITY_PIPE, this); - this.helper = new PipeHelper(PipeConstants.SOAP_LAYER, props, null); + this.helper = new SoapAuthenticationService(PipeConstants.SOAP_LAYER, props, null); this.isHttpBinding = isHttpBinding; } @@ -270,7 +270,7 @@ private static Subject getClientSubject(Packet p) { s = (Subject) p.invocationProperties.get(PipeConstants.CLIENT_SUBJECT); } if (s == null) { - s = PipeHelper.getClientSubject(); + s = SoapAuthenticationService.getClientSubject(); if (p != null) { p.invocationProperties.put(PipeConstants.CLIENT_SUBJECT, s); } diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java index f21731b3707..0e55e6d5719 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java @@ -37,31 +37,29 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2022] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; -import static com.sun.enterprise.security.webservices.LogUtils.BASIC_AUTH_ERROR; -import static com.sun.enterprise.security.webservices.LogUtils.CLIENT_CERT_ERROR; -import static com.sun.enterprise.security.webservices.LogUtils.EJB_SEC_CONFIG_FAILURE; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; -import static org.apache.catalina.Globals.CERTIFICATES_ATTR; -import static org.apache.catalina.Globals.SSL_CERTIFICATE_ATTR; - +import com.sun.enterprise.deployment.ServiceReferenceDescriptor; +import com.sun.enterprise.deployment.WebServiceEndpoint; +import com.sun.enterprise.security.SecurityContext; +import com.sun.enterprise.security.ee.audit.AppServerAuditManager; +import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; +import com.sun.enterprise.security.web.integration.WebPrincipal; +import com.sun.enterprise.web.WebModule; +import com.sun.web.security.RealmAdapter; +import com.sun.xml.ws.assembler.metro.dev.ClientPipelineHook; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import jakarta.security.jacc.PolicyContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.xml.soap.SOAPMessage; import java.lang.ref.WeakReference; import java.security.Principal; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; - -import jakarta.inject.Inject; -import jakarta.inject.Singleton; -import jakarta.security.jacc.PolicyContext; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.xml.soap.SOAPMessage; - import org.apache.catalina.util.Base64; import org.glassfish.webservices.EjbRuntimeEndpointInfo; import org.glassfish.webservices.SecurityService; @@ -71,18 +69,12 @@ import org.glassfish.webservices.monitoring.WebServiceEngineImpl; import org.jvnet.hk2.annotations.Service; -import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.enterprise.deployment.WebServiceEndpoint; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.security.SecurityContext; -import com.sun.enterprise.security.ee.audit.AppServerAuditManager; -import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; -import com.sun.enterprise.security.jauth.AuthConfig; -import com.sun.enterprise.security.jauth.jaspic.provider.ServerAuthConfig; -import com.sun.enterprise.security.web.integration.WebPrincipal; -import com.sun.enterprise.web.WebModule; -import com.sun.web.security.RealmAdapter; -import com.sun.xml.ws.assembler.metro.dev.ClientPipelineHook; +import static com.sun.enterprise.security.webservices.LogUtils.BASIC_AUTH_ERROR; +import static com.sun.enterprise.security.webservices.LogUtils.CLIENT_CERT_ERROR; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.WARNING; +import static org.apache.catalina.Globals.CERTIFICATES_ATTR; +import static org.apache.catalina.Globals.SSL_CERTIFICATE_ATTR; /** * @@ -101,18 +93,6 @@ public class SecurityServiceImpl implements SecurityService { @Inject private AppServerAuditManager auditManager; - @Override - public Object mergeSOAPMessageSecurityPolicies(MessageSecurityBindingDescriptor desc) { - try { - // Merge message security policy from domain.xml and sun-specific - // deployment descriptor - return ServerAuthConfig.getConfig(AuthConfig.SOAP, desc, null); - } catch (Exception ae) { - _logger.log(SEVERE, EJB_SEC_CONFIG_FAILURE, ae); - } - return null; - } - @Override public boolean doSecurity(HttpServletRequest hreq, EjbRuntimeEndpointInfo epInfo, String realmName, WebServiceContextImpl context) { // BUG2263 - Clear the value of UserPrincipal from previous request @@ -238,7 +218,7 @@ public void resetPolicyContext() { @Override public ClientPipelineHook getClientPipelineHook(ServiceReferenceDescriptor ref) { - return new ClientPipeCreator(ref); + return new ClientSecurityPipeCreator(ref); } diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/GFServerPipeCreator.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ServerSecurityPipeCreator.java similarity index 88% rename from appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/GFServerPipeCreator.java rename to appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ServerSecurityPipeCreator.java index 106dc22132f..a4302546834 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/GFServerPipeCreator.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ServerSecurityPipeCreator.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import java.util.HashMap; @@ -59,17 +59,17 @@ import com.sun.xml.wss.provider.wsit.PipeConstants; /** - * This is used by JAXWSContainer to return proper 196 security and app server monitoing pipes to + * This is used by JAXWSContainer to return proper Jakarta Authentication security and app server monitoing pipes to * the StandAlonePipeAssembler and TangoPipeAssembler */ @Service @Singleton -public class GFServerPipeCreator extends org.glassfish.webservices.ServerPipeCreator { +public class ServerSecurityPipeCreator extends org.glassfish.webservices.ServerPipeCreator { private static final String SECURITY_POLICY_NAMESPACE_URI_SUBMISSION = "http://schemas.xmlsoap.org/ws/2005/07/securitypolicy"; private static final String SECURITY_POLICY_NAMESPACE_URI_SPECVERSION = "http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702"; - public GFServerPipeCreator() { + public ServerSecurityPipeCreator() { super(); } @@ -81,20 +81,20 @@ public void init(WebServiceEndpoint ep) { @Override public Pipe createSecurityPipe(PolicyMap map, SEIModel sei, WSDLPort port, WSEndpoint owner, Pipe tail) { - HashMap props = new HashMap<>(); + HashMap properties = new HashMap<>(); - props.put(PipeConstants.POLICY, map); - props.put(PipeConstants.SEI_MODEL, sei); - props.put(PipeConstants.WSDL_MODEL, port); - props.put(PipeConstants.ENDPOINT, owner); - props.put(PipeConstants.SERVICE_ENDPOINT, endpoint); - props.put(PipeConstants.NEXT_PIPE, tail); - props.put(PipeConstants.CONTAINER, owner.getContainer()); + properties.put(PipeConstants.POLICY, map); + properties.put(PipeConstants.SEI_MODEL, sei); + properties.put(PipeConstants.WSDL_MODEL, port); + properties.put(PipeConstants.ENDPOINT, owner); + properties.put(PipeConstants.SERVICE_ENDPOINT, endpoint); + properties.put(PipeConstants.NEXT_PIPE, tail); + properties.put(PipeConstants.CONTAINER, owner.getContainer()); if (isSecurityEnabled(map, port)) { endpoint.setSecurePipeline(); } - return new CommonServerSecurityPipe(props, tail, isHttpBinding); + return new CommonServerSecurityPipe(properties, tail, isHttpBinding); } // @Override diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java index e0145fad991..85b7961082f 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java @@ -50,6 +50,7 @@ import javax.xml.namespace.QName; import jakarta.xml.soap.MimeHeaders; import jakarta.xml.soap.Name; +import jakarta.xml.soap.Node; import jakarta.xml.soap.SOAPBody; import jakarta.xml.soap.SOAPElement; import jakarta.xml.soap.SOAPEnvelope; @@ -64,7 +65,6 @@ import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; -import com.sun.enterprise.security.jauth.AuthParam; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.SOAPAuthParam; import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; @@ -144,12 +144,6 @@ public String getAuthContextID(MessageInfo messageInfo) { } - @Override - public AuthParam newSOAPAuthParam(MessageInfo messageInfo) { - return new SOAPAuthParam((SOAPMessage) messageInfo.getRequestMessage(), (SOAPMessage) messageInfo.getResponseMessage()); - - } - private String getOpName(SOAPMessage message) { if (message == null) { return null; @@ -193,11 +187,11 @@ private Name getName(SOAPMessage message) { if (envelope != null) { SOAPBody body = envelope.getBody(); if (body != null) { - Iterator it = body.getChildElements(); + Iterator it = body.getChildElements(); while (it.hasNext()) { - Object o = it.next(); - if (o instanceof SOAPElement) { - rvalue = ((SOAPElement) o).getElementName(); + Node node = it.next(); + if (node instanceof SOAPElement) { + rvalue = ((SOAPElement) node).getElementName(); break; } } @@ -211,21 +205,4 @@ private Name getName(SOAPMessage message) { } return rvalue; } - - @Override - public Object getSOAPMessage(ComponentInvocation inv) { - /* - * V3 commented getting this from EJBPolicyContextDelegate instead currently getting this from - * EjbPolicyContextDelegate which might be OK SOAPMessage soapMessage = null; MessageContext - * msgContext = inv.messageContext; - * - * if (msgContext != null) { if (msgContext instanceof SOAPMessageContext) { SOAPMessageContext smc - * = (SOAPMessageContext) msgContext; soapMessage = smc.getMessage(); } } else { soapMessage = - * inv.getSOAPMessage(); } - * - * return soapMessage; - */ - return null; - } - } diff --git a/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/SecurityService.java b/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/SecurityService.java index 0fa630f0343..bd9cc7ae766 100644 --- a/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/SecurityService.java +++ b/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/SecurityService.java @@ -37,17 +37,15 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package org.glassfish.webservices; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; import com.sun.enterprise.web.WebModule; import com.sun.xml.ws.assembler.metro.dev.ClientPipelineHook; import jakarta.servlet.http.HttpServletRequest; -import org.jvnet.hk2.annotations.Contract; - import java.security.Principal; +import org.jvnet.hk2.annotations.Contract; /** * @@ -55,9 +53,7 @@ */ @Contract public interface SecurityService { - - Object mergeSOAPMessageSecurityPolicies(MessageSecurityBindingDescriptor desc); - + boolean doSecurity(HttpServletRequest hreq, EjbRuntimeEndpointInfo ejbEndpoint, String realmName, WebServiceContextImpl context); Principal getUserPrincipal(boolean isWeb); diff --git a/core/core-bom/pom.xml b/core/core-bom/pom.xml index 303dec97362..fa8435c0d04 100644 --- a/core/core-bom/pom.xml +++ b/core/core-bom/pom.xml @@ -1,7 +1,7 @@ ../nucleus/flashlight/framework - - ../appserver/security/jaspic-provider-framework ../appserver/security/core-ee diff --git a/nucleus/admin/template/src/main/resources/config/server.policy b/nucleus/admin/template/src/main/resources/config/server.policy index 94de59288fc..78c3e6c92e8 100644 --- a/nucleus/admin/template/src/main/resources/config/server.policy +++ b/nucleus/admin/template/src/main/resources/config/server.policy @@ -119,6 +119,7 @@ grant { permission java.io.SerializablePermission "enableSubstitution"; permission java.security.SecurityPermission "getProperty.package.definition"; permission java.security.SecurityPermission "createPolicy.JavaPolicy"; + permission java.security.SecurityPermission "getProperty.authconfigprovider.factory.providers"; }; // Following grant block is only required by Connectors. If Connectors diff --git a/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java b/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java index e69de29bb2d..3d79278667d 100644 --- a/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java +++ b/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java @@ -0,0 +1,85 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) [2024] Payara Foundation and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://github.com/payara/Payara/blob/main/LICENSE.txt + * See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at glassfish/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * The Payara Foundation designates this particular file as subject to the "Classpath" + * exception as provided by the Payara Foundation in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package fish.payara.internal.notification; + +import java.util.function.BiPredicate; +import java.util.logging.Level; + +/** + * + */ +public enum EventLevel { + INFO(800), + WARNING(900), + SEVERE(1000); + + private final int severityLevel; + + public static EventLevel fromNameOrWarning (String name) { + try { + return EventLevel.valueOf(name.toUpperCase()); + } catch (Exception e) { + return WARNING; + } + } + + public static EventLevel fromLogLevel (Level level) { + if (level.intValue() <= INFO.severityLevel) { + return INFO; + } + if (level.intValue() <= WARNING.severityLevel) { + return WARNING; + } + return SEVERE; + } + + EventLevel (int severityLevel) { + this.severityLevel = severityLevel; + } + + public int getSeverityLevel () { + return severityLevel; + } + + public boolean compare (EventLevel other, BiPredicate predicate) { + return predicate.test(this.severityLevel, other.severityLevel); + } +} \ No newline at end of file diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java similarity index 99% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java rename to nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java index 10612bf5fdc..4071525d44d 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java @@ -38,11 +38,10 @@ * holder. */ // Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.ee.authorize; +package com.sun.enterprise.security; import com.sun.enterprise.config.serverbeans.JaccProvider; import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.security.SecurityLoggerInfo; import com.sun.enterprise.util.i18n.StringManager; import jakarta.inject.Inject; import jakarta.inject.Named; diff --git a/nucleus/security/core/src/main/resources/config/server.policy b/nucleus/security/core/src/main/resources/config/server.policy index b7ea5d4b130..adc4e053fec 100644 --- a/nucleus/security/core/src/main/resources/config/server.policy +++ b/nucleus/security/core/src/main/resources/config/server.policy @@ -119,6 +119,7 @@ grant { permission java.io.SerializablePermission "enableSubstitution"; permission java.security.SecurityPermission "getProperty.package.definition"; permission java.security.SecurityPermission "createPolicy.JavaPolicy"; + permission java.security.SecurityPermission "getProperty.authconfigprovider.factory.providers"; }; diff --git a/nucleus/security/services/pom.xml b/nucleus/security/services/pom.xml index 025b85eda25..6528572c126 100644 --- a/nucleus/security/services/pom.xml +++ b/nucleus/security/services/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -86,6 +86,10 @@ fish.payara.server.core.security security + + org.glassfish.epicyro + epicyro + org.glassfish.annotations logging-annotation-processor From 70835b71501d6706cdb01382ea095b018464a7e2 Mon Sep 17 00:00:00 2001 From: Kalin Chan Date: Fri, 15 Nov 2024 09:28:43 +0000 Subject: [PATCH 05/34] FISH-9630 Use UserPrincipal instead of PrincipalImpl --- .../util/ConnectionPoolObjectsUtils.java | 4 +- .../ConnectorsRecoveryResourceHandler.java | 14 +- .../context/ConnectorCallbackHandler.java | 10 +- .../work/context/WorkContextHandlerImpl.java | 9 +- .../deployment/ResourcePrincipal.java | 14 +- .../node/runtime/PrincipalNode.java | 17 ++- .../common/DescriptorPrincipalName.java | 75 +++++++++++ .../runtime/common/PrincipalNameNode.java | 6 +- .../common/PrincipalNameDescriptor.java | 14 +- .../recovery/JdbcRecoveryResourceHandler.java | 7 +- .../enterprise/security/acl/RoleMapper.java | 11 +- .../ee/auth/login/DigestLoginModule.java | 6 +- .../jacc/JaccWebAuthorizationManager.java | 16 +-- .../BaseContainerCallbackHandler.java | 10 +- .../PrincipalGroupFactoryImpl.java | 12 +- .../web/integration/WebPrincipal.java | 34 ++--- .../security/SecClientRequestInterceptor.java | 4 +- .../webservices/SecurityServiceImpl.java | 41 +++--- .../admin/rest/utils/RunCommandTest.java | 7 +- .../common/FileRealmStorageManager.java | 19 ++- .../org/glassfish/security/common/Group.java | 19 ++- .../security/common/PrincipalImpl.java | 123 ------------------ .../org/glassfish/security/common/Role.java | 18 ++- .../security/common/UserNameAndPassword.java | 116 +++++++++++++++++ .../security/common/UserPrincipal.java | 2 +- .../admin/mbeanserver/ConnectorStarter.java | 9 +- .../security/BasePasswordLoginModule.java | 15 ++- .../security/PrincipalGroupFactory.java | 6 +- .../enterprise/security/SecurityContext.java | 11 +- .../security/auth/WebAndEjbToJaasBridge.java | 8 +- .../login/ClientCertificateLoginModule.java | 20 +-- .../auth/login/ClientPasswordLoginModule.java | 18 +-- .../DistinguishedPrincipalCredential.java | 14 +- .../common/ClientSecurityContext.java | 6 +- .../security/services/common/SubjectUtil.java | 14 +- .../impl/ImpersonationServiceImpl.java | 6 +- .../authorization/SimpleAtzProviderTest.java | 7 +- .../authorization/SimpleRoleProviderTest.java | 8 +- .../services/common/SubjectUtilTest.java | 8 +- nucleus/test-utils/utils/pom.xml | 6 +- .../glassfish/tests/utils/ConfigApiTest.java | 20 +-- 41 files changed, 451 insertions(+), 333 deletions(-) create mode 100644 appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/common/DescriptorPrincipalName.java delete mode 100644 nucleus/common/common-util/src/main/java/org/glassfish/security/common/PrincipalImpl.java create mode 100644 nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserNameAndPassword.java rename nucleus/{security/core/src/main/java/com/sun/enterprise => common/common-util/src/main/java/org/glassfish}/security/common/UserPrincipal.java (95%) diff --git a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/util/ConnectionPoolObjectsUtils.java b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/util/ConnectionPoolObjectsUtils.java index cced8afa2ab..a9789b9ccea 100644 --- a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/util/ConnectionPoolObjectsUtils.java +++ b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/util/ConnectionPoolObjectsUtils.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] Payara Foundation and/or affiliates +// Portions Copyright [2019-2024] Payara Foundation and/or affiliates package com.sun.enterprise.connectors.util; @@ -333,7 +333,7 @@ public static Subject createSubject(ManagedConnectionFactory mcf, password.toCharArray()); pc.setManagedConnectionFactory(mcf); PrivilegedAction action = () -> { - tempSubject.getPrincipals().add(prin); + tempSubject.getPrincipals().add(prin.toPrincipalNameAndPassword()); tempSubject.getPrivateCredentials().add(pc); return null; }; diff --git a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/resource/recovery/ConnectorsRecoveryResourceHandler.java b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/resource/recovery/ConnectorsRecoveryResourceHandler.java index 6c31b74b18b..0035c77aa2c 100644 --- a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/resource/recovery/ConnectorsRecoveryResourceHandler.java +++ b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/resource/recovery/ConnectorsRecoveryResourceHandler.java @@ -37,8 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation] - +// Portions Copyright 2016-2024 Payara Foundation and/or its affiliates package com.sun.enterprise.resource.recovery; import com.sun.appserv.connectors.internal.api.ConnectorConstants; @@ -58,7 +57,6 @@ import com.sun.enterprise.deployment.ResourcePrincipal; import com.sun.enterprise.resource.deployer.ConnectorResourceDeployer; import com.sun.enterprise.transaction.spi.RecoveryResourceHandler; -import com.sun.enterprise.v3.server.ApplicationLoaderService; import com.sun.logging.LogDomains; import org.glassfish.connectors.config.ConnectorConnectionPool; import org.glassfish.connectors.config.ConnectorResource; @@ -68,7 +66,6 @@ import org.jvnet.hk2.config.types.Property; import jakarta.inject.Inject; -import jakarta.inject.Named; import jakarta.inject.Provider; import javax.naming.InitialContext; import javax.naming.NamingException; @@ -78,7 +75,6 @@ import jakarta.resource.spi.security.PasswordCredential; import javax.security.auth.Subject; import javax.transaction.xa.XAResource; -import java.security.Principal; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; @@ -295,9 +291,9 @@ public void loadXAResourcesAndItsConnections(List xaresList, List connList) { PasswordCredential pc = new PasswordCredential( dbUser, dbPassword.toCharArray()); pc.setManagedConnectionFactory(mcfs[i]); - Principal prin = + ResourcePrincipal prin = new ResourcePrincipal(dbUser, dbPassword); - subject.getPrincipals().add(prin); + subject.getPrincipals().add(prin.toPrincipalNameAndPassword()); subject.getPrivateCredentials().add(pc); ManagedConnection mc = mcfs[i]. createManagedConnection(subject, null); @@ -318,8 +314,8 @@ public void loadXAResourcesAndItsConnections(List xaresList, List connList) { PasswordCredential pc = new PasswordCredential( dbUser, dbPassword.toCharArray()); pc.setManagedConnectionFactory(mcf); - Principal prin = new ResourcePrincipal(dbUser, dbPassword); - subject.getPrincipals().add(prin); + ResourcePrincipal prin = new ResourcePrincipal(dbUser, dbPassword); + subject.getPrincipals().add(prin.toPrincipalNameAndPassword()); subject.getPrivateCredentials().add(pc); ManagedConnection mc = mcf.createManagedConnection(subject, null); connList.add(mc); diff --git a/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java b/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java index a259af6a339..610103cdf07 100644 --- a/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java +++ b/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/ConnectorCallbackHandler.java @@ -37,15 +37,17 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright 2024 Payara Foundation and/or affiliates package com.sun.enterprise.connectors.work.context; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.connectors.work.LogFacade; +import org.glassfish.security.common.UserNameAndPassword; import org.glassfish.logging.annotation.LogMessageInfo; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.security.common.UserPrincipal; + import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -276,12 +278,12 @@ public Callback handleCallerPrincipalCallbackWithMapping(CallerPrincipalCallback private Principal getMappedPrincipal(Principal eisPrincipal, String eisName) { Principal asPrincipal = null; if (eisPrincipal != null) { - asPrincipal = (PrincipalImpl) securityMap.get(eisPrincipal); + asPrincipal = (UserPrincipal) securityMap.get(eisPrincipal); if(logger.isLoggable(Level.FINEST)){ logger.finest("got mapped principal as [" + asPrincipal + "] for eis-group [" + eisPrincipal.getName() + "]"); } } else if (eisName != null) { - asPrincipal = ((PrincipalImpl) securityMap.get(new PrincipalImpl(eisName))); + asPrincipal = ((UserPrincipal) securityMap.get(new UserNameAndPassword(eisName))); if(logger.isLoggable(Level.FINEST)){ logger.finest("got mapped principal as [" + asPrincipal + "] for eis-group [" + eisName + "]"); } diff --git a/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/WorkContextHandlerImpl.java b/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/WorkContextHandlerImpl.java index 943a87b876a..e8f1a5eef6b 100644 --- a/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/WorkContextHandlerImpl.java +++ b/appserver/connectors/work-management/src/main/java/com/sun/enterprise/connectors/work/context/WorkContextHandlerImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright 2024 Payara Foundation and/or its affiliates package com.sun.enterprise.connectors.work.context; import com.sun.appserv.connectors.internal.api.WorkContextHandler; @@ -48,8 +48,9 @@ import org.glassfish.connectors.config.GroupMap; import org.glassfish.connectors.config.PrincipalMap; import org.glassfish.connectors.config.WorkSecurityMap; -import org.glassfish.security.common.PrincipalImpl; + import org.glassfish.security.common.Group; +import org.glassfish.security.common.UserNameAndPassword; import org.jvnet.hk2.annotations.Service; import org.glassfish.hk2.api.PerLookup; @@ -533,7 +534,7 @@ private Map getSecurityWorkContextMap(String raName) { int delimiterLocation = nameValue.indexOf("="); String eisPrincipal = nameValue.substring(0, delimiterLocation); String appserverPrincipal = nameValue.substring(delimiterLocation + 1); - eisASMap.put(new PrincipalImpl(eisPrincipal), new PrincipalImpl(appserverPrincipal)); + eisASMap.put(new UserNameAndPassword(eisPrincipal), new UserNameAndPassword(appserverPrincipal)); } } } @@ -571,7 +572,7 @@ private Map getWorkContextMap(String raName){ HashMap eisASMap = new HashMap(); for(PrincipalMap map : principalsMap){ - eisASMap.put(new PrincipalImpl(map.getEisPrincipal()), new PrincipalImpl(map.getMappedPrincipal())); + eisASMap.put(new UserNameAndPassword(map.getEisPrincipal()), new UserNameAndPassword(map.getMappedPrincipal())); } for(GroupMap map : groupsMap){ diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/ResourcePrincipal.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/ResourcePrincipal.java index 2a130353bf1..cbe86ecb520 100644 --- a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/ResourcePrincipal.java +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/ResourcePrincipal.java @@ -37,10 +37,14 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright 2024 Payara Foundation and/or its affiliates +// Portions Copyright 2024 Contributors to the Eclipse Foundation +// Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.deployment; -import org.glassfish.security.common.PrincipalImpl; +import com.sun.enterprise.deployment.runtime.common.PrincipalNameDescriptor; +import org.glassfish.security.common.UserNameAndPassword; + /** * This class encapsulates the Resource Principal information needed @@ -48,7 +52,7 @@ * * @author Tony Ng */ -public class ResourcePrincipal extends PrincipalImpl { +public class ResourcePrincipal extends PrincipalNameDescriptor { private String password; static private final int NULL_HASH_CODE = Integer.valueOf(1).hashCode(); @@ -93,4 +97,8 @@ private boolean isEqual(Object a, Object b) { } } + public UserNameAndPassword toPrincipalNameAndPassword() { + return new UserNameAndPassword(getName(), password); + } + } diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/PrincipalNode.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/PrincipalNode.java index e9bd268a819..b2d860853b2 100644 --- a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/PrincipalNode.java +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/PrincipalNode.java @@ -37,13 +37,16 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright 2024 Payara Foundation and/or its affiliates +// Portions Copyright 2024 Contributors to the Eclipse Foundation +// Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.deployment.node.runtime; import com.sun.enterprise.deployment.node.DeploymentDescriptorNode; import com.sun.enterprise.deployment.node.XMLElement; +import com.sun.enterprise.deployment.runtime.common.PrincipalNameDescriptor; import com.sun.enterprise.deployment.xml.RuntimeTagNames; -import org.glassfish.security.common.PrincipalImpl; + import org.w3c.dom.Node; /** @@ -52,14 +55,14 @@ * @author Jerome Dochez * @version */ -public class PrincipalNode extends DeploymentDescriptorNode { +public class PrincipalNode extends DeploymentDescriptorNode { - PrincipalImpl principal=null; + PrincipalNameDescriptor principal=null; /** * @return the descriptor instance to associate with this XMLNode */ - public Object getDescriptor() { + public PrincipalNameDescriptor getDescriptor() { return principal; } @@ -72,7 +75,7 @@ public Object getDescriptor() { public void setElementValue(XMLElement element, String value) { if (RuntimeTagNames.NAME.equals(element.getQName())) { - principal = new PrincipalImpl(value); + principal = new PrincipalNameDescriptor(value); } else super.setElementValue(element, value); } @@ -84,7 +87,7 @@ public void setElementValue(XMLElement element, String value) { * @param the descriptor to write * @return the DOM tree top node */ - public Node writeDescriptor(Node parent, String nodeName, PrincipalImpl descriptor) { + public Node writeDescriptor(Node parent, String nodeName, PrincipalNameDescriptor descriptor) { Node principal = appendChild(parent, nodeName); appendTextChild(principal, RuntimeTagNames.NAME, descriptor.getName()); return principal; diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/common/DescriptorPrincipalName.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/common/DescriptorPrincipalName.java new file mode 100644 index 00000000000..3fa8107baa5 --- /dev/null +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/common/DescriptorPrincipalName.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2024 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package com.sun.enterprise.deployment.node.runtime.common; + +import java.io.Serializable; +import java.security.Principal; +import java.util.Objects; + +import org.glassfish.security.common.UserPrincipal; + +/** + * {@link Principal} loaded from XML descriptor. + * When the equals method is used, it compares just principal names and that the other object + * is an {@link Principal} instance too. + */ +// Must be UserPrincipal, because RoleMapper.internalAssignRole knows just that and Group. +public class DescriptorPrincipalName implements UserPrincipal, Serializable { + + private static final long serialVersionUID = -640182254691955451L; + + private final String name; + + /** + * @param name must not be null. + */ + public DescriptorPrincipalName(String name) { + this.name = Objects.requireNonNull(name, "XML principal-name element must not be null."); + } + + + @Override + public String getName() { + return name; + } + + + @Override + public int hashCode() { + return name.hashCode(); + } + + + /** + * We match user principals just by name. + * This is used in Jakarta Security to resolve authorisation. + */ + @Override + public boolean equals(Object o) { + if (o instanceof Principal) { + Principal other = (Principal) o; + return getName().equals(other.getName()); + } + return false; + } + + + @Override + public String toString() { + return getClass().getSimpleName() + "[" + getName() + "]"; + } +} diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/common/PrincipalNameNode.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/common/PrincipalNameNode.java index c1235945724..ce794be9ad6 100644 --- a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/common/PrincipalNameNode.java +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/runtime/common/PrincipalNameNode.java @@ -37,7 +37,9 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright 2024 Payara Foundation and/or its affiliates +// Portions Copyright 2024 Contributors to the Eclipse Foundation +// Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.deployment.node.runtime.common; import com.sun.enterprise.deployment.node.XMLElement; @@ -57,7 +59,7 @@ public class PrincipalNameNode extends RuntimeDescriptorNode { @Override protected PrincipalNameDescriptor createDescriptor() { - return new PrincipalNameDescriptor(); + return new PrincipalNameDescriptor(null); } diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/common/PrincipalNameDescriptor.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/common/PrincipalNameDescriptor.java index 6efb53ae900..666aeeeca5f 100644 --- a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/common/PrincipalNameDescriptor.java +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/common/PrincipalNameDescriptor.java @@ -37,11 +37,14 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] +// Portions Copyright 2024 Contributors to the Eclipse Foundation +// Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.deployment.runtime.common; import java.security.Principal; +import com.sun.enterprise.deployment.node.runtime.common.DescriptorPrincipalName; import org.glassfish.deployment.common.Descriptor; /** @@ -52,19 +55,22 @@ public class PrincipalNameDescriptor extends Descriptor { private static final long serialVersionUID = 884693766288296132L; - private static final String DEFAULT_CLASSNAME = "org.glassfish.security.common.PrincipalImpl"; - + private String principalName; private String className; private transient ClassLoader classLoader; + public PrincipalNameDescriptor(String principalName) { + this.principalName = principalName; + } + public String getName() { return principalName; } public String getClassName() { if (className == null) { - return DEFAULT_CLASSNAME; + return DescriptorPrincipalName.class.getName(); } return className; diff --git a/appserver/jdbc/jdbc-runtime/src/main/java/org/glassfish/jdbc/recovery/JdbcRecoveryResourceHandler.java b/appserver/jdbc/jdbc-runtime/src/main/java/org/glassfish/jdbc/recovery/JdbcRecoveryResourceHandler.java index 57a4a304c8a..a2811e26a78 100644 --- a/appserver/jdbc/jdbc-runtime/src/main/java/org/glassfish/jdbc/recovery/JdbcRecoveryResourceHandler.java +++ b/appserver/jdbc/jdbc-runtime/src/main/java/org/glassfish/jdbc/recovery/JdbcRecoveryResourceHandler.java @@ -37,11 +37,10 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation] +// Portions Copyright 2016-2024 Payara Foundation and/or its affiliates package org.glassfish.jdbc.recovery; -import java.security.Principal; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -287,8 +286,8 @@ public void loadXAResourcesAndItsConnections(List xaresList, List connList) { PasswordCredential pc = new PasswordCredential( dbUser, dbPassword.toCharArray()); pc.setManagedConnectionFactory(fac); - Principal prin = new ResourcePrincipal(dbUser, dbPassword); - subject.getPrincipals().add(prin); + ResourcePrincipal prin = new ResourcePrincipal(dbUser, dbPassword); + subject.getPrincipals().add(prin.toPrincipalNameAndPassword()); subject.getPrivateCredentials().add(pc); ManagedConnection mc = fac.createManagedConnection(subject, null); connList.add(mc); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/acl/RoleMapper.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/acl/RoleMapper.java index 1f179f7d785..9ec1efc7404 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/acl/RoleMapper.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/acl/RoleMapper.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] // Portions Copyright [2024] Contributors to the Eclipse Foundation // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license @@ -66,7 +66,6 @@ import javax.security.auth.Subject; import com.sun.enterprise.security.auth.login.DistinguishedPrincipalCredential; -import com.sun.security.auth.UserPrincipal; import org.glassfish.api.admin.ServerEnvironment; import org.glassfish.deployment.common.RootDeploymentDescriptor; import org.glassfish.deployment.common.SecurityRoleMapper; @@ -74,7 +73,7 @@ import org.glassfish.internal.data.ApplicationInfo; import org.glassfish.internal.data.ApplicationRegistry; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; + import org.glassfish.security.common.Role; import com.sun.enterprise.config.serverbeans.SecurityService; @@ -82,6 +81,8 @@ import com.sun.enterprise.deployment.BundleDescriptor; import com.sun.enterprise.security.common.AppservAccessController; import com.sun.logging.LogDomains; +import org.glassfish.security.common.UserNameAndPassword; +import org.glassfish.security.common.UserPrincipal; /** * This class maintains a mapping of users and groups to application specific roles. @@ -159,8 +160,8 @@ public RoleMapper(RoleMapper r) { Enumeration users = r.getUsersAssignedTo(new Role(role)); Set usersToRole = new HashSet(); for (; users.hasMoreElements();) { - PrincipalImpl gp = (PrincipalImpl) users.nextElement(); - usersToRole.add(new PrincipalImpl(gp.getName())); + UserPrincipal gp = (UserPrincipal) users.nextElement(); + usersToRole.add(new UserNameAndPassword(gp.getName())); addRoleToPrincipal(gp, role); } this.roleToPrincipal.put(role, usersToRole); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java index 558144aaa21..5d070555388 100755 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/auth/login/DigestLoginModule.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.ee.auth.login; import static com.sun.logging.LogDomains.SECURITY_LOGGER; @@ -56,9 +56,9 @@ import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; +import org.glassfish.security.common.UserPrincipal; import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; import com.sun.enterprise.security.PrincipalGroupFactory; import com.sun.enterprise.security.auth.digest.api.DigestAlgorithmParameter; @@ -76,7 +76,7 @@ public abstract class DigestLoginModule implements LoginModule { protected boolean _succeeded; protected boolean _commitSucceeded; - protected PrincipalImpl _userPrincipal; + protected UserPrincipal _userPrincipal; private DigestCredentials digestCredentials; private Subject subject; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java index ca9558ac5e2..81cefd76b61 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java @@ -55,6 +55,7 @@ import com.sun.enterprise.security.SecurityServicesUtil; import com.sun.enterprise.security.WebSecurityDeployerProbeProvider; import com.sun.enterprise.security.audit.AuditManager; +import org.glassfish.security.common.UserNameAndPassword; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; import com.sun.enterprise.security.jacc.cache.CachedPermission; @@ -80,10 +81,9 @@ import jakarta.servlet.http.HttpServletRequest; import org.glassfish.deployment.common.SecurityRoleMapperFactory; import org.glassfish.exousia.AuthorizationService; -import org.glassfish.exousia.mapping.DefaultPrincipalMapper; import org.glassfish.internal.api.ServerContext; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; + import org.glassfish.security.common.Role; import javax.security.auth.Subject; @@ -220,7 +220,7 @@ public JaccWebAuthorizationManager(WebBundleDescriptor webBundleDescriptor, Serv GlassFishToExousiaConverter.getConstraintsFromBundle(webBundleDescriptor), webBundleDescriptor.getRoles() .stream() - .map(PrincipalImpl::getName) + .map(Role::getName) .collect(Collectors.toSet()), webBundleDescriptor.isDenyUncoveredHttpMethods(), GlassFishToExousiaConverter.getSecurityRoleRefsFromBundle(webBundleDescriptor)); @@ -434,8 +434,8 @@ public boolean hasRoleRefPermission(String servletName, String role, Principal p return isGranted; } - /* If the principal set contains CallerPrincipal, replace it with PrincipalImpl. - This is because CallerPrincipal isn't equal to PrincipalImpl and doesn't imply it. + /* If the principal set contains CallerPrincipal, replace it with UserPrincipal. + This is because CallerPrincipal isn't equal to UserPrincipal and doesn't imply it. CallerPrincipal doesn't even implement equals method, so 2 CallerPrincipals with the same name are not equal. Because CallerPrincipal is from Jakarta EE, we can't change it. */ @@ -445,7 +445,7 @@ private boolean checkPermissionForModifiedPrincipalSet(Set principalS for (Principal p : principalSetFromSecurityContext) { if (p instanceof CallerPrincipal) { principalSetContainsCallerPrincipal = true; - modifiedPrincipalSet.add(new PrincipalImpl(p.getName())); + modifiedPrincipalSet.add(new UserNameAndPassword(p.getName())); } else { modifiedPrincipalSet.add(p); } @@ -524,7 +524,7 @@ private void initialise(String appName) throws PolicyContextException { if (roleMappings != null) { for (SecurityRoleMapping roleMapping : roleMappings) { for (String principal : roleMapping.getPrincipalName()) { - webSecurityManagerFactory.addAdminPrincipal(principal, realmName, new PrincipalImpl(principal)); + webSecurityManagerFactory.addAdminPrincipal(principal, realmName, new UserNameAndPassword(principal)); } for (String group : roleMapping.getGroupNames()) { webSecurityManagerFactory.addAdminGroup(group, realmName, new Group(group)); @@ -541,7 +541,7 @@ private void initialise(String appName) throws PolicyContextException { } for (String principal : roleAssignment.getPrincipalNames()) { - webSecurityManagerFactory.addAdminPrincipal(principal, realmName, new PrincipalImpl(principal)); + webSecurityManagerFactory.addAdminPrincipal(principal, realmName, new UserNameAndPassword(principal)); } } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/BaseContainerCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/BaseContainerCallbackHandler.java index 41821757fb8..df643ab1208 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/BaseContainerCallbackHandler.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/BaseContainerCallbackHandler.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright 2016-2022 Payara Foundation and/or its affiliates +// Portions Copyright 2016-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license /* * BaseContainerCallbackHandler.java @@ -54,6 +54,7 @@ import com.sun.enterprise.security.auth.login.common.LoginException; import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; import com.sun.enterprise.security.common.AppservAccessController; +import org.glassfish.security.common.UserNameAndPassword; import com.sun.enterprise.security.jaspic.config.CallbackHandlerConfig; import com.sun.enterprise.security.jaspic.config.HandlerContext; import com.sun.enterprise.security.ssl.SSLUtils; @@ -71,7 +72,6 @@ import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; import org.glassfish.security.common.MasterPassword; -import org.glassfish.security.common.PrincipalImpl; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; @@ -221,7 +221,7 @@ protected void processCallback(Callback callback) throws UnsupportedCallbackExce * * A. handling of CPCB by CBH: * - * 1. handling of CPC by CBH modifies subject a. constructs principalImpl if called by name b. uses LoginContextDriver + * 1. handling of CPC by CBH modifies subject a. constructs UserPrincipal if called by name b. uses LoginContextDriver * to add group principals for name c. puts principal in principal set, and DPC in public credentials * * B. construction of WebPrincipal by RealmAdapter (occurs after SAM uses CBH to set other than an unauthenticated @@ -264,7 +264,7 @@ public Boolean run() { Set distinguishedCreds = wps.getPublicCredentials(DistinguishedPrincipalCredential.class); if (distinguishedCreds.size() == 1) { for (DistinguishedPrincipalCredential cred : distinguishedCreds) { - if (cred.getPrincipal().equals(callerPrincipal)) { + if (cred.principal().equals(callerPrincipal)) { hasObject = true; } } @@ -383,7 +383,7 @@ private void processCallerPrincipal(CallerPrincipalCallback callerPrincipalCallb if (isCertRealm) { principal = new X500Principal(callerPrincipalCallback.getName()); } else { - principal = new PrincipalImpl(callerPrincipalCallback.getName()); + principal = new UserNameAndPassword(callerPrincipalCallback.getName()); } } else { // Jakarta Authentication unauthenticated caller principal diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java index 206dd3f6314..98e894ae925 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2017-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] /* * PrincipalGroupFactory.java * @@ -48,9 +48,11 @@ import java.lang.ref.WeakReference; +import org.glassfish.security.common.UserNameAndPassword; import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.security.common.UserPrincipal; + import org.jvnet.hk2.annotations.Service; import com.sun.enterprise.security.PrincipalGroupFactory; @@ -65,10 +67,10 @@ public class PrincipalGroupFactoryImpl implements PrincipalGroupFactory { private static WeakReference webSecurityManagerFactory = new WeakReference(null); @Override - public PrincipalImpl getPrincipalInstance(String name, String realm) { - PrincipalImpl principal = (PrincipalImpl) getWebSecurityManagerFactory().getAdminPrincipal(name, realm); + public UserPrincipal getPrincipalInstance(String name, String realm) { + UserPrincipal principal = (UserPrincipal) getWebSecurityManagerFactory().getAdminPrincipal(name, realm); if (principal == null) { - principal = new PrincipalImpl(name); + principal = new UserNameAndPassword(name); } return principal; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/WebPrincipal.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/WebPrincipal.java index 511e2930e6c..cf13bc8ca26 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/WebPrincipal.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/WebPrincipal.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.web.integration; import java.security.Principal; @@ -46,14 +46,14 @@ import com.sun.enterprise.security.auth.realm.certificate.OID; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.security.common.UserNameAndPassword; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityContextProxy; import javax.security.auth.x500.X500Principal; -public class WebPrincipal extends PrincipalImpl implements SecurityContextProxy { +public class WebPrincipal extends UserNameAndPassword implements SecurityContextProxy { private static final long serialVersionUID = 1L; @@ -63,11 +63,16 @@ public class WebPrincipal extends PrincipalImpl implements SecurityContextProxy private final SecurityContext securityContext; private Principal customPrincipal; + public WebPrincipal(UserNameAndPassword principal, SecurityContext context) { + super(principal.getName(), principal.getPassword()); + this.useCertificate = false; + this.securityContext = context; + } + + public WebPrincipal(Principal principal, SecurityContext context) { super(principal.getName()); - if (!(principal instanceof PrincipalImpl)) { - customPrincipal = principal; - } + this.customPrincipal = principal; this.useCertificate = false; this.securityContext = context; } @@ -98,11 +103,6 @@ public WebPrincipal(X509Certificate[] certificates, SecurityContext context, boo this.securityContext = context; } - public char[] getPassword() { - // Copy the password to another reference and return the reference - return password == null ? null : Arrays.copyOf(password, password.length); - } - public X509Certificate[] getCertificates() { return certificates; } @@ -116,14 +116,6 @@ public SecurityContext getSecurityContext() { return securityContext; } - @Override - public String getName() { - if (customPrincipal == null) { - return super.getName(); - } - - return customPrincipal.getName(); - } @Override public boolean equals(Object another) { @@ -161,13 +153,13 @@ private static String getPrincipalName(X509Certificate[] certificates, SecurityC // Use the principal name from the security context, ensuring the context caller principal and // the web principal have the same name. // - // This will typically be an org.glassfish.security.common.PrincipalImpl which as its name has + // This will typically be an org.glassfish.security.common.UserPrincipal which as its name has // the name obtained from javax.security.auth.x500.X500Principal, which is obtained from // certificates[0].getSubjectX500Principal(). // // I.e. the internal principal in the security context is effectively created via: // - // new PrincipalImpl(certificates[0].getSubjectX500Principal()); + // new UserNameAndPassword(certificates[0].getSubjectX500Principal()); // // The format of the X.500 distinguished name (DN) returned here will then be RFC 2253, e.g. // C=UK,ST=lak,L=zak,O=kaz,OU=bar,CN=lfoo diff --git a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecClientRequestInterceptor.java b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecClientRequestInterceptor.java index 53155a9c8ea..b85556d60e0 100644 --- a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecClientRequestInterceptor.java +++ b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecClientRequestInterceptor.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright 2018-2022 Payara Foundation and/or its affiliates +// Portions Copyright 2018-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.iiop.security; @@ -248,7 +248,7 @@ private IdentityToken createIdToken(java.lang.Object cred, Class cls, ORB orb) t // Create a DER encoding of the principal name as a GSSUPName - realm is not currently factored into the // parsing of the principal name from the IdentityToken so is left blank. - GSSUPName gssupName = new GSSUPName(distinguishedPrincipalCredential.getPrincipal().getName(), ""); + GSSUPName gssupName = new GSSUPName(distinguishedPrincipalCredential.principal().getName(), ""); byte[] expname = gssupName.getExportedName(); GSS_NT_ExportedNameHelper.insert(any, expname); diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java index f21731b3707..4b52eaa7c82 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java @@ -37,7 +37,9 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2022] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +// Portions Copyright [2024] Contributors to the Eclipse Foundation +// Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.security.webservices; import static com.sun.enterprise.security.webservices.LogUtils.BASIC_AUTH_ERROR; @@ -52,8 +54,6 @@ import java.lang.ref.WeakReference; import java.security.Principal; import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; import java.util.logging.Logger; import jakarta.inject.Inject; @@ -63,6 +63,7 @@ import jakarta.xml.soap.SOAPMessage; import org.apache.catalina.util.Base64; +import org.glassfish.security.common.UserNameAndPassword; import org.glassfish.webservices.EjbRuntimeEndpointInfo; import org.glassfish.webservices.SecurityService; import org.glassfish.webservices.WebServiceContextImpl; @@ -144,10 +145,9 @@ public boolean doSecurity(HttpServletRequest hreq, EjbRuntimeEndpointInfo epInfo return false; } - List usernamePassword = parseUsernameAndPassword(rawAuthInfo); + UserNameAndPassword usernamePassword = parseUsernameAndPassword(rawAuthInfo); if (usernamePassword != null) { - webPrincipal = new WebPrincipal((String) usernamePassword.get(0), (char[]) usernamePassword.get(1), - SecurityContext.init()); + webPrincipal = new WebPrincipal(usernamePassword, SecurityContext.init()); } else { _logger.log(WARNING, BASIC_AUTH_ERROR, endpointName); } @@ -242,21 +242,24 @@ public ClientPipelineHook getClientPipelineHook(ServiceReferenceDescriptor ref) } - private List parseUsernameAndPassword(String rawAuthInfo) { + private UserNameAndPassword parseUsernameAndPassword(String rawAuthInfo) { + if (rawAuthInfo == null || !rawAuthInfo.startsWith("Basic ")) { + return null; + } - List usernamePassword = null; - if ((rawAuthInfo != null) && (rawAuthInfo.startsWith("Basic "))) { - String authString = rawAuthInfo.substring(6).trim(); - // Decode and parse the authorization credentials - String unencoded = new String(Base64.decode(authString.getBytes())); - int colon = unencoded.indexOf(':'); - if (colon > 0) { - usernamePassword = new ArrayList(); - usernamePassword.add(unencoded.substring(0, colon).trim()); - usernamePassword.add(unencoded.substring(colon + 1).trim().toCharArray()); - } + String authString = rawAuthInfo.substring(6).trim(); + + // Decode and parse the authorization credentials + String unencoded = new String(Base64.decode(authString.getBytes())); + int colon = unencoded.indexOf(':'); + + if (colon <= 0) { + return null; } - return usernamePassword; + + String user = unencoded.substring(0, colon).trim(); + String password = unencoded.substring(colon + 1).trim(); + return new UserNameAndPassword(user, password); } private void sendAuthenticationEvents(boolean success, String url, Principal principal) { diff --git a/nucleus/admin/rest/rest-service/src/test/java/fish/payara/admin/rest/utils/RunCommandTest.java b/nucleus/admin/rest/rest-service/src/test/java/fish/payara/admin/rest/utils/RunCommandTest.java index 3f65b2422a2..a4725b6fade 100644 --- a/nucleus/admin/rest/rest-service/src/test/java/fish/payara/admin/rest/utils/RunCommandTest.java +++ b/nucleus/admin/rest/rest-service/src/test/java/fish/payara/admin/rest/utils/RunCommandTest.java @@ -1,7 +1,7 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * - * Copyright (c) [2019-2021] Payara Foundation and/or its affiliates. All rights reserved. + * Copyright (c) [2019-2024] Payara Foundation and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development @@ -76,6 +76,7 @@ import org.glassfish.api.admin.ParameterMap; import org.glassfish.api.admin.Payload; import org.glassfish.api.admin.ProgressStatus; +import org.glassfish.security.common.UserNameAndPassword; import org.jvnet.hk2.config.ConfigBeanProxy; import org.jvnet.hk2.config.TransactionFailure; import org.glassfish.hk2.api.DynamicConfiguration; @@ -89,7 +90,7 @@ import org.glassfish.hk2.utilities.ServiceLocatorUtilities; import org.glassfish.internal.api.Globals; import org.glassfish.internal.api.Target; -import org.glassfish.security.common.PrincipalImpl; + import org.glassfish.server.ServerEnvironmentImpl; import org.junit.Before; import org.junit.Test; @@ -136,7 +137,7 @@ public void setUp() { @Test public void testAdminAudit() { Subject testSubject = new Subject(); - testSubject.getPrincipals().add(new PrincipalImpl("testuser")); + testSubject.getPrincipals().add(new UserNameAndPassword("testuser")); RestActionReporter commandResult = ResourceUtil.runCommand("get-admin-audit-configuration", new ParameterMap(), testSubject); Assert.assertTrue(commandResult.isSuccess()); diff --git a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/FileRealmStorageManager.java b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/FileRealmStorageManager.java index 919fb93f673..f2bf05cdd79 100644 --- a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/FileRealmStorageManager.java +++ b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/FileRealmStorageManager.java @@ -38,6 +38,8 @@ * holder. */ // Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] +// Portions Copyright 2024 Contributors to the Eclipse Foundation +// Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package org.glassfish.security.common; @@ -52,13 +54,17 @@ import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; +import java.io.Serial; +import java.io.Serializable; import java.nio.charset.StandardCharsets; +import java.nio.file.attribute.UserPrincipal; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; +import java.util.Objects; import java.util.Set; import java.util.StringTokenizer; @@ -726,8 +732,9 @@ private static void setPassword(User user, char[] password) throws IllegalArgume /** * Represents a FileRealm user. */ - public static class User extends PrincipalImpl { + public static class User implements UserPrincipal, Serializable { + @Serial private static final long serialVersionUID = 5310671725001301966L; private String[] groups; @@ -735,13 +742,14 @@ public static class User extends PrincipalImpl { private byte[] salt; private byte[] hash; private String algo; + private final String name; /** * Constructor. * */ public User(String name) { - super(name); + this.name = Objects.requireNonNull(name); } /** @@ -755,7 +763,7 @@ public User(String name) { * */ public User(String name, String[] groups, String realm, byte[] salt, byte[] hash, String algo) { - super(name); + this.name = Objects.requireNonNull(name); this.groups = groups; this.realm = realm; this.hash = hash; @@ -809,6 +817,11 @@ public int hashCode() { return hc; } + @Override + public String getName() { + return name; + } + /** * Returns salt value. * diff --git a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/Group.java b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/Group.java index 8843f2a3754..f120a267349 100644 --- a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/Group.java +++ b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/Group.java @@ -37,9 +37,16 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +// Portions Copyright 2024 Contributors to the Eclipse Foundation +// Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license + package org.glassfish.security.common; +import java.io.Serializable; +import java.security.Principal; +import java.util.Objects; + /** * This class implements the EJB concept of a Group. A Group is a privilege attribute that several * Principals share. Or, in in other words, several Principals belong to a same group. @@ -48,15 +55,16 @@ * * @author Harish Prabandham */ -public class Group extends PrincipalImpl { +public class Group implements Principal, Serializable { private static final long serialVersionUID = -3087471149205106412L; + private final String name; /** * @param name - a name of the group */ public Group(String name) { - super(name); + this.name = Objects.requireNonNull(name); } @Override @@ -72,4 +80,9 @@ public boolean equals(Object other) { public int hashCode() { return getName().hashCode(); } + + @Override + public String getName() { + return name; + } } diff --git a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/PrincipalImpl.java b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/PrincipalImpl.java deleted file mode 100644 index 2eca0fc5605..00000000000 --- a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/PrincipalImpl.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] - -package org.glassfish.security.common; - -import java.io.Serializable; -import java.security.Principal; - -/** - * This class implements the principal interface. - * - * @author Harish Prabandham - */ -public class PrincipalImpl implements Principal, Serializable { - - private static final long serialVersionUID = 373616283817165845L; - - /** - * @serial - */ - private final String name; - - /** - * Construct a principal from a string user name. - * - * @param user The string form of the principal name. - */ - public PrincipalImpl(String user) { - this.name = user; - } - - /** - * This function returns true if the object passed matches the principal represented in this implementation - * - * @param another the Principal to compare with. - * @return true if the Principal passed is the same as that encapsulated in this object, false otherwise - */ - @Override - public boolean equals(Object another) { - // XXX for bug 4889642: if groupA and userA have - // the same name, then groupA.equals(userA) return false - // BUT userA.equals(groupA) return "true" - if (another instanceof Group) { - return false; - } - - if (another instanceof PrincipalImpl) { - Principal p = (Principal) another; - return getName().equals(p.getName()); - } - - return false; - } - - /** - * Prints a stringified version of the principal. - * - * @return A java.lang.String object returned by the method getName() - */ - @Override - public String toString() { - return getName(); - } - - /** - * Returns the hashcode for this Principal object - * - * @return a hashcode for the principal. - */ - @Override - public int hashCode() { - return name.hashCode(); - } - - /** - * Gets the name of the Principal as a java.lang.String - * - * @return the name of the principal. - */ - @Override - public String getName() { - return name; - } - -} diff --git a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/Role.java b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/Role.java index 0391cd3c202..e637db6af56 100644 --- a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/Role.java +++ b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/Role.java @@ -37,10 +37,16 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +// Portions Copyright 2024 Contributors to the Eclipse Foundation +// Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package org.glassfish.security.common; +import java.io.Serializable; +import java.security.Principal; +import java.util.Objects; + /** * In EJBs, ACL checking is done using the Roles. Roles are an abstraction of an application specific Logical * Principals. These Principals do not have any properties of Principals within a Security Domain (or Realm). They @@ -48,15 +54,16 @@ * * @author Harish Prabandham */ -public class Role extends PrincipalImpl { +public class Role implements Principal, Serializable { private static final long serialVersionUID = -7801565721107580516L; private String description; + private final String name; /** Creates a new Role with a given name */ public Role(String name) { - super(name); + this.name = Objects.requireNonNull(name); } @Override @@ -74,6 +81,11 @@ public int hashCode() { return getName().hashCode(); } + @Override + public String getName() { + return name; + } + public String getDescription() { if (this.description == null) { this.description = ""; diff --git a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserNameAndPassword.java b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserNameAndPassword.java new file mode 100644 index 00000000000..18c0235652e --- /dev/null +++ b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserNameAndPassword.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2022 Eclipse Foundation and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.security.common; + +import java.util.Arrays; +import java.util.Objects; + +/** + * Concrete implementation of {@link UserPrincipal} with username and password. + *
    + *
  • The password is not mandatory, it can be null. + *
  • Two instances are equal if they have the same name and the same password. + *
+ * + * @author David Matejcek + */ +public class UserNameAndPassword implements UserPrincipal { + + private static final long serialVersionUID = 1L; + private final String name; + private final char[] password; + private final int hashCode; + + /** + * @param name non-null name + */ + public UserNameAndPassword(String name) { + this(name, (char[]) null); + } + + + /** + * @param name non-null name + * @param password can be null. + */ + public UserNameAndPassword(String name, String password) { + this(name, password == null ? null : password.toCharArray()); + } + + + /** + * @param name non-null name + * @param password can be null. + */ + public UserNameAndPassword(String name, char[] password) { + this.name = Objects.requireNonNull(name); + this.password = password == null ? null : Arrays.copyOf(password, password.length); + this.hashCode = 31 * name.hashCode() + Arrays.hashCode(this.password); + } + + + /** + * @return never null. + */ + @Override + public final String getName() { + return name; + } + + + /** + * @return password as a string, can be null. + */ + public final String getStringPassword() { + return password == null ? null : new String(password); + } + + + /** + * @return password as a string, can be null. + */ + public final char[] getPassword() { + return password == null ? null : Arrays.copyOf(password, password.length); + } + + + /** + * @return true if the object is an instance of {@link UserNameAndPassword} and has the same + * name and the same password. + */ + @Override + public boolean equals(Object o) { + if (o instanceof UserNameAndPassword) { + UserNameAndPassword another = (UserNameAndPassword) o; + return Objects.equals(getName(), another.getName()) + && Objects.equals(getPassword(), another.getPassword()); + } + return false; + } + + + @Override + public int hashCode() { + return this.hashCode; + } + + + @Override + public String toString() { + return "UserNameAndPassword[" + this.name + "]"; + } +} \ No newline at end of file diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/UserPrincipal.java b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserPrincipal.java similarity index 95% rename from nucleus/security/core/src/main/java/com/sun/enterprise/security/common/UserPrincipal.java rename to nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserPrincipal.java index 4519efed810..41f5bc61061 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/UserPrincipal.java +++ b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserPrincipal.java @@ -14,7 +14,7 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package com.sun.enterprise.security.common; +package org.glassfish.security.common; import java.io.Serializable; import java.security.Principal; diff --git a/nucleus/common/mbeanserver/src/main/java/org/glassfish/admin/mbeanserver/ConnectorStarter.java b/nucleus/common/mbeanserver/src/main/java/org/glassfish/admin/mbeanserver/ConnectorStarter.java index 140bb66e300..26480222a35 100644 --- a/nucleus/common/mbeanserver/src/main/java/org/glassfish/admin/mbeanserver/ConnectorStarter.java +++ b/nucleus/common/mbeanserver/src/main/java/org/glassfish/admin/mbeanserver/ConnectorStarter.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2017] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package org.glassfish.admin.mbeanserver; @@ -53,8 +53,9 @@ import java.util.Set; import javax.management.remote.JMXPrincipal; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; + import org.glassfish.security.common.Role; +import org.glassfish.security.common.UserPrincipal; /** Start and stop JMX connectors, base class. @@ -124,8 +125,8 @@ public Subject authenticate(Object credentials) { Subject adminSubject = controller.authenticate(credentials); if (adminSubject != null) { // extract the principal name and create a JMXPrincipal and add to the subject PAYARA-1251 - Set principals = adminSubject.getPrincipals(PrincipalImpl.class); - for (PrincipalImpl principal : principals) { + Set principals = adminSubject.getPrincipals(UserPrincipal.class); + for (UserPrincipal principal : principals) { if (!(principal instanceof Group) && !(principal instanceof Role)) { adminSubject.getPrincipals().add(new JMXPrincipal(principal.getName())); } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java index 677f8758199..886ab59552a 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; import static com.sun.enterprise.security.SecurityLoggerInfo.noPwdCredentialProvidedError; @@ -59,9 +59,10 @@ import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; +import org.glassfish.security.common.UserNameAndPassword; +import org.glassfish.security.common.UserPrincipal; import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; import com.sun.enterprise.security.auth.login.LoginCallbackHandler; import com.sun.enterprise.security.auth.login.common.PasswordCredential; @@ -98,7 +99,7 @@ public abstract class BasePasswordLoginModule implements LoginModule { // the authentication status protected boolean _succeeded; protected boolean _commitSucceeded; - protected PrincipalImpl _userPrincipal; + protected UserPrincipal _userPrincipal; protected String[] _groupsList; /** @@ -150,7 +151,7 @@ public final boolean login() throws LoginException { * Commit the authentication. * *

- * Commit is called after all necessary login modules have succeeded. It adds (if not present) a PrincipalImpl principal + * Commit is called after all necessary login modules have succeeded. It adds (if not present) a UserPrincipal principal * and a LocalCredentials public credential to the Subject. * * @throws LoginException If commit fails. @@ -163,13 +164,13 @@ public boolean commit() throws LoginException { } // Add a Principal (authenticated identity) to the Subject - // Assume the user we authenticated is the PrincipalImpl [RI] + // Assume the user we authenticated is the UserPrincipal [RI] String realmName = _currentRealm.getName(); PrincipalGroupFactory factory = Globals.getDefaultHabitat().getService(PrincipalGroupFactory.class); if (factory != null) { _userPrincipal = factory.getPrincipalInstance(getUsername(), realmName); } else { - _userPrincipal = new PrincipalImpl(getUsername()); + _userPrincipal = new UserNameAndPassword(getUsername()); } Set principals = _subject.getPrincipals(); @@ -444,7 +445,7 @@ public boolean isCommitSucceeded() { /** * @return the UserPrincipal - for backward compatibility */ - public PrincipalImpl getUserPrincipal() { + public UserPrincipal getUserPrincipal() { return _userPrincipal; } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java index 01ecb60710c..e5bc4861e7f 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PrincipalGroupFactory.java @@ -37,11 +37,11 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2017-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; +import org.glassfish.security.common.UserPrincipal; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; import org.jvnet.hk2.annotations.Contract; /** @@ -50,7 +50,7 @@ @Contract public interface PrincipalGroupFactory { - PrincipalImpl getPrincipalInstance(String name, String realm); + UserPrincipal getPrincipalInstance(String name, String realm); Group getGroupInstance(String name, String realm); } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java index df40b6cff41..74653006bfb 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; import static com.sun.enterprise.security.SecurityLoggerInfo.defaultSecurityContextError; @@ -64,7 +64,8 @@ import org.glassfish.api.admin.ServerEnvironment; import org.glassfish.hk2.api.PerLookup; import org.glassfish.internal.api.Globals; -import org.glassfish.security.common.PrincipalImpl; + +import org.glassfish.security.common.UserNameAndPassword; import org.jvnet.hk2.annotations.Service; import com.sun.enterprise.config.serverbeans.SecurityService; @@ -159,7 +160,7 @@ public Object run() throws Exception { } } - defaultSecurityContext.callerPrincipal = new PrincipalImpl(guestUser); + defaultSecurityContext.callerPrincipal = new UserNameAndPassword(guestUser); } } return defaultSecurityContext.callerPrincipal; @@ -235,7 +236,7 @@ public static void setUnauthenticatedContext() { public SecurityContext(String username, Subject subject) { Subject localSubject = nullSafeSubject(subject); - this.callerPrincipal = new PrincipalImpl(username); + this.callerPrincipal = new UserNameAndPassword(username); this.subject = privileged(() -> {localSubject.getPrincipals().add(callerPrincipal); return localSubject;}); } @@ -257,7 +258,7 @@ public SecurityContext(Subject subject) { for (Object publicCredential : localSubject.getPublicCredentials()) { if (publicCredential instanceof DistinguishedPrincipalCredential) { DistinguishedPrincipalCredential distinguishedCredential = (DistinguishedPrincipalCredential) publicCredential; - principal = distinguishedCredential.getPrincipal(); + principal = distinguishedCredential.principal(); break; } } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/WebAndEjbToJaasBridge.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/WebAndEjbToJaasBridge.java index 3e081454ca8..3a3c02d1bc8 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/WebAndEjbToJaasBridge.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/WebAndEjbToJaasBridge.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.auth; import static com.sun.enterprise.security.SecurityLoggerInfo.auditAtnRefusedError; @@ -69,7 +69,9 @@ import javax.security.auth.x500.X500Principal; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.security.common.UserNameAndPassword; +import org.glassfish.security.common.UserPrincipal; + import com.sun.enterprise.common.iiop.security.AnonCredential; import com.sun.enterprise.common.iiop.security.GSSUPName; @@ -312,7 +314,7 @@ public static void loginPrincipal(String username, String realmName) { } Subject subject = new Subject(); - PrincipalImpl callerPrincipal = new PrincipalImpl(username); + UserPrincipal callerPrincipal = new UserNameAndPassword(username); GSSUPName name = new GSSUPName(username, realmName); privileged(() -> { diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/ClientCertificateLoginModule.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/ClientCertificateLoginModule.java index 76e1a0c5605..9322ea7ec40 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/ClientCertificateLoginModule.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/ClientCertificateLoginModule.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.auth.login; import static com.sun.enterprise.security.auth.login.LoginContextDriver.CERT_REALMNAME; @@ -63,7 +63,9 @@ import com.sun.enterprise.security.auth.realm.certificate.OID; import org.glassfish.internal.api.Globals; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.security.common.UserNameAndPassword; +import org.glassfish.security.common.UserPrincipal; + import com.sun.enterprise.security.SecurityLoggerInfo; import com.sun.enterprise.security.auth.login.common.X509CertificateCredential; @@ -76,7 +78,7 @@ * This LoginModule authenticates users with X509 certificates. * *

- * If testUser successfully authenticates itself, a PrincipalImpl with the testUser's + * If testUser successfully authenticates itself, a UserPrincipal with the testUser's * username is added to the Subject. * *

@@ -106,7 +108,7 @@ public class ClientCertificateLoginModule implements LoginModule { private String alias; private X509Certificate certificate; - private PrincipalImpl userPrincipal; + private UserPrincipal userPrincipal; private AppClientSSL ssl; private SSLUtils sslUtils; @@ -213,7 +215,7 @@ public boolean login() throws LoginException { *

* If this LoginModule's own authentication attempt succeeded (checked by retrieving the private * state saved by the login method), then this method associates a - * PrincipalImpl with the Subject located in the LoginModule. + * UserPrincipal with the Subject located in the LoginModule. * If this LoginModule's own authentication attempted failed, then this method removes any state * that was originally saved. * @@ -230,15 +232,15 @@ public boolean commit() throws LoginException { } // Add a Principal (authenticated identity) to the Subject - // Assume the user we authenticated is the PrincipalImpl - userPrincipal = new PrincipalImpl(alias); + // Assume the user we authenticated is the UserPrincipal + userPrincipal = new UserNameAndPassword(alias); if (!subject.getPrincipals().contains(userPrincipal)) { subject.getPrincipals().add(userPrincipal); } if (debug) { if (_logger.isLoggable(FINE)) { - _logger.log(FINE, "\t\t[ClientCertificateLoginModule] " + "added PrincipalImpl to Subject"); + _logger.log(FINE, "\t\t[ClientCertificateLoginModule] " + "added UserPrincipal to Subject"); } } @@ -297,7 +299,7 @@ public boolean abort() throws LoginException { * Logout the user. * *

- * This method removes the PrincipalImpl that was added by the commit + * This method removes the UserPrincipal that was added by the commit * method. * *

diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/ClientPasswordLoginModule.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/ClientPasswordLoginModule.java index 7bbdc3147e2..c8943b5f322 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/ClientPasswordLoginModule.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/ClientPasswordLoginModule.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.auth.login; import static java.util.logging.Level.FINE; @@ -57,7 +57,9 @@ import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.security.common.UserNameAndPassword; +import org.glassfish.security.common.UserPrincipal; + import com.sun.enterprise.security.SecurityLoggerInfo; import com.sun.enterprise.security.UsernamePasswordStore; @@ -99,7 +101,7 @@ public class ClientPasswordLoginModule implements LoginModule { private boolean commitSucceeded; // The principal set when authentication succeeds. We don't really know why this is an instance variable. - private PrincipalImpl userPrincipal; + private UserPrincipal userPrincipal; /** @@ -221,7 +223,7 @@ public boolean login() throws LoginException { *

* If this LoginModule's own authentication attempt succeeded (checked by retrieving the private * state saved by the login method), then this method associates a - * PrincipalImpl with the Subject located in the LoginModule. + * UserPrincipal with the Subject located in the LoginModule. * If this LoginModule's own authentication attempted failed, then this method removes any state * that was originally saved. * @@ -239,13 +241,13 @@ public boolean commit() throws LoginException { // 1. Add a Principal (authenticated identity) to the Subject - // Assume the user we authenticated is the PrincipalImpl - userPrincipal = new PrincipalImpl(username); + // Assume the user we authenticated is the UserPrincipal + userPrincipal = new UserNameAndPassword(username); if (!subject.getPrincipals().contains(userPrincipal)) { subject.getPrincipals().add(userPrincipal); } - _logger.log(FINE, "\t\t[ClientPasswordLoginModule] " + "added PrincipalImpl to Subject"); + _logger.log(FINE, "\t\t[ClientPasswordLoginModule] " + "added UserPrincipal to Subject"); String realm = DEFAULT_REALMNAME; @@ -313,7 +315,7 @@ public boolean abort() throws LoginException { * Logout the user. * *

- * This method removes the PrincipalImpl that was added by the commit + * This method removes the UserPrincipal that was added by the commit * method. * *

diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/DistinguishedPrincipalCredential.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/DistinguishedPrincipalCredential.java index 626a81ffe4f..f311364786a 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/DistinguishedPrincipalCredential.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/DistinguishedPrincipalCredential.java @@ -41,22 +41,12 @@ package com.sun.enterprise.security.auth.login; -import com.sun.enterprise.security.common.UserPrincipal; +import org.glassfish.security.common.UserPrincipal; import java.io.Serializable; import java.security.Principal; -public class DistinguishedPrincipalCredential implements UserPrincipal, Serializable { - - private final Principal principal; - - public DistinguishedPrincipalCredential(Principal principal) { - this.principal = principal; - } - - public Principal getPrincipal() { - return principal; - } +public record DistinguishedPrincipalCredential(Principal principal) implements UserPrincipal, Serializable { @Override public String toString() { diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java index 4ea09f6432c..7064d60caa9 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java @@ -37,17 +37,17 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.common; import java.security.Principal; import javax.security.auth.Subject; -import org.glassfish.security.common.PrincipalImpl; import com.sun.enterprise.security.UsernamePasswordStore; import com.sun.enterprise.security.integration.AppServSecurityContext; +import org.glassfish.security.common.UserNameAndPassword; /** * This class represents the security context on the client side. For usage of the @@ -78,7 +78,7 @@ public final class ClientSecurityContext extends AbstractSecurityContext { * @param The Credentials of the user. */ public ClientSecurityContext(String username, Subject subject) { - this.callerPrincipal = new PrincipalImpl(username); + this.callerPrincipal = new UserNameAndPassword(username); this.subject = subject; } diff --git a/nucleus/security/services/src/main/java/org/glassfish/security/services/common/SubjectUtil.java b/nucleus/security/services/src/main/java/org/glassfish/security/services/common/SubjectUtil.java index 1ea3c1488cb..8840bdd56e0 100644 --- a/nucleus/security/services/src/main/java/org/glassfish/security/services/common/SubjectUtil.java +++ b/nucleus/security/services/src/main/java/org/glassfish/security/services/common/SubjectUtil.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright 2024 Payara Foundation and/or its affiliates package org.glassfish.security.services.common; import java.util.Set; @@ -47,17 +47,18 @@ import javax.security.auth.Subject; import java.security.Principal; -import org.glassfish.security.common.PrincipalImpl; +import org.glassfish.security.common.UserPrincipal; + import org.glassfish.security.common.Group; public class SubjectUtil { /** * Utility method to find the user names from a subject. The method assumes the user name is - * represented by {@link org.glassfish.security.common.PrincipalImpl PrincipalImpl } inside the Subject's principal set. + * represented by {@link org.glassfish.security.common.UserPrincipal UserPrincipal } inside the Subject's principal set. * @param subject the subject from which to find the user name * @return a list of strings representing the user name. The list may have more than one entry if the subject's principal set - * contains more than one PrincipalImpl instances, or empty entry (i.e., anonymous user) if the subject's principal set contains no PrincipalImpl instances. + * contains more than one UserPrincipal instances, or empty entry (i.e., anonymous user) if the subject's principal set contains no UserPrincipal instances. */ public static List getUsernamesFromSubject(Subject subject) { @@ -66,11 +67,10 @@ public static List getUsernamesFromSubject(Subject subject) { Set princSet = null; if (subject != null) { - princSet = subject.getPrincipals(); for (Principal p : princSet) { if ((p != null) && ( - p.getClass().isAssignableFrom(PrincipalImpl.class) || + p instanceof UserPrincipal || "weblogic.security.principal.WLSUserImpl".equals(p.getClass().getCanonicalName()) )) { String uName = p.getName(); @@ -99,7 +99,7 @@ public static List getGroupnamesFromSubject(Subject subject) { if (subject != null) { princSet = subject.getPrincipals(Group.class); - for (PrincipalImpl g : princSet) { + for (Group g : princSet) { String gName = g.getName(); groupList.add(gName); } diff --git a/nucleus/security/services/src/main/java/org/glassfish/security/services/impl/ImpersonationServiceImpl.java b/nucleus/security/services/src/main/java/org/glassfish/security/services/impl/ImpersonationServiceImpl.java index be7f832898a..8edf9ca5e98 100644 --- a/nucleus/security/services/src/main/java/org/glassfish/security/services/impl/ImpersonationServiceImpl.java +++ b/nucleus/security/services/src/main/java/org/glassfish/security/services/impl/ImpersonationServiceImpl.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright 2024 Payara Foundation and/or its affiliates package org.glassfish.security.services.impl; import java.security.Principal; @@ -48,7 +49,8 @@ import javax.security.auth.login.LoginException; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; + +import org.glassfish.security.common.UserNameAndPassword; import org.glassfish.security.services.api.authentication.ImpersonationService; import org.glassfish.security.services.common.Secure; import org.jvnet.hk2.annotations.Service; @@ -86,7 +88,7 @@ public Subject impersonate(String user, String[] groups, Subject subject, } else { // Build the Subject Set principals = _subject.getPrincipals(); - principals.add(new PrincipalImpl(user)); + principals.add(new UserNameAndPassword(user)); if (groups != null) { for (String group: groups) { principals.add(new Group(group)); diff --git a/nucleus/security/services/src/test/java/org/glassfish/security/services/api/authorization/SimpleAtzProviderTest.java b/nucleus/security/services/src/test/java/org/glassfish/security/services/api/authorization/SimpleAtzProviderTest.java index cc1785e729d..ed3772e84df 100644 --- a/nucleus/security/services/src/test/java/org/glassfish/security/services/api/authorization/SimpleAtzProviderTest.java +++ b/nucleus/security/services/src/test/java/org/glassfish/security/services/api/authorization/SimpleAtzProviderTest.java @@ -37,15 +37,16 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright 2024 Payara Foundation and/or its affiliates package org.glassfish.security.services.api.authorization; +import org.glassfish.security.common.UserNameAndPassword; import org.glassfish.security.services.impl.authorization.*; import java.net.URI; import javax.security.auth.Subject; -import org.glassfish.security.common.PrincipalImpl; + import org.glassfish.security.services.api.common.Attributes; import org.glassfish.security.services.api.context.SecurityContextService; import org.glassfish.security.services.impl.authorization.AuthorizationServiceImpl; @@ -114,7 +115,7 @@ public void testService() throws Exception { private Subject adminSubject() { final Subject result = new Subject(); - result.getPrincipals().add(new PrincipalImpl("asadmin")); + result.getPrincipals().add(new UserNameAndPassword("asadmin")); return result; } } \ No newline at end of file diff --git a/nucleus/security/services/src/test/java/org/glassfish/security/services/api/authorization/SimpleRoleProviderTest.java b/nucleus/security/services/src/test/java/org/glassfish/security/services/api/authorization/SimpleRoleProviderTest.java index 4117e268123..e3840f0e3e1 100644 --- a/nucleus/security/services/src/test/java/org/glassfish/security/services/api/authorization/SimpleRoleProviderTest.java +++ b/nucleus/security/services/src/test/java/org/glassfish/security/services/api/authorization/SimpleRoleProviderTest.java @@ -37,11 +37,13 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright 2024 Payara Foundation and/or its affiliates package org.glassfish.security.services.api.authorization; import java.net.URI; import javax.security.auth.Subject; +import org.glassfish.security.common.UserNameAndPassword; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -49,7 +51,7 @@ import org.jvnet.hk2.testing.junit.HK2Runner; import org.glassfish.security.common.Group; -import org.glassfish.security.common.PrincipalImpl; + import org.glassfish.security.services.impl.authorization.AuthorizationServiceImpl; import org.glassfish.security.services.spi.authorization.RoleMappingProvider; @@ -78,7 +80,7 @@ public void testProviderAdmin() throws Exception { private Subject adminSubject() { Subject result = new Subject(); - result.getPrincipals().add(new PrincipalImpl("admin")); + result.getPrincipals().add(new UserNameAndPassword("admin")); result.getPrincipals().add(new Group("asadmin")); return result; } @@ -95,7 +97,7 @@ public void testProviderNonAdmin() throws Exception { private Subject nonAdminSubject() { Subject result = new Subject(); - result.getPrincipals().add(new PrincipalImpl("joe")); + result.getPrincipals().add(new UserNameAndPassword("joe")); result.getPrincipals().add(new Group("myGroup")); return result; } diff --git a/nucleus/security/services/src/test/java/org/glassfish/security/services/common/SubjectUtilTest.java b/nucleus/security/services/src/test/java/org/glassfish/security/services/common/SubjectUtilTest.java index 6f091c87fcc..57ac2a7cbe8 100644 --- a/nucleus/security/services/src/test/java/org/glassfish/security/services/common/SubjectUtilTest.java +++ b/nucleus/security/services/src/test/java/org/glassfish/security/services/common/SubjectUtilTest.java @@ -37,9 +37,10 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright 2024 Payara Foundation and/or its affiliates package org.glassfish.security.services.common; +import org.glassfish.security.common.UserNameAndPassword; import org.junit.Test; import javax.security.auth.Subject; @@ -48,7 +49,6 @@ import java.util.List; import java.util.Set; -import org.glassfish.security.common.PrincipalImpl; import junit.framework.Assert; @@ -113,7 +113,7 @@ public void testGroupNameUtil_empty() { public void testUserNameUtil_multi() { Subject sub = createSub(USERNAME, GROUPS); - sub.getPrincipals().add(new PrincipalImpl(USERNAME2)); + sub.getPrincipals().add(new UserNameAndPassword(USERNAME2)); List usernames = SubjectUtil.getUsernamesFromSubject(sub); @@ -130,7 +130,7 @@ public static Subject createSub(String username, String[] groups) { Set pset = new HashSet(); if (username != null) { - Principal u = new PrincipalImpl(username); + Principal u = new UserNameAndPassword(username); pset.add(u); } diff --git a/nucleus/test-utils/utils/pom.xml b/nucleus/test-utils/utils/pom.xml index fd413072a8e..7e098637fa3 100644 --- a/nucleus/test-utils/utils/pom.xml +++ b/nucleus/test-utils/utils/pom.xml @@ -40,7 +40,7 @@ holder. --> - + @@ -88,5 +88,9 @@ junit compile + + fish.payara.server.core.common + common-util + diff --git a/nucleus/test-utils/utils/src/main/java/org/glassfish/tests/utils/ConfigApiTest.java b/nucleus/test-utils/utils/src/main/java/org/glassfish/tests/utils/ConfigApiTest.java index 28a4afd6977..d58552f2022 100644 --- a/nucleus/test-utils/utils/src/main/java/org/glassfish/tests/utils/ConfigApiTest.java +++ b/nucleus/test-utils/utils/src/main/java/org/glassfish/tests/utils/ConfigApiTest.java @@ -37,12 +37,11 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2016] [Payara Foundation] +// Portions Copyright 2016-2024 Payara Foundation and/or its affiliates package org.glassfish.tests.utils; import java.lang.reflect.Method; import java.security.AccessController; -import java.security.Principal; import java.security.PrivilegedAction; import java.util.List; import java.util.Set; @@ -51,6 +50,7 @@ import org.glassfish.hk2.api.Filter; import org.glassfish.hk2.api.ServiceLocator; +import org.glassfish.security.common.UserNameAndPassword; import org.junit.Ignore; import org.jvnet.hk2.config.ConfigBean; import org.jvnet.hk2.config.ConfigModel; @@ -125,23 +125,11 @@ public boolean matches(Descriptor d) { } } final Subject s = new Subject(); - s.getPrincipals().add(new PrincipalImpl("asadmin")); - s.getPrincipals().add(new PrincipalImpl("_InternalSystemAdministrator_")); + s.getPrincipals().add(new UserNameAndPassword("asadmin")); + s.getPrincipals().add(new UserNameAndPassword("_InternalSystemAdministrator_")); return s; } - private static class PrincipalImpl implements Principal { - private final String name; - - private PrincipalImpl(final String name) { - this.name = name; - } - @Override - public String getName() { - return name; - } - } - protected Subject adminSubject() { return adminSubject; } From 78126c425eab2260c8b985087aeb9474c0eb4dab Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Fri, 15 Nov 2024 11:39:56 +0000 Subject: [PATCH 06/34] Correct comment name --- appserver/packager/external/jakarta-ee11-shim/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/appserver/packager/external/jakarta-ee11-shim/pom.xml b/appserver/packager/external/jakarta-ee11-shim/pom.xml index 7ad63f09bf0..9a478bb449c 100644 --- a/appserver/packager/external/jakarta-ee11-shim/pom.xml +++ b/appserver/packager/external/jakarta-ee11-shim/pom.xml @@ -92,7 +92,7 @@ provided - + jakarta.security.enterprise jakarta.security.enterprise-api @@ -132,7 +132,7 @@ jakarta.security.jacc-api, jakarta.ws.rs-api, - + jakarta.security.enterprise-api @@ -237,7 +237,7 @@ jakarta.ws.rs.core; jakarta.ws.rs.ext; jakarta.ws.rs.sse;version="3.1.99";shim=true, - + jakarta.security.enterprise; jakarta.security.enterprise.authentication.mechanism.http; jakarta.security.enterprise.authentication.mechanism.http.openid; From 79f2fd87eef5e55f7d2e898885d4e83e20e88b2c Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Fri, 15 Nov 2024 11:48:39 +0000 Subject: [PATCH 07/34] Add soteria downgrade shim Signed-off-by: Andrew Pielage --- .../external/jakarta-ee11-shim/pom.xml | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/appserver/packager/external/jakarta-ee11-shim/pom.xml b/appserver/packager/external/jakarta-ee11-shim/pom.xml index 9a478bb449c..db1490d4e00 100644 --- a/appserver/packager/external/jakarta-ee11-shim/pom.xml +++ b/appserver/packager/external/jakarta-ee11-shim/pom.xml @@ -98,6 +98,13 @@ jakarta.security.enterprise-api provided + + + + org.glassfish.soteria + jakarta.security.enterprise + provided + @@ -133,7 +140,9 @@ jakarta.ws.rs-api, - jakarta.security.enterprise-api + jakarta.security.enterprise-api, + + org.glassfish.jakarta.security.enterprise + org.glassfish.soteria; + org.glassfish.soteria.authorization; + org.glassfish.soteria.authorization.spi; + org.glassfish.soteria.authorization.spi.impl; + org.glassfish.soteria.cdi; + org.glassfish.soteria.cdi.spi; + org.glassfish.soteria.cdi.spi.impl; + org.glassfish.soteria.identitystores; + org.glassfish.soteria.identitystores.annotation; + org.glassfish.soteria.identitystores.hash; + org.glassfish.soteria.mechanisms; + org.glassfish.soteria.mechanisms.jaspic; + org.glassfish.soteria.mechanisms.openid; + org.glassfish.soteria.mechanisms.openid.controller; + org.glassfish.soteria.mechanisms.openid.domain; + org.glassfish.soteria.servletversion="3.0.99";shim=true From 9afed1f2c38fc02a3b8cae2241dc797191c53eb6 Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Fri, 15 Nov 2024 11:59:25 +0000 Subject: [PATCH 08/34] Bundle name correction and missing ';' Signed-off-by: Andrew Pielage --- appserver/packager/external/jakarta-ee11-shim/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appserver/packager/external/jakarta-ee11-shim/pom.xml b/appserver/packager/external/jakarta-ee11-shim/pom.xml index db1490d4e00..4ead225e372 100644 --- a/appserver/packager/external/jakarta-ee11-shim/pom.xml +++ b/appserver/packager/external/jakarta-ee11-shim/pom.xml @@ -142,7 +142,7 @@ jakarta.security.enterprise-api, - org.glassfish.jakarta.security.enterprise + org.glassfish.soteria [Dynamic Code Evolution-11.0.10|]-XX:HotswapAgent=core [Dynamic Code Evolution-11.0.10|]-Xlog:redefine+class*=info + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy @@ -377,7 +378,7 @@ - + @@ -516,6 +517,7 @@ [Dynamic Code Evolution-11.0.10|]-XX:HotswapAgent=core [Dynamic Code Evolution-11.0.10|]-Xlog:redefine+class*=info + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy diff --git a/appserver/admin/gf_template_web/src/main/resources/config/domain.xml b/appserver/admin/gf_template_web/src/main/resources/config/domain.xml index 28804527ea1..7aea1e2a6b8 100644 --- a/appserver/admin/gf_template_web/src/main/resources/config/domain.xml +++ b/appserver/admin/gf_template_web/src/main/resources/config/domain.xml @@ -142,7 +142,7 @@ - + @@ -274,6 +274,7 @@ [Dynamic Code Evolution-11.0.10|]-XX:HotswapAgent=core [Dynamic Code Evolution-11.0.10|]-Xlog:redefine+class*=info + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy @@ -368,7 +369,7 @@ - + @@ -506,6 +507,7 @@ [Dynamic Code Evolution-11.0.10|]-XX:HotswapAgent=core [Dynamic Code Evolution-11.0.10|]-Xlog:redefine+class*=info + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy diff --git a/appserver/admin/production_domain_template/src/main/resources/config/domain.xml b/appserver/admin/production_domain_template/src/main/resources/config/domain.xml index a447b0260df..027827a7f1f 100644 --- a/appserver/admin/production_domain_template/src/main/resources/config/domain.xml +++ b/appserver/admin/production_domain_template/src/main/resources/config/domain.xml @@ -124,7 +124,7 @@ - + @@ -225,6 +225,7 @@ -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar -Djdk.attach.allowAttachSelf=true + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy @@ -328,7 +329,7 @@ - + @@ -438,6 +439,7 @@ -Dorg.jboss.weld.serialization.beanIdentifierIndexOptimization=false -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy diff --git a/appserver/admin/production_domain_template_web/src/main/resources/config/domain.xml b/appserver/admin/production_domain_template_web/src/main/resources/config/domain.xml index 11fa5ec0b00..7c58b5a0203 100644 --- a/appserver/admin/production_domain_template_web/src/main/resources/config/domain.xml +++ b/appserver/admin/production_domain_template_web/src/main/resources/config/domain.xml @@ -147,7 +147,7 @@ - + @@ -248,6 +248,7 @@ -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar -Djdk.attach.allowAttachSelf=true + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy @@ -346,7 +347,7 @@ - + @@ -455,6 +456,7 @@ -Dorg.jboss.weld.serialization.beanIdentifierIndexOptimization=false -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index 04f19d1bcad..603ae7fc4bf 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -634,7 +634,7 @@ private boolean validateRequest(HttpRequest request, HttpResponse response, Logi try { - isMandatory = this.webAuthorizationManagerService.permitAll(servletRequest); + isMandatory = !this.webAuthorizationManagerService.permitAll(servletRequest); // Produce caller challenge if call originates from HttpServletRequest#authenticate if (isMandatory || calledFromAuthenticate) { messageInfo.getMap().put(HttpServletConstants.IS_MANDATORY, Boolean.TRUE.toString()); From 6cfd0bf5969150699a3942e5c894feeaed973eb6 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Wed, 30 Oct 2024 23:45:30 -0600 Subject: [PATCH 14/34] FISH-8925: rebasing last changes from Payara7 branch --- appserver/connectors/work-management/pom.xml | 7 +- .../deployment/runtime/RuntimeDescriptor.java | 4 +- .../glassfish/ejb/startup/EjbDeployer.java | 2 +- .../appclient/AppClientSecurityInfoImpl.java | 6 +- .../security/appclient/ConfigXMLParser.java | 49 +- appserver/security/core-ee/pom.xml | 6 +- .../security/ee/JavaEESecurityLifecycle.java | 89 +- .../jakarta/AuthMessagePolicy.java | 238 +++++ .../jakarta}/ConfigDomainParser.java | 44 +- .../jakarta}/WebServicesDelegate.java | 6 +- .../security/ee/authorize}/PolicyLoader.java | 3 +- .../jacc/JaccWebAuthorizationManager.java | 2 +- .../security/jacc/package-info.java | 4 +- .../security/jaspic/AuthMessagePolicy.java | 334 ------ ...essageSecurityConfigEventListenerImpl.java | 76 +- .../security/jaspic/config/ConfigParser.java | 101 -- .../jaspic/config/GFAuthConfigFactory.java | 126 --- .../jaspic/config/GFServerConfigProvider.java | 981 ------------------ ...rvices.java => PayaraEpicyroServices.java} | 8 +- ...java => PayaraEpicyroServletServices.java} | 17 +- .../enterprise/security/jauth/ConfigFile.java | 619 ----------- .../jaspic-provider-framework/osgi.bundle | 4 +- .../jaspic-provider-framework/pom.xml | 6 +- .../config/factory/AuthConfigFileFactory.java | 89 -- .../config/factory/BaseAuthConfigFactory.java | 728 ------------- .../config/factory/RegStoreFileParser.java | 454 -------- .../AuthConfigRegistrationWrapper.java | 180 ---- .../com/sun/jaspic/services/ConfigData.java | 83 -- .../sun/jaspic/services/JaspicServices.java | 237 ----- .../services/RegistrationWrapperRemover.java | 53 - .../com/sun/jaspic/config/FactoryTest.java | 5 +- .../sun/jaspic/config/RuntimeSurrogate.java | 4 +- .../security/realmadapter/JaspicRealm.java | 10 +- .../security/webservices.security/pom.xml | 12 +- .../jaspic/provider/config/PipeHelper.java | 61 +- .../webservices/ClientPipeCloser.java | 4 +- .../webservices/ClientPipeCreator.java | 4 +- .../webservices/WebServicesDelegateImpl.java | 6 +- core/core-parent/pom.xml | 2 + core/pom.xml | 6 + .../common/DynamicAttributesDescriptor.java | 6 +- nucleus/security/core/pom.xml | 6 +- .../security/audit/BaseAuditManager.java | 4 +- .../common/ClientSecurityContext.java | 5 +- 44 files changed, 505 insertions(+), 4186 deletions(-) create mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic/config => ee/authentication/jakarta}/ConfigDomainParser.java (86%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic => ee/authentication/jakarta}/WebServicesDelegate.java (95%) rename {nucleus/security/core/src/main/java/com/sun/enterprise/security => appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize}/PolicyLoader.java (99%) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/{PayaraJaspicServices.java => PayaraEpicyroServices.java} (91%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/{PayaraJaspicServletServices.java => PayaraEpicyroServletServices.java} (86%) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java diff --git a/appserver/connectors/work-management/pom.xml b/appserver/connectors/work-management/pom.xml index 9925f728c2d..1687e63df76 100644 --- a/appserver/connectors/work-management/pom.xml +++ b/appserver/connectors/work-management/pom.xml @@ -39,7 +39,7 @@ holder. --> - + 4.0.0 @@ -148,5 +148,10 @@ logging-annotation-processor true + + + org.glassfish.epicyro + epicyro + diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java index 7b89d2bc908..1be283f8542 100644 --- a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/runtime/RuntimeDescriptor.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2020] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.deployment.runtime; @@ -121,7 +121,7 @@ public void setValue(String name, Object value) { /** * @return a property value */ - public Object getValue(String name) { + public T getValue(String name) { return getExtraAttribute(name); } diff --git a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java index 46326ada624..207f4258b46 100644 --- a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java +++ b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java @@ -89,7 +89,7 @@ import com.sun.enterprise.deployment.Application; import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.module.bootstrap.StartupContext; -import com.sun.enterprise.security.PolicyLoader; +import com.sun.enterprise.security.ee.authorize.PolicyLoader; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.util.IASSecurityException; import com.sun.enterprise.util.LocalStringManagerImpl; diff --git a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java index 7cc9ff43c2c..e5fd188d81e 100644 --- a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java +++ b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2022] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.appclient; import com.sun.enterprise.security.SecurityServicesUtil; @@ -50,7 +50,6 @@ import com.sun.enterprise.security.common.Util; import com.sun.enterprise.security.ee.J2EESecurityManager; import com.sun.enterprise.security.integration.AppClientSSL; -import com.sun.enterprise.security.jaspic.config.GFAuthConfigFactory; import com.sun.enterprise.security.ssl.SSLUtils; import com.sun.logging.LogDomains; import jakarta.inject.Inject; @@ -60,6 +59,7 @@ import org.glassfish.appclient.client.acc.config.Ssl; import org.glassfish.appclient.client.acc.config.TargetServer; import org.glassfish.enterprise.iiop.api.IIOPSSLUtil; +import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; import org.jvnet.hk2.annotations.Service; import javax.security.auth.Subject; @@ -147,7 +147,7 @@ public void initializeSecurity( if (defaultFactory == null) { java.security.Security.setProperty (AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY, - GFAuthConfigFactory.class.getName()); + AuthConfigFileFactory.class.getName()); } } catch (Exception e) { diff --git a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java index ec0352c1261..197b75e9db2 100644 --- a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java +++ b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/ConfigXMLParser.java @@ -37,15 +37,12 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright 2019-2022 Payara Foundation and/or its affiliates +// Portions Copyright 2019-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.security.appclient; import com.sun.enterprise.security.common.Util; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; -import com.sun.enterprise.security.jaspic.config.ConfigParser; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; import com.sun.logging.LogDomains; import jakarta.security.auth.message.MessagePolicy; import jakarta.xml.bind.JAXBContext; @@ -57,6 +54,10 @@ import org.glassfish.appclient.client.acc.config.ProviderConfig; import org.glassfish.appclient.client.acc.config.RequestPolicy; import org.glassfish.appclient.client.acc.config.ResponsePolicy; +import org.glassfish.epicyro.config.factory.ConfigParser; +import org.glassfish.epicyro.config.helper.AuthMessagePolicy; +import org.glassfish.epicyro.data.AuthModuleConfig; +import org.glassfish.epicyro.data.AuthModulesLayerConfig; import org.glassfish.internal.api.Globals; import java.io.FileInputStream; @@ -83,22 +84,22 @@ public class ConfigXMLParser implements ConfigParser { private static Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{\\{(.*?)}}|\\$\\{(.*?)}"); // configuration info - private Map configMap = new HashMap(); + private final Map authModuleLayers = new HashMap<>(); private Set layersWithDefault = new HashSet(); private List msgSecConfigs = null; private static final String ACC_XML = "glassfish-acc.xml.url"; - public ConfigXMLParser() throws IOException { + public ConfigXMLParser() { } public void initialize(List msgConfigs) throws IOException { this.msgSecConfigs = msgConfigs; if (this.msgSecConfigs != null) { - processClientConfigContext(configMap); + processClientConfigContext(authModuleLayers); } } - private void processClientConfigContext(Map newConfig) throws IOException { + private void processClientConfigContext(Map newConfig) throws IOException { // auth-layer String intercept = null; @@ -113,16 +114,12 @@ private void processClientConfigContext(Map newConfig) throws IOException { } } - - public Map getConfigMap() { - return configMap; - } - + public Set getLayersWithDefault() { return layersWithDefault; } - private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { + private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { String intercept = null; String defaultServerID = null; String defaultClientID = null; @@ -140,19 +137,19 @@ private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfi layersWithDefault.add(intercept); } - GFServerConfigProvider.InterceptEntry intEntry = (GFServerConfigProvider.InterceptEntry) newConfig.get(intercept); + AuthModulesLayerConfig intEntry = newConfig.get(intercept); if (intEntry != null) { throw new IOException("found multiple MessageSecurityConfig " + "entries with the same auth-layer"); } // create new intercept entry - intEntry = new GFServerConfigProvider.InterceptEntry(defaultClientID, defaultServerID, null); + intEntry = new AuthModulesLayerConfig(defaultClientID, defaultServerID, null); newConfig.put(intercept, intEntry); return intercept; } // duplicate implementation for clientbeans config - private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercept) throws IOException { + private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercept) throws IOException { String id = pConfig.getProviderId(); String type = pConfig.getProviderType(); String moduleClass = pConfig.getClassName(); @@ -183,20 +180,21 @@ private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercep // create ID entry - GFServerConfigProvider.IDEntry idEntry = new GFServerConfigProvider.IDEntry(type, moduleClass, requestPolicy, - responsePolicy, options); + //GFServerConfigProvider.IDEntry idEntry = new GFServerConfigProvider.IDEntry(type, moduleClass, requestPolicy, + // responsePolicy, options); + AuthModuleConfig idEntry = new AuthModuleConfig(type, moduleClass, requestPolicy, responsePolicy, options); - GFServerConfigProvider.InterceptEntry intEntry = (GFServerConfigProvider.InterceptEntry) newConfig.get(intercept); + AuthModulesLayerConfig intEntry = newConfig.get(intercept); if (intEntry == null) { throw new IOException("intercept entry for " + intercept + " must be specified before ID entries"); } - if (intEntry.getIdMap() == null) { - intEntry.setIdMap(new HashMap()); + if (intEntry.getAuthModules() == null) { + intEntry.setIdMap(new HashMap<>()); } // map id to Intercept - intEntry.getIdMap().put(id, idEntry); + intEntry.getAuthModules().put(id, idEntry); } private String expand(String rawProperty) { @@ -270,4 +268,9 @@ public void initialize(Object config) throws IOException { this.initialize(msgconfigs); } + + @Override + public Map getAuthModuleLayers() { + return this.authModuleLayers; + } } diff --git a/appserver/security/core-ee/pom.xml b/appserver/security/core-ee/pom.xml index 0f7f0f28bf1..3172d64f9c3 100644 --- a/appserver/security/core-ee/pom.xml +++ b/appserver/security/core-ee/pom.xml @@ -41,7 +41,7 @@ --> - + 4.0.0 @@ -282,5 +282,9 @@ org.glassfish.exousia exousia + + org.glassfish.epicyro + epicyro + diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java index 6a33dc32c3e..fb41dad5358 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java @@ -37,26 +37,39 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.ee; import com.sun.enterprise.security.ContainerSecurityLifecycle; -import com.sun.enterprise.security.jaspic.config.GFAuthConfigFactory; +import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; +import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; +import com.sun.enterprise.security.ee.authorize.PolicyLoader; import com.sun.logging.LogDomains; +import jakarta.inject.Inject; +import jakarta.security.auth.message.MessageInfo; +import jakarta.security.auth.message.MessagePolicy; +import java.security.Provider; import java.security.Security; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; import java.util.logging.Logger; import jakarta.inject.Singleton; import org.glassfish.common.util.Constants; +import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import org.glassfish.hk2.api.PostConstruct; import org.glassfish.hk2.api.Rank; +import org.glassfish.internal.api.Globals; import org.glassfish.internal.api.InitRunLevel; import org.jvnet.hk2.annotations.Service; -import static java.util.logging.Level.WARNING; import static jakarta.security.auth.message.config.AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY; +import static org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory.DEFAULT_FACTORY_DEFAULT_PROVIDERS; /** @@ -71,42 +84,62 @@ public class JavaEESecurityLifecycle implements ContainerSecurityLifecycle, Post private static final Logger LOG = LogDomains.getLogger(JavaEESecurityLifecycle.class, LogDomains.SECURITY_LOGGER); + @Inject + PolicyLoader policyLoader; + @Override public void postConstruct() { onInitialization(); } - @Override public void onInitialization() { - LOG.finest(() -> "Initializing " + getClass()); - - // TODO: Need some way to not override the security manager if the EmbeddedServer was - // run with a different non-default security manager. - // - // Right now there seems no way to find out if the security manager is the VM's default security manager. - final SecurityManager systemSecurityManager = System.getSecurityManager(); - if (systemSecurityManager != null && !(J2EESecurityManager.class.equals(systemSecurityManager.getClass()))) { - J2EESecurityManager eeSecurityManager = new J2EESecurityManager(); - try { - System.setSecurityManager(eeSecurityManager); - LOG.config(() -> "System security manager has been set to " + eeSecurityManager); - } catch (SecurityException ex) { - LOG.log(WARNING, "security.secmgr.could.not.override", ex); - } - } - initializeJASPIC(); + initializeJakartaAuthentication(); + initializeJakartaAuthorization(); } - private void initializeJASPIC() { + private void initializeJakartaAuthentication() { + // Define default factory if it is not already defined. - // The factory will be constructed on the first getFactory call. - final String defaultFactory = Security.getProperty(DEFAULT_FACTORY_SECURITY_PROPERTY); + // The factory will be constructed on first getFactory call. + + String defaultFactory = Security.getProperty(DEFAULT_FACTORY_SECURITY_PROPERTY); if (defaultFactory == null) { - final String defaultAuthConfigProvideFactoryClassName = GFAuthConfigFactory.class.getName(); - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, defaultAuthConfigProvideFactoryClassName); - LOG.config(() -> String.format("System JVM option '%s' has been set to '%s'", - DEFAULT_FACTORY_SECURITY_PROPERTY, defaultAuthConfigProvideFactoryClassName)); + Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, AuthConfigFileFactory.class.getName()); + } + + String defaultProvidersString = null; + WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); + if (delegate == null) { + defaultProvidersString = GFServerConfigProvider.class.getName(); + } else { + // NOTE: Order matters here. Providers for the same auth layer (HttpServlet or SOAP) will be overwritten + // by ones that appear later in this string without warning. + defaultProvidersString = delegate.getDefaultWebServicesProvider() + " " + GFServerConfigProvider.class.getName(); } + + Security.setProperty(DEFAULT_FACTORY_DEFAULT_PROVIDERS, defaultProvidersString); + + Function authContextIdGenerator = + e -> Globals.get(WebServicesDelegate.class).getAuthContextID(e); + + BiFunction, MessagePolicy[]> soapPolicyGenerator = + (authContextId, properties) -> AuthMessagePolicy.getSOAPPolicies( + AuthMessagePolicy.getMessageSecurityBinding("SOAP", properties), + authContextId, true); + + Provider provider = new Provider("EleosProvider", "1.0", "") { + private static final long serialVersionUID = 1L; + }; + provider.put("authContextIdGenerator", authContextIdGenerator); + provider.put("soapPolicyGenerator", soapPolicyGenerator); + + Security.addProvider(provider); + + System.setProperty("config.parser", ConfigDomainParser.class.getName()); + } + + private void initializeJakartaAuthorization() { + policyLoader.loadPolicy(); } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java new file mode 100644 index 00000000000..fc2dc352ab3 --- /dev/null +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/AuthMessagePolicy.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ +package com.sun.enterprise.security.ee.authentication.jakarta; + +import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; +import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; +import static org.glassfish.epicyro.config.helper.HttpServletConstants.SOAP; + +import com.sun.enterprise.deployment.ServiceReferenceDescriptor; +import com.sun.enterprise.deployment.WebBundleDescriptor; +import com.sun.enterprise.deployment.WebServiceEndpoint; +import com.sun.enterprise.deployment.runtime.common.MessageDescriptor; +import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; +import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; +import com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor; +import com.sun.enterprise.deployment.runtime.web.SunWebApp; +import jakarta.security.auth.message.MessagePolicy; +import java.util.List; +import java.util.Map; +import javax.security.auth.callback.CallbackHandler; +import org.glassfish.internal.api.Globals; + +/** + * Utility class for Jakarta Authentication appserver implementation. + */ +public class AuthMessagePolicy { + + public static final String WEB_BUNDLE = "WEB_BUNDLE"; + + private static final String HANDLER_CLASS_PROPERTY = "security.jmac.config.ConfigHelper.CallbackHandler"; + private static final String DEFAULT_HANDLER_CLASS = "com.sun.enterprise.security.ee.authentication.jakarta.callback.ContainerCallbackHandler"; + + private static String handlerClassName; + + private AuthMessagePolicy() { + } + + public static MessageSecurityBindingDescriptor getMessageSecurityBinding(String layer, Map properties) { + if (properties == null) { + return null; + } + + MessageSecurityBindingDescriptor binding = null; + + WebServiceEndpoint webServiceEndpoint = (WebServiceEndpoint) properties.get("SERVICE_ENDPOINT"); + + if (webServiceEndpoint != null) { + binding = webServiceEndpoint.getMessageSecurityBinding(); + } else { + ServiceReferenceDescriptor serviceReferenceDescriptor = (ServiceReferenceDescriptor) properties.get("SERVICE_REF"); + if (serviceReferenceDescriptor != null) { + WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); + if (delegate != null) { + binding = delegate.getBinding(serviceReferenceDescriptor, properties); + } + } + } + + if (binding != null) { + String bindingLayer = (String) binding.getValue(AUTH_LAYER); + if (bindingLayer == null || layer.equals(bindingLayer)) { + return binding; + } + } + + return null; + } + + public static MessagePolicy getMessagePolicy(ProtectionDescriptor protectionDescriptor) { + MessagePolicy messagePolicy = null; + if (protectionDescriptor != null) { + String source = protectionDescriptor.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); + String recipient = protectionDescriptor.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); + messagePolicy = org.glassfish.epicyro.config.helper.AuthMessagePolicy.getMessagePolicy(source, recipient); + } + + return messagePolicy; + } + + public static String getProviderID(MessageSecurityBindingDescriptor binding) { + if (binding == null) { + return null; + } + + if (!SOAP.equals(binding.getValue(AUTH_LAYER))) { + return null; + } + + return binding.getValue(PROVIDER_ID); + } + + public static MessagePolicy[] getSOAPPolicies(MessageSecurityBindingDescriptor binding, String operation, boolean onePolicy) { + MessagePolicy requestPolicy = null; + MessagePolicy responsePolicy = null; + + if (binding != null) { + List messageSecurityDescriptors = null; + String layer = binding.getValue(AUTH_LAYER); + if (SOAP.equals(layer)) { + messageSecurityDescriptors = binding.getMessageSecurityDescriptors(); + } + + if (messageSecurityDescriptors != null) { + if (onePolicy) { + if (messageSecurityDescriptors.size() > 0) { + MessageSecurityDescriptor messageSecurityDescriptor = messageSecurityDescriptors.get(0); + requestPolicy = getMessagePolicy(messageSecurityDescriptor.getRequestProtectionDescriptor()); + responsePolicy = getMessagePolicy(messageSecurityDescriptor.getResponseProtectionDescriptor()); + } + } else { // try to match + MessageSecurityDescriptor matchMsd = null; + for (int i = 0; i < messageSecurityDescriptors.size(); i++) { + MessageSecurityDescriptor msd = messageSecurityDescriptors.get(i); + List msgDescs = msd.getMessageDescriptors(); + for (int j = i + 1; j < msgDescs.size(); j++) { + // XXX don't know how to get JavaMethod from operation + MessageDescriptor msgDesc = msgDescs.get(j); + String opName = msgDesc.getOperationName(); + if (opName == null && matchMsd == null) { + matchMsd = msd; + } else if (opName != null && opName.equals(operation)) { + matchMsd = msd; + break; + } + } + + if (matchMsd != null) { + requestPolicy = getMessagePolicy(matchMsd.getRequestProtectionDescriptor()); + responsePolicy = getMessagePolicy(matchMsd.getResponseProtectionDescriptor()); + } + } + } + } + } + + return new MessagePolicy[] { requestPolicy, responsePolicy }; + } + + public static boolean oneSOAPPolicy(MessageSecurityBindingDescriptor binding) { + + boolean onePolicy = true; + List msgSecDescs = null; + if (binding != null) { + String layer = binding.getAttributeValue(AUTH_LAYER); + if (SOAP.equals(layer)) { + msgSecDescs = binding.getMessageSecurityDescriptors(); + } + } + + if (msgSecDescs == null) { + return true; + } + + for (int i = 0; i < msgSecDescs.size(); i++) { + + MessageSecurityDescriptor msd = msgSecDescs.get(i); + + // Determine if all the different messageSecurityDesriptors have the + // same policy which will help us interpret the effective policy if + // we cannot determine the opcode of a request at runtime. + for (int j = 0; j < msgSecDescs.size(); j++) { + if (j != i && !policiesAreEqual(msd, msgSecDescs.get(j))) { + onePolicy = false; + } + } + } + + return onePolicy; + } + + public static SunWebApp getSunWebApp(Map properties) { + if (properties == null) { + return null; + } + + WebBundleDescriptor webBundle = (WebBundleDescriptor) properties.get(WEB_BUNDLE); + return webBundle.getSunDescriptor(); + } + + public static String getProviderID(SunWebApp sunWebApp) { + if (sunWebApp == null) { + return null; + } + + return sunWebApp.getAttributeValue(SunWebApp.HTTPSERVLET_SECURITY_PROVIDER); + } + + + public static CallbackHandler getDefaultCallbackHandler() { + try { + if (handlerClassName == null) { + handlerClassName = System.getProperty(HANDLER_CLASS_PROPERTY, DEFAULT_HANDLER_CLASS); + } + + return (CallbackHandler) + Class.forName(handlerClassName, true, Thread.currentThread().getContextClassLoader()) + .getDeclaredConstructor() + .newInstance(); + + } catch (ReflectiveOperationException pae) { + throw new RuntimeException(pae); + } + } + + private static boolean policiesAreEqual(MessageSecurityDescriptor reference, MessageSecurityDescriptor other) { + return protectionDescriptorsAreEqual(reference.getRequestProtectionDescriptor(), other.getRequestProtectionDescriptor()) + && protectionDescriptorsAreEqual(reference.getResponseProtectionDescriptor(), other.getResponseProtectionDescriptor()); + } + + private static boolean protectionDescriptorsAreEqual(ProtectionDescriptor pd1, ProtectionDescriptor pd2) { + String authSource1 = pd1.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); + String authRecipient1 = pd1.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); + + String authSource2 = pd2.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); + String authRecipient2 = pd2.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); + + boolean sameAuthSource = authSource1 == null && authSource2 == null || authSource1 != null && authSource1.equals(authSource2); + boolean sameAuthRecipient = authRecipient1 == null && authRecipient2 == null + || authRecipient1 != null && authRecipient1.equals(authRecipient2); + + return sameAuthSource && sameAuthRecipient; + } +} + diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigDomainParser.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/ConfigDomainParser.java similarity index 86% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigDomainParser.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/ConfigDomainParser.java index c978289d313..f93a305683e 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigDomainParser.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/ConfigDomainParser.java @@ -37,18 +37,21 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright 2019-2022 Payara Foundation and/or its affiliates +// Portions Copyright 2019-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license -package com.sun.enterprise.security.jaspic.config; +package com.sun.enterprise.security.ee.authentication.jakarta; import com.sun.enterprise.config.serverbeans.MessageSecurityConfig; import com.sun.enterprise.config.serverbeans.ProviderConfig; import com.sun.enterprise.config.serverbeans.RequestPolicy; import com.sun.enterprise.config.serverbeans.ResponsePolicy; import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; import com.sun.logging.LogDomains; import jakarta.security.auth.message.MessagePolicy; +import org.glassfish.epicyro.config.factory.ConfigParser; +import org.glassfish.epicyro.config.helper.AuthMessagePolicy; +import org.glassfish.epicyro.data.AuthModuleConfig; +import org.glassfish.epicyro.data.AuthModulesLayerConfig; import org.glassfish.internal.api.Globals; import org.jvnet.hk2.config.types.Property; @@ -78,10 +81,10 @@ public class ConfigDomainParser implements ConfigParser { private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{\\{(.*?)}}|\\$\\{(.*?)}"); // configuration info - private Map configMap = new HashMap<>(); + private Map configMap = new HashMap<>(); private Set layersWithDefault = new HashSet(); - public ConfigDomainParser() throws IOException { + public ConfigDomainParser() { } public void initialize(Object service) throws IOException { @@ -94,7 +97,12 @@ public void initialize(Object service) throws IOException { } } - private void processServerConfig(SecurityService service, Map newConfig) throws IOException { + @Override + public Map getAuthModuleLayers() { + return configMap; + } + + private void processServerConfig(SecurityService service, Map newConfig) throws IOException { List configList = service.getMessageSecurityConfig(); if (configList != null) { @@ -119,7 +127,7 @@ private void processServerConfig(SecurityService service, Map getConfigMap() { + public Map getConfigMap() { return configMap; } @@ -127,7 +135,7 @@ public Set getLayersWithDefault() { return layersWithDefault; } - private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { + private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig) throws IOException { String intercept = null; String defaultServerID = null; String defaultClientID = null; @@ -145,19 +153,19 @@ private String parseInterceptEntry(MessageSecurityConfig msgConfig, Map newConfig, String intercept) throws IOException { + private void parseIDEntry(ProviderConfig pConfig, Map newConfig, String intercept) throws IOException { String id = pConfig.getProviderId(); String type = pConfig.getProviderType(); @@ -194,20 +202,20 @@ private void parseIDEntry(ProviderConfig pConfig, Map(); + if (intEntry.getAuthModules() == null) { + intEntry.setIdMap(new HashMap()); } // map id to Intercept - intEntry.idMap.put(id, idEntry); + intEntry.getAuthModules().put(id, idEntry); } private String expand(String rawProperty) { diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/WebServicesDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java similarity index 95% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/WebServicesDelegate.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java index 2241ca072f6..7951de32a2f 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/WebServicesDelegate.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java @@ -37,8 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic; +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authentication.jakarta; import java.util.Map; @@ -50,7 +50,7 @@ import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; import com.sun.enterprise.security.jauth.AuthParam; -import com.sun.jaspic.services.RegistrationWrapperRemover; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; /** * A Delegate interface for handling WebServices specific security and JASPIC (JSR 196) providers. diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java similarity index 99% rename from nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java index 4071525d44d..10612bf5fdc 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java @@ -38,10 +38,11 @@ * holder. */ // Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security; +package com.sun.enterprise.security.ee.authorize; import com.sun.enterprise.config.serverbeans.JaccProvider; import com.sun.enterprise.config.serverbeans.SecurityService; +import com.sun.enterprise.security.SecurityLoggerInfo; import com.sun.enterprise.util.i18n.StringManager; import jakarta.inject.Inject; import jakarta.inject.Named; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java index 81cefd76b61..b86bbf84028 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java @@ -49,7 +49,7 @@ import com.sun.enterprise.deployment.runtime.common.wls.SecurityRoleAssignment; import com.sun.enterprise.deployment.runtime.web.SunWebApp; import com.sun.enterprise.deployment.web.LoginConfiguration; -import com.sun.enterprise.security.PolicyLoader; +import com.sun.enterprise.security.ee.authorize.PolicyLoader; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityRoleMapperFactoryGen; import com.sun.enterprise.security.SecurityServicesUtil; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java index d3455e78ed6..96c34b3ef69 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java @@ -38,7 +38,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] /** * This package contains much of the implementation code for JACC. * @@ -59,7 +59,7 @@ * *

* The pluggable JACC components are loaded by a class in nucleus: - * {@link com.sun.enterprise.security.PolicyLoader} + * {@link com.sun.enterprise.security.ee.authorize.PolicyLoader} * */ package com.sun.enterprise.security.jacc; \ No newline at end of file diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java deleted file mode 100644 index c2f723f3b91..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/AuthMessagePolicy.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic; - -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; -import static com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor.AUTH_RECIPIENT; -import static com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor.AUTH_SOURCE; -import static com.sun.enterprise.deployment.runtime.web.SunWebApp.HTTPSERVLET_SECURITY_PROVIDER; -import static com.sun.enterprise.security.common.AppservAccessController.doPrivileged; -import static com.sun.enterprise.security.jaspic.config.GFServerConfigProvider.SOAP; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.WEB_BUNDLE; -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_CONTENT; -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_RECIPIENT; -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_SENDER; - -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.MessagePolicy.TargetPolicy; - -import org.glassfish.internal.api.Globals; - -import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.enterprise.deployment.WebBundleDescriptor; -import com.sun.enterprise.deployment.WebServiceEndpoint; -import com.sun.enterprise.deployment.runtime.common.MessageDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; -import com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor; -import com.sun.enterprise.deployment.runtime.web.SunWebApp; - -/** - * Utility class for JASPIC appserver implementation. - */ -public class AuthMessagePolicy { - - private static final String SENDER = "sender"; - private static final String CONTENT = "content"; - private static final String BEFORE_CONTENT = "before-content"; - private static final String HANDLER_CLASS_PROPERTY = "security.jaspic.config.ConfigHelper.CallbackHandler"; - private static final String DEFAULT_HANDLER_CLASS = "com.sun.enterprise.security.jaspic.callback.ContainerCallbackHandler"; - - // for HttpServlet profile - private static final MessagePolicy MANDATORY_POLICY = getMessagePolicy(SENDER, null, true); - private static final MessagePolicy OPTIONAL_POLICY = getMessagePolicy(SENDER, null, false); - - private static String handlerClassName; - - private AuthMessagePolicy() { - } - - public static MessageSecurityBindingDescriptor getMessageSecurityBinding(String layer, Map properties) { - if (properties == null) { - return null; - } - - MessageSecurityBindingDescriptor messageSecurityBinding = null; - - WebServiceEndpoint webServiceEndpoint = (WebServiceEndpoint) properties.get("SERVICE_ENDPOINT"); - - if (webServiceEndpoint != null) { - messageSecurityBinding = webServiceEndpoint.getMessageSecurityBinding(); - } else { - ServiceReferenceDescriptor serviceReference = (ServiceReferenceDescriptor) properties.get("SERVICE_REF"); - if (serviceReference != null) { - WebServicesDelegate webServicesDelegate = Globals.get(WebServicesDelegate.class); - if (webServicesDelegate != null) { - messageSecurityBinding = webServicesDelegate.getBinding(serviceReference, properties); - } - } - } - - if (messageSecurityBinding != null) { - String bindingLayer = messageSecurityBinding.getAttributeValue(AUTH_LAYER); - if (bindingLayer == null || layer.equals(bindingLayer)) { - return messageSecurityBinding; - } - } - - return null; - } - - public static MessagePolicy getMessagePolicy(String authSource, String authRecipient) { - boolean sourceSender = SENDER.equals(authSource); - boolean sourceContent = CONTENT.equals(authSource); - boolean recipientAuth = authRecipient != null; - boolean mandatory = (sourceSender || sourceContent) || recipientAuth; - - return getMessagePolicy(authSource, authRecipient, mandatory); - } - - public static MessagePolicy getMessagePolicy(String authSource, String authRecipient, boolean mandatory) { - boolean sourceSender = SENDER.equals(authSource); - boolean sourceContent = CONTENT.equals(authSource); - boolean recipientAuth = authRecipient != null; - boolean beforeContent = BEFORE_CONTENT.equals(authRecipient); - - List targetPolicies = new ArrayList(); - - if (recipientAuth && beforeContent) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_RECIPIENT)); - - if (sourceSender) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_SENDER)); - } else if (sourceContent) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_CONTENT)); - } - } else { - if (sourceSender) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_SENDER)); - } else if (sourceContent) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_CONTENT)); - } - - if (recipientAuth) { - targetPolicies.add(new TargetPolicy(null, () -> AUTHENTICATE_RECIPIENT)); - } - } - - return new MessagePolicy(targetPolicies.toArray(new TargetPolicy[targetPolicies.size()]), mandatory); - } - - public static MessagePolicy getMessagePolicy(ProtectionDescriptor protectionDescriptor) { - if (protectionDescriptor == null) { - return null; - } - - String source = protectionDescriptor.getAttributeValue(AUTH_SOURCE); - String recipient = protectionDescriptor.getAttributeValue(AUTH_RECIPIENT); - - return getMessagePolicy(source, recipient); - } - - public static String getProviderID(MessageSecurityBindingDescriptor binding) { - String providerID = null; - if (binding != null) { - String layer = binding.getAttributeValue(AUTH_LAYER); - if (SOAP.equals(layer)) { - providerID = binding.getAttributeValue(PROVIDER_ID); - } - } - - return providerID; - } - - public static MessagePolicy[] getSOAPPolicies(MessageSecurityBindingDescriptor binding, String operation, boolean onePolicy) { - - MessagePolicy requestPolicy = null; - MessagePolicy responsePolicy = null; - - if (binding != null) { - List messageSecurityDescriptors = null; - String layer = binding.getAttributeValue(AUTH_LAYER); - if (SOAP.equals(layer)) { - messageSecurityDescriptors = binding.getMessageSecurityDescriptors(); - } - - if (messageSecurityDescriptors != null) { - if (onePolicy) { - if (messageSecurityDescriptors.size() > 0) { - MessageSecurityDescriptor msd = messageSecurityDescriptors.get(0); - requestPolicy = getMessagePolicy(msd.getRequestProtectionDescriptor()); - responsePolicy = getMessagePolicy(msd.getResponseProtectionDescriptor()); - } - } else { // try to match - MessageSecurityDescriptor matchMsd = null; - for (int i = 0; i < messageSecurityDescriptors.size(); i++) { - MessageSecurityDescriptor msd = messageSecurityDescriptors.get(i); - List msgDescs = msd.getMessageDescriptors(); - for (int j = i + 1; j < msgDescs.size(); j++) { - // XXX don't know how to get JavaMethod from operation - MessageDescriptor msgDesc = (MessageDescriptor) msgDescs.get(j); - String opName = msgDesc.getOperationName(); - if ((opName == null && matchMsd == null)) { - matchMsd = msd; - } else if (opName != null && opName.equals(operation)) { - matchMsd = msd; - break; - } - } - - if (matchMsd != null) { - requestPolicy = getMessagePolicy(matchMsd.getRequestProtectionDescriptor()); - responsePolicy = getMessagePolicy(matchMsd.getResponseProtectionDescriptor()); - } - } - } - } - } - - return new MessagePolicy[] { requestPolicy, responsePolicy }; - } - - public static boolean oneSOAPPolicy(MessageSecurityBindingDescriptor binding) { - boolean onePolicy = true; - List messageSecurityDescriptor = null; - - if (binding != null) { - if (SOAP.equals(binding.getAttributeValue(AUTH_LAYER))) { - messageSecurityDescriptor = binding.getMessageSecurityDescriptors(); - } - } - - if (messageSecurityDescriptor == null) { - return true; - } - - for (int i = 0; i < messageSecurityDescriptor.size(); i++) { - - MessageSecurityDescriptor msd = messageSecurityDescriptor.get(i); - - // Determine if all the different messageSecurityDesriptors have the - // same policy which will help us interpret the effective policy if - // we cannot determine the opcode of a request at runtime. - - for (int j = 0; j < messageSecurityDescriptor.size(); j++) { - if (j != i && !policiesAreEqual(msd, messageSecurityDescriptor.get(j))) { - onePolicy = false; - } - } - } - - return onePolicy; - } - - public static SunWebApp getSunWebApp(Map properties) { - if (properties == null) { - return null; - } - - return ((WebBundleDescriptor) properties.get(WEB_BUNDLE)).getSunDescriptor(); - } - - public static String getProviderID(SunWebApp sunWebApp) { - String providerID = null; - if (sunWebApp != null) { - providerID = sunWebApp.getAttributeValue(HTTPSERVLET_SECURITY_PROVIDER); - } - - return providerID; - } - - public static MessagePolicy[] getHttpServletPolicies(String authContextID) { - if (Boolean.valueOf(authContextID)) { - return new MessagePolicy[] { MANDATORY_POLICY, null }; - } - - return new MessagePolicy[] { OPTIONAL_POLICY, null }; - } - - public static CallbackHandler getDefaultCallbackHandler() { - // Get the default handler class - try { - return (CallbackHandler) doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (handlerClassName == null) { - handlerClassName = System.getProperty(HANDLER_CLASS_PROPERTY, DEFAULT_HANDLER_CLASS); - } - - return Class.forName(handlerClassName, true, loader) - .newInstance(); - } - }); - - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); - } - } - - private static boolean policiesAreEqual(MessageSecurityDescriptor reference, MessageSecurityDescriptor other) { - return (protectionDescriptorsAreEqual(reference.getRequestProtectionDescriptor(), other.getRequestProtectionDescriptor()) - && protectionDescriptorsAreEqual(reference.getResponseProtectionDescriptor(), other.getResponseProtectionDescriptor())); - } - - private static boolean protectionDescriptorsAreEqual(ProtectionDescriptor pd1, ProtectionDescriptor pd2) { - String authSource1 = pd1.getAttributeValue(AUTH_SOURCE); - String authRecipient1 = pd1.getAttributeValue(AUTH_RECIPIENT); - - String authSource2 = pd2.getAttributeValue(AUTH_SOURCE); - String authRecipient2 = pd2.getAttributeValue(AUTH_RECIPIENT); - - boolean sameAuthSource = (authSource1 == null && authSource2 == null) || (authSource1 != null && authSource1.equals(authSource2)); - boolean sameAuthRecipient = (authRecipient1 == null && authRecipient2 == null) - || (authRecipient1 != null && authRecipient1.equals(authRecipient2)); - - return sameAuthSource && sameAuthRecipient; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java index 369753c1155..c74d027dec1 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java @@ -37,12 +37,13 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation] +// Portions Copyright [2016-2024] [Payara Foundation] package com.sun.enterprise.security.jaspic; import static com.sun.logging.LogDomains.SECURITY_LOGGER; +import jakarta.security.auth.message.config.AuthConfigFactory; import java.beans.PropertyChangeEvent; import java.util.logging.Logger; @@ -62,7 +63,6 @@ import com.sun.enterprise.config.serverbeans.MessageSecurityConfig; import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; import com.sun.logging.LogDomains; /** @@ -80,59 +80,7 @@ public class MessageSecurityConfigEventListenerImpl implements ConfigListener { @Inject @Named(ServerEnvironment.DEFAULT_INSTANCE_NAME) private SecurityService service; - - /** - * @param event - Event to be processed. - * @throws AdminEventListenerException when the listener is unable to process the event. - */ - public NotProcessed handleUpdate(T instance) { - NotProcessed notProcessed = null; - logger.fine("MessageSecurityConfigEventListenerImpl - handleUpdate called"); - - // Handle only the MessageSecurityConfig. - if (instance instanceof MessageSecurityConfig) { - GFServerConfigProvider.loadConfigContext(service); - } else { - notProcessed = new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); - } - - return notProcessed; - } - - /** - * @param event Event to be processed. - * @throws AdminEventListenerException when the listener is unable to process the event. - */ - public NotProcessed handleDelete(T instance) { - NotProcessed notProcessed = null; - logger.fine("MessageSecurityConfigEventListenerImpl - handleDelete called"); - - if (instance instanceof MessageSecurityConfig) { - GFServerConfigProvider.loadConfigContext(service); - } else { - notProcessed = new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); - } - - return notProcessed; - } - - /** - * @param event Event to be processed. - * @throws AdminEventListenerException when the listener is unable to process the event. - */ - public NotProcessed handleCreate(T instance) { - NotProcessed notProcessed = null; - logger.fine("MessageSecurityConfigEventListenerImpl - handleCreate called"); - - if (instance instanceof MessageSecurityConfig) { - GFServerConfigProvider.loadConfigContext(service); - } else { - notProcessed = new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); - } - - return notProcessed; - } - + @Override public UnprocessedChangeEvents changed(PropertyChangeEvent[] events) { ConfigSupport.sortAndDispatch(events, new Changed() { @@ -151,15 +99,15 @@ public NotProcessed changed(TYPE type, Class chan switch (type) { case ADD: logger.fine("A new " + changedType.getName() + " was added : " + " " + changedInstance); - notProcessed = handleCreate(changedInstance); + notProcessed = handle(changedInstance); break; case CHANGE: logger.fine("A " + changedType.getName() + " was changed : " + changedInstance); - notProcessed = handleUpdate(changedInstance); + notProcessed = handle(changedInstance); break; case REMOVE: logger.fine("A " + changedType.getName() + " was removed : " + changedInstance); - notProcessed = handleDelete(changedInstance); + notProcessed = handle(changedInstance); break; } @@ -169,4 +117,16 @@ public NotProcessed changed(TYPE type, Class chan return null; } + + private NotProcessed handle(T instance) { + if (instance instanceof MessageSecurityConfig) { + AuthConfigFactory factory = AuthConfigFactory.getFactory(); + if (factory != null) { + factory.refresh(); + } + return null; + } + + return new NotProcessed("unimplemented: unknown instance: " + instance.getClass().getName()); + } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java deleted file mode 100644 index dd0c2a12440..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/ConfigParser.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import java.io.IOException; -import java.util.Map; -import java.util.Set; - - -/** - * AuthConfigImpl relies on a ConfigParser to read - * the module configuration. - * - *

The ConfigParser is expected to parse that information - * into the HashMap described below. - * - * @version %I%, %G% - */ -public interface ConfigParser { - - /** - * Initialize the parser. - * Passing null as argument means the parser is to find - * configuration object as necessary. - */ - public void initialize(Object config) throws IOException; - - /** - * Get the module configuration information. - * The information is returned as a HashMap. - * - *

The key is an intercept: - *

    - *
  • SOAP - *
  • HttpServlet - *
- * - *

The value is a AuthConfigImpl.InterceptEntry, which contains: - *

    - *
  • default provider ID - *
  • default type (client or server) - *
  • HashMap, where - * key = provider ID - * value = BaseAuthConfigImpl.IDEntry - *
- * - *

An IDEntry contains: - *

    - *
  • type (client or server) - *
  • moduleClassName - *
  • default requestPolicy - *
  • default responsePolicy - *
  • options - *
  • - *
- */ - public Map getConfigMap(); - - /** - * Get the name of layers with default set in domain.xml. - */ - public Set getLayersWithDefault(); -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java deleted file mode 100644 index 23cdb90706f..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFAuthConfigFactory.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import static java.util.Arrays.asList; - -import java.util.List; - -import com.sun.enterprise.security.SecurityServicesUtil; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; -import com.sun.jaspic.config.factory.BaseAuthConfigFactory; -import com.sun.jaspic.config.factory.EntryInfo; -import com.sun.jaspic.config.factory.RegStoreFileParser; - -/** - * This class implements methods in the abstract class AuthConfigFactory. - * - * @author Shing Wai Chan - */ -public class GFAuthConfigFactory extends BaseAuthConfigFactory { - - // MUST "hide" regStore in derived class. - private static RegStoreFileParser regStore; - - /** - * To specialize the defaultEntries passed to the RegStoreFileParser constructor, create another subclass of - * BaseAuthconfigFactory, that is basically a copy of this class, with a change to the third argument of the call to new - * ResSToreFileParser. to ensure runtime use of the the associated regStore, make sure that the new subclass also - * contains an implementation of the getRegStore method. - * - *

- * As done within this class, use the locks defined in - * BaseAuthConfigFactory to serialize access to the regStore (both within the class constructor, and within getRegStore) - * - *

- * All EntyInfo OBJECTS PASSED as defaultEntries MUST HAVE BEEN CONSTRUCTED USING THE FOLLOWING CONSTRUCTOR: - * - * EntryInfo(String className, Map properties); - * - */ - public GFAuthConfigFactory() { - if (doReadLocked(() -> regStore != null)) { - return; - } - - String userDir = System.getProperty("user.dir"); - - doWriteLocked(() -> { - if (regStore == null) { - initializeRegStore(userDir); - _loadFactory(); - } - }); - } - - /** - * @param userDir - */ - private static void initializeRegStore(String userDir) { - regStore = new RegStoreFileParser(userDir, CONF_FILE_NAME, getDefaultProviders()); - } - - @Override - protected RegStoreFileParser getRegStore() { - return doReadLocked(() -> regStore); - } - - /** - * Contains the default providers used when none are configured in a factory configuration file. - */ - private static List getDefaultProviders() { - WebServicesDelegate delegate = null; - SecurityServicesUtil securityServicesUtil = SecurityServicesUtil.getInstance(); - - if (securityServicesUtil != null) { - delegate = securityServicesUtil.getHabitat().getService(WebServicesDelegate.class); - } - - if (delegate != null) { - return asList( - new EntryInfo(delegate.getDefaultWebServicesProvider()), - new EntryInfo(GFServerConfigProvider.class.getName())); - } - - return asList(new EntryInfo(GFServerConfigProvider.class.getName())); - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java deleted file mode 100644 index 465f2d874c7..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/GFServerConfigProvider.java +++ /dev/null @@ -1,981 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getHttpServletPolicies; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getMessageSecurityBinding; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getProviderID; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getSOAPPolicies; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getSunWebApp; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.oneSOAPPolicy; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.IS_MANDATORY; -import static java.security.AccessController.doPrivileged; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; - -import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.logging.Logger; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -// jsr 196 interface types -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.config.AuthConfig; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ClientAuthModule; -import jakarta.security.auth.message.module.ServerAuthModule; - -import org.glassfish.internal.api.Globals; - -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.web.SunWebApp; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; -import com.sun.logging.LogDomains; - -/** - * This class implements the interface AuthConfigProvider. - * - * @author Shing Wai Chan - * @author Ronald Monzillo - */ -public class GFServerConfigProvider implements AuthConfigProvider { - - private static final Logger logger = LogDomains.getLogger(GFServerConfigProvider.class, LogDomains.SECURITY_LOGGER); - - public static final String SOAP = "SOAP"; - public static final String HTTPSERVLET = "HttpServlet"; - - protected static final String CLIENT = "client"; - protected static final String SERVER = "server"; - protected static final String MANAGES_SESSIONS_OPTION = "managessessions"; - - private static final String DEFAULT_PARSER_CLASS = "com.sun.enterprise.security.jaspic.config.ConfigDomainParser"; - - // since old api does not have subject in PasswordValdiationCallback, - // this is for old modules to pass group info back to subject - private static final ThreadLocal subjectLocal = new ThreadLocal(); - - protected static final ReadWriteLock rwLock = new ReentrantReadWriteLock(); - protected static final Map layerDefaultRegisIDMap = new HashMap(); - - // Mutable statics should be kept package private to eliminate - // the ability for subclasses to access them - static int epoch; - static String parserClassName; - static ConfigParser parser; - static boolean parserInitialized; - static AuthConfigFactory slaveFactory; - - // keep the slave from being visible outside - static AuthConfigProvider slaveProvider; - - protected AuthConfigFactory factory; - private WebServicesDelegate wsdelegate; - - public GFServerConfigProvider(Map properties, AuthConfigFactory factory) { - this.factory = factory; - initializeParser(); - - if (factory != null) { - boolean hasSlaveFactory = false; - try { - rwLock.readLock().lock(); - hasSlaveFactory = (slaveFactory != null); - } finally { - rwLock.readLock().unlock(); - } - - if (!hasSlaveFactory) { - try { - rwLock.writeLock().lock(); - if (slaveFactory == null) { - slaveFactory = factory; - } - } finally { - rwLock.writeLock().unlock(); - } - } - } - - boolean hasSlaveProvider = false; - try { - rwLock.readLock().lock(); - hasSlaveProvider = slaveProvider != null; - } finally { - rwLock.readLock().unlock(); - } - - if (!hasSlaveProvider) { - try { - rwLock.writeLock().lock(); - if (slaveProvider == null) { - slaveProvider = this; - } - } finally { - rwLock.writeLock().unlock(); - } - } - wsdelegate = Globals.get(WebServicesDelegate.class); - } - - private void initializeParser() { - try { - rwLock.readLock().lock(); - if (parserInitialized) { - return; - } - } finally { - rwLock.readLock().unlock(); - } - - try { - rwLock.writeLock().lock(); - if (!parserInitialized) { - parserClassName = System.getProperty("config.parser", DEFAULT_PARSER_CLASS); - loadParser(this, factory, null); - parserInitialized = true; - } - } finally { - rwLock.writeLock().unlock(); - } - } - - /** - * Instantiate and initialize module class - */ - static ModuleInfo createModuleInfo(Entry entry, CallbackHandler handler, String type, Map properties) throws AuthException { - try { - // Instantiate module using no-arg constructor - Object newModule = entry.newInstance(); - - Map map = properties; - Map entryOptions = entry.getOptions(); - - if (entryOptions != null) { - if (map == null) { - map = new HashMap<>(); - } else { - map = new HashMap<>(map); - } - map.putAll(entryOptions); - } - - // Initialize Module - if (SERVER.equals(type)) { - ServerAuthModule sam = (ServerAuthModule) newModule; - sam.initialize(entry.getRequestPolicy(), entry.getResponsePolicy(), handler, map); - } else { // CLIENT - ClientAuthModule cam = (ClientAuthModule) newModule; - cam.initialize(entry.getRequestPolicy(), entry.getResponsePolicy(), handler, map); - } - - return new ModuleInfo(newModule, map); - } catch (Exception e) { - if (e instanceof AuthException) { - throw (AuthException) e; - } - - throw (AuthException) new AuthException().initCause(e); - } - } - - /** - * Create an object of a given class. - * - * @param className - * - */ - private static Object createObject(String className) { - ClassLoader loader = getClassLoader(); - - if (System.getSecurityManager() != null) { - try { - return doPrivileged((PrivilegedExceptionAction) - () -> Class.forName(className, true, loader).newInstance()); - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); - } - } - - try { - return Class.forName(className, true, loader).newInstance(); - } catch (Throwable t) { - throw new RuntimeException(t); - } - } - - Entry getEntry(String intercept, String id, MessagePolicy requestPolicy, MessagePolicy responsePolicy, String type) { - - // get the parsed module config and DD information - - Map configMap; - - try { - rwLock.readLock().lock(); - configMap = parser.getConfigMap(); - } finally { - rwLock.readLock().unlock(); - } - - if (configMap == null) { - return null; - } - - // get the module config info for this intercept - - InterceptEntry intEntry = configMap.get(intercept); - if (intEntry == null || intEntry.idMap == null) { - if (logger.isLoggable(FINE)) { - logger.fine("module config has no IDs configured for [" + intercept + "]"); - } - - return null; - } - - // look up the DD's provider ID in the module config - - IDEntry idEntry = null; - if (id == null || (idEntry = (IDEntry) intEntry.idMap.get(id)) == null) { - - // either the DD did not specify a provider ID, - // or the DD-specified provider ID was not found - // in the module config. - // - // in either case, look for a default ID in the module config - - if (logger.isLoggable(FINE)) { - logger.fine("DD did not specify ID, " + "or DD-specified ID for [" + intercept + "] not found in config -- " - + "attempting to look for default ID"); - } - - String defaultID; - if (CLIENT.equals(type)) { - defaultID = intEntry.defaultClientID; - } else { - defaultID = intEntry.defaultServerID; - } - - idEntry = (IDEntry) intEntry.idMap.get(defaultID); - if (idEntry == null) { - - // did not find a default provider ID - - if (logger.isLoggable(FINE)) { - logger.fine("no default config ID for [" + intercept + "]"); - } - - return null; - } - } - - // We found the DD provider ID in the module config - // or we found a default module config - - // check provider-type - if (idEntry.type.indexOf(type) < 0) { - if (logger.isLoggable(FINE)) { - logger.fine("request type [" + type + "] does not match config type [" + idEntry.type + "]"); - } - - return null; - } - - // check whether a policy is set - MessagePolicy reqP = requestPolicy != null || responsePolicy != null ? requestPolicy : idEntry.requestPolicy; // default; - - MessagePolicy respP = requestPolicy != null || responsePolicy != null ? responsePolicy : idEntry.responsePolicy; // default; - - // optimization: if policy was not set, return null - if (reqP == null && respP == null) { - if (logger.isLoggable(FINE)) { - logger.fine("no policy applies"); - } - return null; - } - - // return the configured modules with the correct policies - - Entry entry = new Entry(idEntry.moduleClassName, reqP, respP, idEntry.options); - - if (logger.isLoggable(FINE)) { - logger.fine("getEntry for: " + intercept + " -- " + id + "\n module class: " + entry.moduleClassName + "\n options: " - + entry.options + "\n request policy: " + entry.requestPolicy + "\n response policy: " + entry.responsePolicy); - } - - return entry; - } - - /** - * Class representing a single AuthModule entry configured for an ID, interception point, and stack. - * - *

- * This class also provides a way for a caller to obtain an instance of the module listed in the entry by invoking the - * newInstance method. - */ - static class Entry { - - // For loading modules - private static final Class[] PARAMS = {}; - private static final Object[] ARGS = {}; - - private String moduleClassName; - private MessagePolicy requestPolicy; - private MessagePolicy responsePolicy; - private Map options; - - /** - * Construct a ConfigFile entry. - * - *

- * An entry encapsulates a single module and its related information. - * - * @param moduleClassName - * the module class name - * @param requestPolicy - * the request policy assigned to the module listed in this entry, which may be null. - * - * @param responsePolicy - * the response policy assigned to the module listed in this entry, which may be null. - * - * @param options - * the options configured for this module. - */ - Entry(String moduleClassName, MessagePolicy requestPolicy, MessagePolicy responsePolicy, Map options) { - this.moduleClassName = moduleClassName; - this.requestPolicy = requestPolicy; - this.responsePolicy = responsePolicy; - this.options = options; - } - - /** - * Return the request policy assigned to this module. - * - * @return the policy, which may be null. - */ - MessagePolicy getRequestPolicy() { - return requestPolicy; - } - - /** - * Return the response policy assigned to this module. - * - * @return the policy, which may be null. - */ - MessagePolicy getResponsePolicy() { - return responsePolicy; - } - - String getModuleClassName() { - return moduleClassName; - } - - Map getOptions() { - return options; - } - - /** - * Return a new instance of the module contained in this entry. - * - *

- * The default implementation of this method attempts to invoke the default no-args constructor of the module class. - * This method may be overridden if a different constructor should be invoked. - * - * @return a new instance of the module contained in this entry. - * - * @exception AuthException - * if the instantiation failed. - */ - Object newInstance() throws AuthException { - try { - return Class.forName(moduleClassName, true, getClassLoader()) - .getConstructor(PARAMS) - .newInstance(ARGS); - } catch (Exception e) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.provider_unable_to_load_authmodule", new String[] { moduleClassName, e.toString() }); - } - - AuthException ae = new AuthException(); - ae.initCause(e); - throw ae; - } - } - } - - public static class InterceptEntry { - String defaultClientID; - String defaultServerID; - Map idMap; - - public InterceptEntry(String defaultClientID, String defaultServerID, Map idMap) { - this.defaultClientID = defaultClientID; - this.defaultServerID = defaultServerID; - this.idMap = idMap; - } - - public Map getIdMap() { - return idMap; - } - - public void setIdMap(Map map) { - idMap = map; - } - - public String getDefaultClientID() { - return defaultClientID; - } - - public String getDefaultServerID() { - return defaultServerID; - } - } - - /** - * Get an instance of ClientAuthConfig from this provider. - * - *

- * The implementation of this method returns a ClientAuthConfig instance that describes the configuration of - * ClientAuthModules at a given message layer, and for use in an identified application context. - * - * @param layer - * a String identifying the message layer for the returned ClientAuthConfig object. This argument must not be - * null. - * - * @param appContext - * a String that identifies the messaging context for the returned ClientAuthConfig object. This argument - * must not be null. - * - * @param handler - * a CallbackHandler to be passed to the ClientAuthModules encapsulated by ClientAuthContext objects derived - * from the returned ClientAuthConfig. This argument may be null, in which case the implementation may assign - * a default handler to the configuration. - * - * @return a ClientAuthConfig Object that describes the configuration of ClientAuthModules at the message layer and - * messaging context identified by the layer and appContext arguments. This method does not return null. - * - * @exception AuthException - * if this provider does not support the assignment of a default CallbackHandler to the returned - * ClientAuthConfig. - * - * @exception SecurityException - * if the caller does not have permission to retrieve the configuration. - * - * The CallbackHandler assigned to the configuration must support the Callback objects required to be - * supported by the profile of this specification being followed by the messaging runtime. The - * CallbackHandler instance must be initialized with any application context needed to process the - * required callbacks on behalf of the corresponding application. - */ - public ClientAuthConfig getClientAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException { - return new GFClientAuthConfig(this, layer, appContext, handler); - } - - /** - * Get an instance of ServerAuthConfig from this provider. - * - *

- * The implementation of this method returns a ServerAuthConfig instance that describes the configuration of - * ServerAuthModules at a given message layer, and for a particular application context. - * - * @param layer - * a String identifying the message layer for the returned ServerAuthConfig object. This argument must not be - * null. - * - * @param appContext - * a String that identifies the messaging context for the returned ServerAuthConfig object. This argument - * must not be null. - * - * @param handler - * a CallbackHandler to be passed to the ServerAuthModules encapsulated by ServerAuthContext objects derived - * from thr returned ServerAuthConfig. This argument may be null, in which case the implementation may assign - * a default handler to the configuration. - * - * @return a ServerAuthConfig Object that describes the configuration of ServerAuthModules at a given message layer, and - * for a particular application context. This method does not return null. - * - * @exception AuthException - * if this provider does not support the assignment of a default CallbackHandler to the returned - * ServerAuthConfig. - * - * @exception SecurityException - * if the caller does not have permission to retrieve the configuration. - *

- * The CallbackHandler assigned to the configuration must support the Callback objects required to be - * supported by the profile of this specification being followed by the messaging runtime. The - * CallbackHandler instance must be initialized with any application context needed to process the - * required callbacks on behalf of the corresponding application. - */ - public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException { - return new GFServerAuthConfig(this, layer, appContext, handler); - } - - /** - * Causes a dynamic configuration provider to update its internal state such that any resulting change to its state is - * reflected in the corresponding authentication context configuration objects previously created by the provider within - * the current process context. - * - * @exception AuthException - * if an error occured during the refresh. - * - * @exception SecurityException - * if the caller does not have permission to refresh the provider. - */ - - public void refresh() { - loadParser(this, factory, null); - } - - /** - * this method is intended to be called by the admin configuration system when the corresponding config object has - * changed. It relies on the slaves, since it is a static method. - * - * @param config - * a config object of type understood by the parser. NOTE: there appears to be a thread saftey problem, and - * this method will fail if a slaveProvider has not been established prior to its call. - */ - public static void loadConfigContext(Object config) { - - boolean hasSlaveFactory = false; - rwLock.readLock().lock(); - try { - hasSlaveFactory = (slaveFactory != null); - } finally { - rwLock.readLock().unlock(); - } - - if (slaveProvider == null) { - if (logger.isLoggable(SEVERE)) { - logger.severe("unableToLoad.noSlaveProvider"); - } - return; - } - - if (!hasSlaveFactory) { - rwLock.writeLock().lock(); - try { - if (slaveFactory == null) { - slaveFactory = AuthConfigFactory.getFactory(); - } - } finally { - rwLock.writeLock().unlock(); - } - } - - loadParser(slaveProvider, slaveFactory, config); - } - - protected static void loadParser(AuthConfigProvider aProvider, AuthConfigFactory aFactory, Object config) { - rwLock.writeLock().lock(); - try { - ConfigParser nextParser; - int next = epoch + 1; - nextParser = (ConfigParser) createObject(parserClassName); - nextParser.initialize(config); - - if (aFactory != null && aProvider != null) { - Set layerSet = nextParser.getLayersWithDefault(); - for (String layer : layerDefaultRegisIDMap.keySet()) { - if (!layerSet.contains(layer)) { - String regisID = layerDefaultRegisIDMap.remove(layer); - aFactory.removeRegistration(regisID); - } - } - - for (String layer : layerSet) { - if (!layerDefaultRegisIDMap.containsKey(layer)) { - String regisID = aFactory.registerConfigProvider(aProvider, layer, null, - "GFServerConfigProvider: self registration"); - layerDefaultRegisIDMap.put(layer, regisID); - } - } - } - epoch = (next == 0 ? 1 : next); - parser = nextParser; - } catch (IOException ex) { - throw new RuntimeException(ex); - } finally { - rwLock.writeLock().unlock(); - } - } - - protected static ClassLoader getClassLoader() { - if (System.getSecurityManager() == null) { - return Thread.currentThread().getContextClassLoader(); - } - - return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - return Thread.currentThread().getContextClassLoader(); - } - }); - } - - // for old API - public static void setValidateRequestSubject(Subject subject) { - subjectLocal.set(subject); - } - - class GFAuthConfig implements AuthConfig { - - protected AuthConfigProvider provider; - protected String layer; - protected String appContext; - protected CallbackHandler handler; - protected String type; - protected String providerID; - protected boolean init; - protected boolean onePolicy; - protected MessageSecurityBindingDescriptor binding; - protected SunWebApp sunWebApp; - - protected GFAuthConfig(AuthConfigProvider provider, String layer, String appContext, CallbackHandler handler, String type) { - this.provider = provider; - this.layer = layer; - this.appContext = appContext; - this.handler = handler != null ? handler : AuthMessagePolicy.getDefaultCallbackHandler(); - this.type = type; - } - - /** - * Get the message layer name of this authentication context configuration object. - * - * @return the message layer name of this configuration object, or null if the configuration object pertains to an - * unspecified message layer. - */ - public String getMessageLayer() { - return layer; - } - - /** - * Get the application context identifier of this authentication context configuration object. - * - * @return the String identifying the application context of this configuration object or null if the configuration - * object pertains to an unspecified application context. - */ - public String getAppContext() { - return appContext; - } - - /** - * Get the authentication context identifier corresponding to the request and response objects encapsulated in - * messageInfo. - * - * See method AuthMessagePolicy. getHttpServletPolicies() for more details on why this method returns the String's - * "true" or "false" for AuthContextID. - * - * @param messageInfo - * a contextual Object that encapsulates the client request and server response objects. - * - * @return the authentication context identifier corresponding to the encapsulated request and response objects, or - * null. - * - * - * @throws IllegalArgumentException - * if the type of the message objects incorporated in messageInfo are not compatible with the message types - * supported by this authentication context configuration object. - */ - public String getAuthContextID(MessageInfo messageInfo) { - if (HTTPSERVLET.equals(layer)) { - return Boolean.valueOf((String) messageInfo.getMap().get(IS_MANDATORY)).toString(); - } - - if (SOAP.equals(layer) && wsdelegate != null) { - return wsdelegate.getAuthContextID(messageInfo); - } - - return null; - } - - // we should be able to replace the following with a method on packet - - /** - * Causes a dynamic anthentication context configuration object to update the internal state that it uses to process - * calls to its getAuthContext method. - * - * @exception AuthException - * if an error occured during the update. - * - * @exception SecurityException - * if the caller does not have permission to refresh the configuration object. - */ - public void refresh() { - loadParser(provider, factory, null); - } - - /** - * Used to determine whether or not the getAuthContext method of the authentication context configuration - * will return null for all possible values of authentication context identifier. - * - * @return false when getAuthContext will return null for all possible values of authentication context - * identifier. Otherwise, this method returns true. - */ - public boolean isProtected() { - // XXX TBD - return true; - } - - - CallbackHandler getCallbackHandler() { - return handler; - } - - protected ModuleInfo getModuleInfo(String authContextID, Map properties) throws AuthException { - if (!init) { - initialize(properties); - } - - MessagePolicy[] policies = null; - - if (HTTPSERVLET.equals(layer)) { - policies = getHttpServletPolicies(authContextID); - } else { - policies = getSOAPPolicies(binding, authContextID, onePolicy); - } - - MessagePolicy requestPolicy = policies[0]; - MessagePolicy responsePolicy = policies[1]; - - Entry entry = getEntry(layer, providerID, requestPolicy, responsePolicy, type); - - return entry != null ? createModuleInfo(entry, handler, type, properties) : null; - } - - // Lazy initialize this as SunWebApp is not available in RealmAdapter creation - private void initialize(Map properties) { - if (!init) { - if (HTTPSERVLET.equals(layer)) { - sunWebApp = getSunWebApp(properties); - providerID = getProviderID(sunWebApp); - onePolicy = true; - } else { - binding = getMessageSecurityBinding(layer, properties); - providerID = getProviderID(binding); - onePolicy = oneSOAPPolicy(binding); - } - - // HandlerContext need to be explicitly set by caller - init = true; - } - } - } - - class GFServerAuthConfig extends GFAuthConfig implements ServerAuthConfig { - - protected GFServerAuthConfig(AuthConfigProvider provider, String layer, String appContext, CallbackHandler handler) { - super(provider, layer, appContext, handler, SERVER); - } - - public ServerAuthContext getAuthContext(String authContextID, Subject serviceSubject, @SuppressWarnings("rawtypes") Map properties) throws AuthException { - @SuppressWarnings("unchecked") - ModuleInfo moduleInfo = getModuleInfo(authContextID, (Map) properties); - - if (moduleInfo != null && moduleInfo.getModule() != null) { - return new GFServerAuthContext(moduleInfo.getModule()); - } - - return null; - } - } - - class GFClientAuthConfig extends GFAuthConfig implements ClientAuthConfig { - - protected GFClientAuthConfig(AuthConfigProvider provider, String layer, String appContext, CallbackHandler handler) { - super(provider, layer, appContext, handler, CLIENT); - } - - public ClientAuthContext getAuthContext(String authContextID, Subject clientSubject, @SuppressWarnings("rawtypes") Map properties) throws AuthException { - @SuppressWarnings("unchecked") - ModuleInfo moduleInfo = getModuleInfo(authContextID, (Map) properties); - - if (moduleInfo != null && moduleInfo.getModule() != null) { - return new GFClientAuthContext(moduleInfo.getModule()); - } - - return null; - } - } - - static protected class GFServerAuthContext implements ServerAuthContext { - - private final ServerAuthModule module; - - GFServerAuthContext(ServerAuthModule module) { - this.module = module; - } - - public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.validateRequest(messageInfo, clientSubject, serviceSubject); - } - - public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.secureResponse(messageInfo, serviceSubject); - } - - public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - module.cleanSubject(messageInfo, subject); - } - } - - static protected class GFClientAuthContext implements ClientAuthContext { - - private final ClientAuthModule module; - - GFClientAuthContext(ClientAuthModule module) { - this.module = module; - } - - public AuthStatus secureRequest(MessageInfo messageInfo, Subject clientSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.secureRequest(messageInfo, clientSubject); - } - - public AuthStatus validateResponse(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - return module.validateResponse(messageInfo, clientSubject, serviceSubject); - } - - public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { - if (module == null) { - throw new AuthException(); - } - - module.cleanSubject(messageInfo, subject); - } - } - - /** - * parsed ID entry - */ - public static class IDEntry { - private String type; // provider type (client, server, client-server) - private String moduleClassName; - private MessagePolicy requestPolicy; - private MessagePolicy responsePolicy; - private Map options; - - public IDEntry(String type, String moduleClassName, MessagePolicy requestPolicy, MessagePolicy responsePolicy, Map options) { - this.type = type; - this.moduleClassName = moduleClassName; - this.requestPolicy = requestPolicy; - this.responsePolicy = responsePolicy; - this.options = options; - } - - public String getModuleClassName() { - return moduleClassName; - } - - public Map getOptions() { - return options; - } - - public MessagePolicy getRequestPolicy() { - return requestPolicy; - } - - public MessagePolicy getResponsePolicy() { - return responsePolicy; - } - - public String getType() { - return type; - } - } - - /** - * A data object contains module object and the corresponding map. - */ - protected static class ModuleInfo { - - private final Object module; - private final Map map; - - ModuleInfo(Object module, Map map) { - this.module = module; - this.map = map; - } - - @SuppressWarnings("unchecked") - T getModule() { - return (T) module; - } - - Map getMap() { - return map; - } - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java similarity index 91% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServices.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java index 4386c028fcd..dd401546776 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServices.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java @@ -37,20 +37,20 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jaspic.config; import java.util.Map; import javax.security.auth.callback.CallbackHandler; -import com.sun.enterprise.security.jaspic.AuthMessagePolicy; -import com.sun.jaspic.services.JaspicServices; +import org.glassfish.epicyro.config.helper.AuthMessagePolicy; +import org.glassfish.epicyro.services.BaseAuthenticationService; /** * This is based Helper class for 196 Configuration. */ -public abstract class PayaraJaspicServices extends JaspicServices { +public abstract class PayaraEpicyroServices extends BaseAuthenticationService { /** * Get the default callback handler diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServletServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java similarity index 86% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServletServices.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java index 8b4d5054cf5..ba6a29e30b4 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraJaspicServletServices.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java @@ -37,11 +37,11 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jaspic.config; import static com.sun.enterprise.deployment.web.LoginConfiguration.CLIENT_CERTIFICATION_AUTHENTICATION; -import static com.sun.enterprise.security.jaspic.config.GFServerConfigProvider.HTTPSERVLET; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.POLICY_CONTEXT; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.WEB_BUNDLE; @@ -58,15 +58,18 @@ import com.sun.enterprise.deployment.web.LoginConfiguration; import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; import com.sun.enterprise.security.jacc.JaccWebAuthorizationManager; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; -public class PayaraJaspicServletServices extends PayaraJaspicServices { +public class PayaraEpicyroServletServices extends PayaraEpicyroServices { public static final String AUTH_TYPE = "jakarta.servlet.http.authType"; + + public static final String HTTPSERVLET = "HttpServlet"; private String realmName; - public PayaraJaspicServletServices(String appContext, Map map, CallbackHandler callbackHandler, String realmName, boolean isSystemApp, String defaultSystemProviderID) { + public PayaraEpicyroServletServices(String appContext, Map map, CallbackHandler callbackHandler, String realmName, boolean isSystemApp, String defaultSystemProviderID) { WebBundleDescriptor webBundle = null; @@ -84,7 +87,7 @@ public PayaraJaspicServletServices(String appContext, Map map, C } // Set realmName before init - init(HTTPSERVLET, appContext, map, callbackHandler, Globals.get(WebServicesDelegate.class)); + init(HTTPSERVLET, appContext, map, callbackHandler, (RegistrationWrapperRemover) Globals.get(WebServicesDelegate.class)); if (webBundle != null) { String policyContextId = JaccWebAuthorizationManager.getContextID(webBundle); @@ -106,7 +109,7 @@ public PayaraJaspicServletServices(String appContext, Map map, C // Register the Payara JASPIC provider - String jaspicRegistrationId = factory.registerConfigProvider( + String jaspicRegistrationId = authConfigFactory.registerConfigProvider( configProvider, HTTPSERVLET, appContext, "Payara provider: " + HTTPSERVLET + ":" + appContext); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java deleted file mode 100644 index 0c6e6642cbb..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ConfigFile.java +++ /dev/null @@ -1,619 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import java.io.*; -import java.util.*; - -import java.lang.reflect.Method; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.AppConfigurationEntry; - -import com.sun.enterprise.security.jaspic.config.ConfigParser; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; -import com.sun.logging.LogDomains; - -/** - * This is a default file-based AuthConfig implementation. - * - * @version %I%, %G% - */ -class ConfigFile extends AuthConfig { - - // indicates the age of the configuration approximately in - // terms of the number of times refresh has been called - private int epoch; - - // parser class name - private String parserClassName; - - // parser - private ConfigParser parser; - - // package private for ConfigFileParser - static final String CLIENT = "client"; - static final String SERVER = "server"; - - private static final String DEFAULT_HANDLER_CLASS = "com.sun.enterprise.security.jaspic.callback.ContainerCallbackHandler"; - - private static final String DEFAULT_PARSER_CLASS = "com.sun.enterprise.security.jaspic.config.ConfigDomainParser"; - - private static final Logger logger = LogDomains.getLogger(ConfigFile.class, LogDomains.SECURITY_LOGGER); - - ConfigFile() throws IOException { - String propertyValue = System.getProperty("config.parser"); - if (propertyValue == null) { - parserClassName = DEFAULT_PARSER_CLASS; - } else { - parserClassName = propertyValue; - } - this.epoch = 1; - parser = ConfigFile.loadParser(parserClassName); - parser.initialize(null); - } - - /** - * Get a default ClientAuthContext. - * - * @return an instance of ConfigClient. - */ - @Override - public ClientAuthContext getClientAuthContext(String intercept, String id, AuthPolicy requestPolicy, AuthPolicy responsePolicy, - CallbackHandler handler) throws AuthException { - - ConfigFile.Entry[] entries = getEntries(intercept, id, requestPolicy, responsePolicy, CLIENT); - if (entries == null || entries.length == 0) { - return null; - } - - // instantiate and initialize modules up front as well - - if (handler == null) { - handler = ConfigFile.loadDefaultCallbackHandler(); - } else if (handler instanceof DependentCallbackHandler) { - handler = new DelegatingHandler(handler); - } - - for (int i = 0; i < entries.length; i++) { - entries[i].module = ConfigFile.createModule(entries[i], handler); - } - - return new ConfigClient(entries); - } - - /** - * Get a default ServerAuthContext. - * - * @return an instance of ConfigServer. - */ - @Override - public ServerAuthContext getServerAuthContext(String intercept, String id, AuthPolicy requestPolicy, AuthPolicy responsePolicy, - CallbackHandler handler) throws AuthException { - - ConfigFile.Entry[] entries = getEntries(intercept, id, requestPolicy, responsePolicy, SERVER); - if (entries == null || entries.length == 0) { - return null; - } - - // instantiate and initialize modules up front as well - - if (handler == null) { - handler = ConfigFile.loadDefaultCallbackHandler(); - } else if (handler instanceof DependentCallbackHandler) { - handler = new DelegatingHandler(handler); - } - - for (int i = 0; i < entries.length; i++) { - entries[i].module = ConfigFile.createModule(entries[i], handler); - } - - return new ConfigServer(entries); - } - - @Override - public void refresh() throws AuthException { - synchronized (this) { - ConfigParser nextParser; - int next = this.epoch + 1; - try { - nextParser = ConfigFile.loadParser(parserClassName); - } catch (IOException ioe) { - throw new AuthException(ioe.toString()); - } - this.epoch = (next == 0 ? 1 : next); - parser = nextParser; - } - } - - private ConfigFile.Entry[] getEntries(String intercept, String id, AuthPolicy requestPolicy, AuthPolicy responsePolicy, String type) { - - // get the parsed module config and DD information - - Map configMap; - - synchronized (parser) { - configMap = parser.getConfigMap(); - } - - if (configMap == null) { - return null; - } - - // get the module config info for this intercept - - GFServerConfigProvider.InterceptEntry intEntry = (GFServerConfigProvider.InterceptEntry) configMap.get(intercept); - if (intEntry == null || intEntry.getIdMap() == null) { - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("module config has no IDs configured for [" + intercept + "]"); - } - return null; - } - - // look up the DD's provider ID in the module config - - GFServerConfigProvider.IDEntry idEntry = null; - if (id == null || (idEntry = intEntry.getIdMap().get(id)) == null) { - - // either the DD did not specify a provider ID, - // or the DD-specified provider ID was not found - // in the module config. - // - // in either case, look for a default ID in the module config - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("DD did not specify ID, " + "or DD-specified ID for [" + intercept + "] not found in config -- " - + "attempting to look for default ID"); - } - - String defaultID; - if (CLIENT.equals(type)) { - defaultID = intEntry.getDefaultClientID(); - } else { - defaultID = intEntry.getDefaultServerID(); - } - - idEntry = intEntry.getIdMap().get(defaultID); - if (idEntry == null) { - - // did not find a default provider ID - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("no default config ID for [" + intercept + "]"); - } - return null; - } - } - - // we found the DD provider ID in the module config - // or we found a default module config - - // check provider-type - if (idEntry.getType().indexOf(type) < 0) { - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("request type [" + type + "] does not match config type [" + idEntry.getType() + "]"); - } - return null; - } - - // check whether a policy is set - AuthPolicy reqP, respP; - if (requestPolicy != null || responsePolicy != null) { - reqP = requestPolicy; - respP = responsePolicy; - } else if (idEntry.getRequestPolicy() != null || idEntry.getResponsePolicy() != null) { - // default - reqP = new AuthPolicy(idEntry.getRequestPolicy()); - respP = new AuthPolicy(idEntry.getResponsePolicy()); - } else { - // optimization: if policy was not set, return null - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("no policy applies"); - } - return null; - } - - // return the configured modules with the correct policies - - // ConfigFile.Entry[] entries = new Entry[idEntry.modules.size()]; - ConfigFile.Entry[] entries = new Entry[1]; - for (int i = 0; i < entries.length; i++) { - // Login Bridge profile? - entries[i] = new ConfigFile.Entry(reqP, respP, idEntry.getModuleClassName(), - AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, idEntry.getOptions()); - } - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("getEntries found " + entries.length + " entries for: " + intercept + " -- " + id); - - for (int i = 0; i < entries.length; i++) { - logger.fine("Entry " + (i + 1) + ":" + "\n module class: " + entries[i].getLoginModuleName() + "\n flag: " - + entries[i].getControlFlag() + "\n options: " + entries[i].getOptions() + "\n request policy: " - + entries[i].requestPolicy + "\n response policy: " + entries[i].responsePolicy); - } - - } - - return entries; - } - - /** - * get a custom config file parser - * - * XXX custom file that can be used in place of [domain|sun-acc].xml - */ - private static ConfigParser loadParser(String className) throws IOException { - try { - - final String finalClassName = className; - final ClassLoader finalLoader = AuthConfig.getClassLoader(); - - return (ConfigParser) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - Class c = Class.forName(finalClassName, true, finalLoader); - return c.newInstance(); - } - }); - } catch (java.security.PrivilegedActionException pae) { - IOException iex = new IOException(pae.getException().toString()); - iex.initCause(pae.getException()); - throw iex; - } - } - - /** - * get the default callback handler - */ - private static CallbackHandler loadDefaultCallbackHandler() throws AuthException { - - // get the default handler class - try { - - final ClassLoader finalLoader = AuthConfig.getClassLoader(); - - return (CallbackHandler) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - - String className = DEFAULT_HANDLER_CLASS; - Class c = Class.forName(className, true, finalLoader); - return c.newInstance(); - } - }); - } catch (java.security.PrivilegedActionException pae) { - AuthException aex = new AuthException(pae.getException().toString()); - aex.initCause(pae.getException()); - throw aex; - } - } - - /** - * Instantiate+initialize module class - */ - private static Object createModule(ConfigFile.Entry entry, CallbackHandler handler) throws AuthException { - try { - - // instantiate module using no-arg constructor - - Object newModule = entry.newInstance(); - - // initialize module - - Object[] initArgs = { entry.getRequestPolicy(), entry.getResponsePolicy(), handler, entry.getOptions() }; - - try { - Method initMethod = newModule.getClass().getMethod(AuthContext.INIT, AuthPolicy.class, AuthPolicy.class, - CallbackHandler.class, Map.class); - initMethod.invoke(newModule, initArgs); - // return the new module - return newModule; - } catch (Exception ex) { - throw new SecurityException( - "could not invoke " + AuthContext.INIT + " method in module: " + newModule.getClass().getName() + " " + ex, ex); - } - - } catch (Exception e) { - if (e instanceof AuthException) { - throw (AuthException) e; - } - AuthException ae = new AuthException(); - ae.initCause(e); - throw ae; - } - } - - /** - * Class representing a single AuthModule entry configured for an ID, interception point, and stack. - * - *

- * An instance of this class contains the same information as its superclass, AppConfigurationEntry. It additionally - * stores the request and response policy assigned to this module. - * - *

- * This class also provides a way for a caller to obtain an instance of the module listed in the entry by invoking the - * newInstance method. - */ - static class Entry extends javax.security.auth.login.AppConfigurationEntry { - - // for loading modules - private static final Class[] PARAMS = {}; - private static final Object[] ARGS = {}; - - private AuthPolicy requestPolicy; - private AuthPolicy responsePolicy; - Object module = null; // convenience location to store instance - - // package private for AuthContext - - /** - * Construct a ConfigFile entry. - * - *

- * An entry encapsulates a single module and its related information. - * - * @param requestPolicy the request policy assigned to the module listed in this entry, which may be null. - * - * @param responsePolicy the response policy assigned to the module listed in this entry, which may be null. - * - * @param moduleClass the fully qualified class name of the module. - * - * @param flag the module control flag. This value must either be REQUIRED, REQUISITE, SUFFICIENT, or OPTIONAL. - * - * @param options the options configured for this module. - */ - Entry(AuthPolicy requestPolicy, AuthPolicy responsePolicy, String moduleClass, AppConfigurationEntry.LoginModuleControlFlag flag, - Map options) { - super(moduleClass, flag, options); - this.requestPolicy = requestPolicy; - this.responsePolicy = responsePolicy; - } - - /** - * Return the request policy assigned to this module. - * - * @return the policy, which may be null. - */ - AuthPolicy getRequestPolicy() { - return requestPolicy; - } - - /** - * Return the response policy assigned to this module. - * - * @return the policy, which may be null. - */ - AuthPolicy getResponsePolicy() { - return responsePolicy; - } - - /** - * Return a new instance of the module contained in this entry. - * - *

- * The default implementation of this method attempts to invoke the default no-args constructor of the module class. - * This method may be overridden if a different constructor should be invoked. - * - * @return a new instance of the module contained in this entry. - * - * @exception AuthException if the instantiation failed. - */ - Object newInstance() throws AuthException { - try { - final ClassLoader finalLoader = AuthConfig.getClassLoader(); - String clazz = getLoginModuleName(); - Class c = Class.forName(clazz, true, finalLoader); - java.lang.reflect.Constructor constructor = c.getConstructor(PARAMS); - return constructor.newInstance(ARGS); - } catch (Exception e) { - AuthException ae = new AuthException(); - ae.initCause(e); - throw ae; - } - } - } - - /** - * parsed Intercept entry - */ - /* - * static class InterceptEntry { String defaultClientID; String defaultServerID; HashMap idMap; InterceptEntry(String - * defaultClientID, String defaultServerID, HashMap idMap) { this.defaultClientID = defaultClientID; - * this.defaultServerID = defaultServerID; this.idMap = idMap; } } - */ - - /** - * parsed ID entry - */ - /* - * static class IDEntry { private String type; // provider type (client, server, client-server) private AuthPolicy - * requestPolicy; private AuthPolicy responsePolicy; private ArrayList modules; IDEntry(String type, AuthPolicy - * requestPolicy, AuthPolicy responsePolicy, ArrayList modules) { this.type = type; this.modules = modules; - * this.requestPolicy = requestPolicy; this.responsePolicy = responsePolicy; } // XXX delete this later IDEntry(String - * type, String requestPolicy, String responsePolicy, ArrayList modules) { this.type = type; if (requestPolicy != null) - * { this.requestPolicy = new AuthPolicy(AuthPolicy.SOURCE_AUTH_SENDER, true, // recipient-auth true); // beforeContent - * } if (responsePolicy != null) { this.responsePolicy = new AuthPolicy(AuthPolicy.SOURCE_AUTH_CONTENT, true, // - * recipient-auth false); // beforeContent } this.modules = modules; } } - */ - - /** - * Default implementation of ClientAuthContext. - */ - private static class ConfigClient implements ClientAuthContext { - - // class that does all the work - private AuthContext context; - - ConfigClient(Entry[] entries) throws AuthException { - context = new AuthContext(entries, logger); - } - - @Override - public void secureRequest(AuthParam param, Subject subject, Map sharedState) throws AuthException { - - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.SECURE_REQUEST, args); - } - - @Override - public void validateResponse(AuthParam param, Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.VALIDATE_RESPONSE, args); - } - - @Override - public void disposeSubject(Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { subject, sharedState }; - context.invoke(AuthContext.DISPOSE_SUBJECT, args); - } - } - - /** - * Default implementation of ServerAuthContext. - */ - private static class ConfigServer implements ServerAuthContext { - - // class that does all the work - private AuthContext context; - - ConfigServer(Entry[] entries) throws AuthException { - - context = new AuthContext(entries, logger); - } - - @Override - public void validateRequest(AuthParam param, Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.VALIDATE_REQUEST, args); - } - - @Override - public void secureResponse(AuthParam param, Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { param, subject, sharedState }; - context.invoke(AuthContext.SECURE_RESPONSE, args); - } - - @Override - public void disposeSubject(Subject subject, Map sharedState) throws AuthException { - // invoke modules - Object[] args = { subject, sharedState }; - context.invoke(AuthContext.DISPOSE_SUBJECT, args); - } - - @Override - public boolean managesSessions(Map sharedState) throws AuthException { - - // invoke modules - Object[] args = { sharedState }; - Object[] rValues = null; - - try { - rValues = context.invoke(AuthContext.MANAGES_SESSIONS, args); - } catch (AuthException ae) { - // this new method may not be implemeneted - // by old modules - if (!(ae.getCause() instanceof NoSuchMethodException)) { - throw ae; - } - } - - boolean rvalue = false; - - for (int i = 0; rValues != null && i < rValues.length; i++) { - if (rValues[i] != null) { - boolean thisValue = ((Boolean) rValues[i]).booleanValue(); - rvalue = rvalue | thisValue; - } - } - - return rvalue; - } - } - - private static class DelegatingHandler implements CallbackHandler { - - CallbackHandler handler; - - CallbackHandler defaultHandler; - - private DelegatingHandler(CallbackHandler cbh) { - handler = cbh; - try { - defaultHandler = ConfigFile.loadDefaultCallbackHandler(); - } catch (Exception e) { - defaultHandler = null; - } - } - - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - if (defaultHandler == null) { - handler.handle(callbacks); - } else { - Callback[] oneCallback = new Callback[1]; - for (int i = 0; i < callbacks.length; i++) { - - boolean tryDefault = false; - - oneCallback[0] = callbacks[i]; - try { - handler.handle(oneCallback); - } catch (UnsupportedCallbackException uce) { - tryDefault = true; - } - if (tryDefault) { - defaultHandler.handle(oneCallback); - } - } - } - } - } - -} diff --git a/appserver/security/jaspic-provider-framework/osgi.bundle b/appserver/security/jaspic-provider-framework/osgi.bundle index c0460d0b2f0..46a378460ef 100644 --- a/appserver/security/jaspic-provider-framework/osgi.bundle +++ b/appserver/security/jaspic-provider-framework/osgi.bundle @@ -37,8 +37,8 @@ # only if the new code is made subject to such option by the copyright # holder. # --exportcontents: \ - com.sun.jaspic.services; \ +# Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] +-exportcontents: \ com.sun.jaspic.config.delegate; \ com.sun.jaspic.config.factory; \ com.sun.jaspic.config.jaas; \ diff --git a/appserver/security/jaspic-provider-framework/pom.xml b/appserver/security/jaspic-provider-framework/pom.xml index cb53f558935..e923a2c6615 100644 --- a/appserver/security/jaspic-provider-framework/pom.xml +++ b/appserver/security/jaspic-provider-framework/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -83,5 +83,9 @@ org.glassfish.soteria jakarta.security.enterprise + + org.glassfish.epicyro + epicyro + diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java deleted file mode 100644 index f46ad3325e8..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/AuthConfigFileFactory.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -/** - * - * @author ronmonzillo - */ -public class AuthConfigFileFactory extends BaseAuthConfigFactory { - - // MUST "hide" regStore in derived class. - private static volatile RegStoreFileParser regStore; - - /** - * To specialize the defaultEntries passed to the {@link RegStoreFileParser} constructor, create another subclass of - * BaseAuthconfigFactory, that is basically a copy of this class, with a change to the third argument of the call to new - * ResSToreFileParser. To ensure runtime use of the the associated regStore, make sure that the new subclass also - * contains an implementation of the getRegStore method. - * - *

- * As done within this class, use the locks defined in BaseAuthConfigFactory to serialize access to the regStore (both - * within the class constructor, and within getRegStore) - *

- * - *

- * All EentyInfo OBJECTS PASSED as default Entries MUST HAVE BEEN CONSTRUCTED USING THE FOLLOWING CONSTRUCTOR: - * EntryInfo(String className, Map properties); - * - *

- * - */ - public AuthConfigFileFactory() { - if (doReadLocked(() -> regStore != null)) { - return; - } - - String userDir = System.getProperty("user.dir"); - - doWriteLocked(() -> { - if (regStore == null) { - regStore = new RegStoreFileParser(userDir, CONF_FILE_NAME, null); - _loadFactory(); - } - }); - } - - @Override - protected RegStoreFileParser getRegStore() { - return doReadLocked(() -> regStore); - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java deleted file mode 100644 index 851a6f0bccb..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/BaseAuthConfigFactory.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright 2018-2024 Payara Foundation and/or its affiliates -package com.sun.jaspic.config.factory; - -import static com.sun.jaspic.config.helper.JASPICLogManager.JASPIC_LOGGER; -import static com.sun.jaspic.config.helper.JASPICLogManager.RES_BUNDLE; -import static java.util.logging.Level.WARNING; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.function.Supplier; -import java.util.logging.Logger; - -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.RegistrationListener; -import jakarta.security.auth.message.module.ServerAuthModule; -import jakarta.servlet.ServletContext; -import static org.glassfish.soteria.Utils.isEmpty; - - -/** - * This class implements methods in the abstract class AuthConfigFactory. - * - * @author Shing Wai Chan - */ -public abstract class BaseAuthConfigFactory extends AuthConfigFactory { - - private static final Logger logger = Logger.getLogger(JASPIC_LOGGER, RES_BUNDLE); - - private static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); - - public static final Lock readLock = readWriteLock.readLock(); - public static final Lock writeLock = readWriteLock.writeLock(); - - private static Map idToProviderMap; - private static Map idToRegistrationContextMap; - private static Map> idToRegistrationListenersMap; - private static Map> providerToIdsMap; - - protected static final String CONF_FILE_NAME = "auth.conf"; - private static final String CONTEXT_REGISTRATION_ID = "org.glassfish.security.message.registrationId"; - - /** - * Get a registered AuthConfigProvider from the factory. - * - * Get the provider of ServerAuthConfig and/or ClientAuthConfig objects registered for the identified message layer and - * application context. - * - *

- * All factories shall employ the following precedence rules to select the registered AuthConfigProvider that matches - * (via matchConstructors) the layer and appContext arguments: - *

    - *
  • The provider that is specifically registered for both the corresponding message layer and appContext shall be - * selected. - *
  • if no provider is selected according to the preceding rule, the provider specifically registered for the - * corresponding appContext and for all message layers shall be selected. - *
  • if no provider is selected according to the preceding rules, the provider specifically registered for the - * corresponding message layer and for all appContexts shall be selected. - *
  • if no provider is selected according to the preceding rules, the provider registered for all message layers and - * for all appContexts shall be selected. - *
  • if no provider is selected according to the preceding rules, the factory shall terminate its search for a - * registered provider. - *
- * - * @param layer a String identifying the message layer for which the registered AuthConfigProvider is to be returned. - * This argument may be null. - * - * @param appContext a String that identifies the application messaging context for which the registered - * AuthConfigProvider is to be returned. This argument may be null. - * - * @param listener the RegistrationListener whose notify method is to be invoked if the corresponding - * registration is unregistered or replaced. The value of this argument may be null. - * - * @return the implementation of the AuthConfigProvider interface registered at the factory for the layer and appContext - * or null if no AuthConfigProvider is selected. - * - */ - @Override - public AuthConfigProvider getConfigProvider(String layer, String appContext, RegistrationListener listener) { - if (listener == null) { - return doReadLocked(() -> getConfigProviderUnderLock(layer, appContext, null)); - } - - return doWriteLocked(() -> getConfigProviderUnderLock(layer, appContext, listener)); - } - - /** - * Registers within the factory, a provider of ServerAuthConfig and/or ClientAuthConfig objects for a message layer and - * application context identifier. - * - *

- * At most one registration may exist within the factory for a given combination of message layer and appContext. Any - * pre-existing registration with identical values for layer and appContext is replaced by a subsequent registration. - * When replacement occurs, the registration identifier, layer, and appContext identifier remain unchanged, and the - * AuthConfigProvider (with initialization properties) and description are replaced. - * - *

- * Within the lifetime of its Java process, a factory must assign unique registration identifiers to registrations, and - * must never assign a previously used registration identifier to a registration whose message layer and or appContext - * identifier differ from the previous use. - * - *

- * Programmatic registrations performed via this method must update (according to the replacement rules described - * above), the persistent declarative representation of provider registrations employed by the factory constructor. - * - * @param className the fully qualified name of an AuthConfigProvider implementation class. This argument must not be - * null. - * - * @param properties a Map object containing the initialization properties to be passed to the provider constructor. - * This argument may be null. When this argument is not null, all the values and keys occuring in the Map must be of - * type String. - * - * @param layer a String identifying the message layer for which the provider will be registered at the factory. A null - * value may be passed as an argument for this parameter, in which case, the provider is registered at all layers. - * - * @param appContext a String value that may be used by a runtime to request a configuration object from this provider. - * A null value may be passed as an argument for this parameter, in which case, the provider is registered for all - * configuration ids (at the indicated layers). - * - * @param description a text String describing the provider. this value may be null. - * - * @return a String identifier assigned by the factory to the provider registration, and that may be used to remove the - * registration from the provider. - * - * @exception SecurityException If the provider construction (given a non-null className) or - * registration fails. - * - * @exception AuthException if the provider construction or registration fails. - */ - @Override - @SuppressWarnings("unchecked") - public String registerConfigProvider(String className, @SuppressWarnings("rawtypes") Map properties, String layer, String appContext, - String description) { - return _register(_constructProvider(className, properties, null), properties, layer, appContext, description, true); - } - - @Override - public String registerConfigProvider(AuthConfigProvider provider, String layer, String appContext, String description) { - return _register(provider, null, layer, appContext, description, false); - } - - /** - * Remove the identified provider registration from the factory and invoke any listeners associated with the removed - * registration. - * - * @param registrationID a String that identifies a provider registration at the factory - * - * @return true if there was a registration with the specified identifier and it was removed. Return false if the - * registraionID was invalid. - * - */ - @Override - public boolean removeRegistration(String registrationID) { - return _unRegister(registrationID); - } - - /** - * Disassociate the listener from all the provider registrations whose layer and appContext values are matched by the - * corresponding arguments to this method. - * - * @param listener the RegistrationListener to be detached. - * - * @param layer a String identifying the message layer or null. - * - * @param appContext a String value identifying the application context or null. - * - * @return an array of String values where each value identifies a provider registration from which the listener was - * removed. This method never returns null; it returns an empty array if the listener was not removed from any - * registrations. - * - */ - @Override - public String[] detachListener(RegistrationListener listener, String layer, String appContext) { - List removedListenerIds = new ArrayList<>(); - String registrationId = getRegistrationID(layer, appContext); - - doWriteLocked(() -> { - for (Entry> entry : idToRegistrationListenersMap.entrySet()) { - String targetID = entry.getKey(); - if (regIdImplies(registrationId, targetID)) { - List listeners = entry.getValue(); - if (listeners != null && listeners.remove(listener)) { - removedListenerIds.add(targetID); - } - } - } - }); - - return removedListenerIds.toArray(new String[removedListenerIds.size()]); - } - - /** - * Get the registration identifiers for all registrations of the provider instance at the factory. - * - * @param provider the AuthConfigurationProvider whose registration identifiers are to be returned. This argument may be - * null, in which case, it indicates that the the id's of all active registration within the factory are returned. - * - * @return an array of String values where each value identifies a provider registration at the factory. This method - * never returns null; it returns an empty array when their are no registrations at the factory for the identified - * provider. - */ - @Override - public String[] getRegistrationIDs(AuthConfigProvider provider) { - return doReadLocked(() -> { - Collection registrationIDs = null; - - if (provider != null) { - registrationIDs = providerToIdsMap.get(provider); - } else { - Collection> collList = providerToIdsMap.values(); - if (collList != null) { - registrationIDs = new HashSet<>(); - for (List listIds : collList) { - if (listIds != null) { - registrationIDs.addAll(listIds); - } - } - } - } - - return registrationIDs != null ? registrationIDs.toArray(new String[registrationIDs.size()]) : new String[0]; - }); - } - - /** - * Get the the registration context for the identified registration. - * - * @param registrationID a String that identifies a provider registration at the factory - * - * @return a RegistrationContext or null. When a Non-null value is returned, it is a copy of the registration context - * corresponding to the registration. Null is returned when the registration identifier does not correspond to an active - * registration - */ - @Override - public RegistrationContext getRegistrationContext(String registrationID) { - return doReadLocked(() -> idToRegistrationContextMap.get(registrationID)); - } - - /** - * Cause the factory to reprocess its persistent declarative representation of provider registrations. - * - *

- * A factory should only replace an existing registration when a change of provider implementation class or - * initialization properties has occurred. - * - * @exception AuthException if an error occurred during the reinitialization. - * - * @exception SecurityException If an error occurred during the reinitialization. - */ - @Override - public void refresh() { - Map> preExistingListenersMap = doWriteLocked(() -> loadFactory()); - - // Notify pre-existing listeners after (re)loading factory - if (preExistingListenersMap != null) { - notifyListeners(preExistingListenersMap); - } - } - - abstract protected RegStoreFileParser getRegStore(); - - private AuthConfigProvider getConfigProviderUnderLock(String layer, String appContext, RegistrationListener listener) { - AuthConfigProvider provider = null; - String registrationID = getRegistrationID(layer, appContext); - - boolean providerFound = false; - if (idToProviderMap.containsKey(registrationID)) { - provider = idToProviderMap.get(registrationID); - providerFound = true; - } - - if (!providerFound) { - String matchedID = getRegistrationID(null, appContext); - if (idToProviderMap.containsKey(matchedID)) { - provider = idToProviderMap.get(matchedID); - providerFound = true; - } - } - - if (!providerFound) { - String matchedID = getRegistrationID(layer, null); - if (idToProviderMap.containsKey(matchedID)) { - provider = idToProviderMap.get(matchedID); - providerFound = true; - } - } - - if (!providerFound) { - String matchedID = getRegistrationID(null, null); - if (idToProviderMap.containsKey(matchedID)) { - provider = idToProviderMap.get(matchedID); - } - } - - if (listener != null) { - List listeners = idToRegistrationListenersMap.computeIfAbsent( - registrationID, e -> new ArrayList()); - - if (!listeners.contains(listener)) { - listeners.add(listener); - } - } - - return provider; - } - - private static String getRegistrationID(String layer, String appContext) { - - // (layer, appContext) -> __3_ - // (layer, null) -> __2 - // (null, appContext) -> __1 - // (null, null) -> __0 - - if (layer != null) { - return appContext != null ? "__3" + layer.length() + "_" + layer + appContext : "__2" + layer; - } - - return appContext != null ? "__1" + appContext : "__0"; - } - - /** - * This API decomposes the given registration ID into layer and appContext. - * - * @param registrationId - * @return a String array with layer and appContext - */ - private static String[] decomposeRegistrationId(String registrationId) { - String layer = null; - String appContext = null; - - if (registrationId.equals("__0")) { - // null, null - } else if (registrationId.startsWith("__1")) { - appContext = (registrationId.length() == 3) ? "" : registrationId.substring(3); - } else if (registrationId.startsWith("__2")) { - layer = (registrationId.length() == 3) ? "" : registrationId.substring(3); - } else if (registrationId.startsWith("__3")) { - int ind = registrationId.indexOf('_', 3); - if (registrationId.length() > 3 && ind > 0) { - String numberString = registrationId.substring(3, ind); - int n; - try { - n = Integer.parseInt(numberString); - } catch (Exception ex) { - throw new IllegalArgumentException(); - } - layer = registrationId.substring(ind + 1, ind + 1 + n); - appContext = registrationId.substring(ind + 1 + n); - } else { - throw new IllegalArgumentException(); - } - } else { - throw new IllegalArgumentException(); - } - - return new String[] { layer, appContext }; - } - - private static AuthConfigProvider _constructProvider(String className, Map properties, AuthConfigFactory factory) { - AuthConfigProvider provider = null; - - if (className != null) { - try { - provider = (AuthConfigProvider) Class.forName(className, true, Thread.currentThread().getContextClassLoader()) - .getConstructor(Map.class, AuthConfigFactory.class) - .newInstance(new Object[] { properties, factory }); - } catch (Throwable t) { - Throwable cause = t.getCause(); - logger.log(WARNING, "jaspic.factory_unable_to_load_provider", - new Object[] { className, t.toString(), cause == null ? "cannot determine" : cause.toString() }); - } - } - - return provider; - } - - // XXX need to update persistent state and notify effected listeners - private String _register(AuthConfigProvider provider, Map properties, String layer, String appContext, - String description, boolean persistent) { - String registrationId = getRegistrationID(layer, appContext); - RegistrationContext registrationContext = new RegistrationContextImpl(layer, appContext, description, persistent); - - Map> listenerMap = doWriteLocked( - () -> register(provider, properties, persistent, registrationId, registrationContext)); - - // Outside write lock to prevent dead lock - notifyListeners(listenerMap); - - return registrationId; - } - - private Map> register(AuthConfigProvider provider, Map properties, - boolean persistent, String registrationId, RegistrationContext registrationContext) { - RegistrationContext previousRegistrationContext = idToRegistrationContextMap.get(registrationId); - AuthConfigProvider previousProvider = idToProviderMap.get(registrationId); - - // Handle the persistence first - so that any exceptions occur before - // the actual registration happens - if (persistent) { - _storeRegistration(registrationContext, provider, properties); - } else if (previousRegistrationContext != null && previousRegistrationContext.isPersistent()) { - _deleteStoredRegistration(previousRegistrationContext); - } - - if (idToProviderMap.containsKey(registrationId)) { - List previousRegistrationsIds = providerToIdsMap.get(previousProvider); - previousRegistrationsIds.remove(registrationId); - if (previousRegistrationsIds.isEmpty()) { - providerToIdsMap.remove(previousProvider); - } - } - - idToProviderMap.put(registrationId, provider); - idToRegistrationContextMap.put(registrationId, registrationContext); - - List registrationIds = providerToIdsMap.computeIfAbsent(provider, e -> new ArrayList()); - - if (!registrationIds.contains(registrationId)) { - registrationIds.add(registrationId); - } - - return getEffectedListeners(registrationId); - } - - // XXX need to update persistent state and notify effected listeners - private boolean _unRegister(String registrationId) { - boolean hasProvider = false; - Map> listenerMap; - - writeLock.lock(); - try { - RegistrationContext registrationContext = idToRegistrationContextMap.remove(registrationId); - hasProvider = idToProviderMap.containsKey(registrationId); - AuthConfigProvider provider = idToProviderMap.remove(registrationId); - - List registrationIds = providerToIdsMap.get(provider); - if (registrationIds != null) { - registrationIds.remove(registrationId); - } - - if (registrationIds == null || registrationIds.isEmpty()) { - providerToIdsMap.remove(provider); - } - - if (!hasProvider) { - return false; - } - - listenerMap = getEffectedListeners(registrationId); - if (registrationContext != null && registrationContext.isPersistent()) { - _deleteStoredRegistration(registrationContext); - } - } finally { - writeLock.unlock(); - } - - // Outside write lock to prevent dead lock - notifyListeners(listenerMap); - - return hasProvider; - } - - private Map> loadFactory() { - Map> oldId2RegisListenersMap = idToRegistrationListenersMap; - - _loadFactory(); - - return oldId2RegisListenersMap; - } - - // ### The following methods implement the factory's persistence layer - - protected void _loadFactory() { - try { - initializeMaps(); - - List persistedEntries = getRegStore().getPersistedEntries(); - - for (EntryInfo info : persistedEntries) { - if (info.isConstructorEntry()) { - _constructProvider(info.getClassName(), info.getProperties(), this); - } else { - boolean first = true; - AuthConfigProvider configProvider = null; - for (RegistrationContext context : info.getRegistrationContexts()) { - if (first) { - configProvider = _constructProvider(info.getClassName(), info.getProperties(), null); - } - - _loadRegistration(configProvider, context.getMessageLayer(), context.getAppContext(), context.getDescription()); - } - } - } - } catch (Exception e) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_auth_config_loader_failure", e); - } - } - } - - /** - * Initialize the static maps in a static method - */ - private static void initializeMaps() { - idToProviderMap = new HashMap<>(); - idToRegistrationContextMap = new HashMap<>(); - idToRegistrationListenersMap = new HashMap<>(); - providerToIdsMap = new HashMap<>(); - } - - private static String _loadRegistration(AuthConfigProvider provider, String layer, String appContext, String description) { - - RegistrationContext registrationContext = new RegistrationContextImpl(layer, appContext, description, true); - String registrationId = getRegistrationID(layer, appContext); - - AuthConfigProvider previousProvider = idToProviderMap.get(registrationId); - - boolean wasRegistered = idToProviderMap.containsKey(registrationId); - if (wasRegistered) { - List previousRegistrationIds = providerToIdsMap.get(previousProvider); - previousRegistrationIds.remove(registrationId); - if (previousRegistrationIds.isEmpty()) { - providerToIdsMap.remove(previousProvider); - } - } - - idToProviderMap.put(registrationId, provider); - idToRegistrationContextMap.put(registrationId, registrationContext); - - List registrationIds = providerToIdsMap.get(provider); - if (registrationIds == null) { - registrationIds = new ArrayList<>(); - providerToIdsMap.put(provider, registrationIds); - } - - if (!registrationIds.contains(registrationId)) { - registrationIds.add(registrationId); - } - - return registrationId; - } - - private void _storeRegistration(RegistrationContext registrationContext, AuthConfigProvider configProvider, - Map properties) { - String className = null; - if (configProvider != null) { - className = configProvider.getClass().getName(); - } - - if (propertiesContainAnyNonStringValues(properties)) { - throw new IllegalArgumentException("AuthConfigProvider cannot be registered - properties must all be of type String."); - } - - if (registrationContext.isPersistent()) { - getRegStore().store(className, registrationContext, properties); - } - } - - private boolean propertiesContainAnyNonStringValues(Map properties) { - if (properties != null) { - for (Map.Entry entry : properties.entrySet()) { - if (!(entry.getValue() instanceof String)) { - return true; - } - } - } - - return false; - } - - private void _deleteStoredRegistration(RegistrationContext registrationContext) { - if (registrationContext.isPersistent()) { - getRegStore().delete(registrationContext); - } - } - - private static boolean regIdImplies(String reference, String target) { - - boolean rvalue = true; - - String[] refID = decomposeRegistrationId(reference); - String[] targetID = decomposeRegistrationId(target); - - if (refID[0] != null && !refID[0].equals(targetID[0])) { - rvalue = false; - } else if (refID[1] != null && !refID[1].equals(targetID[1])) { - rvalue = false; - } - - return rvalue; - } - - /** - * Will return some extra listeners. In other words, effected listeners could be reduced by removing any associated with - * a provider registration id that is more specific than the one being added or removed. - */ - private static Map> getEffectedListeners(String regisID) { - Map> effectedListeners = new HashMap<>(); - Set listenerRegistrations = new HashSet<>(idToRegistrationListenersMap.keySet()); - - for (String listenerID : listenerRegistrations) { - if (regIdImplies(regisID, listenerID)) { - if (!effectedListeners.containsKey(listenerID)) { - effectedListeners.put(listenerID, new ArrayList<>()); - } - effectedListeners.get(listenerID).addAll(idToRegistrationListenersMap.remove(listenerID)); - } - } - return effectedListeners; - } - - protected T doReadLocked(Supplier supplier) { - readLock.lock(); - try { - return supplier.get(); - } finally { - readLock.unlock(); - } - } - - protected T doWriteLocked(Supplier supplier) { - writeLock.lock(); - try { - return supplier.get(); - } finally { - writeLock.unlock(); - } - } - - protected void doWriteLocked(Runnable runnable) { - writeLock.lock(); - try { - runnable.run(); - } finally { - writeLock.unlock(); - } - } - - private static void notifyListeners(Map> map) { - Set>> entrySet = map.entrySet(); - for (Map.Entry> entry : entrySet) { - List listeners = map.get(entry.getKey()); - - if (listeners != null && listeners.size() > 0) { - String[] dIds = decomposeRegistrationId(entry.getKey()); - - for (RegistrationListener listener : listeners) { - listener.notify(dIds[0], dIds[1]); - } - } - } - } - - @Override - public String registerServerAuthModule(ServerAuthModule sam, Object context) { - String registrationId = null; - if (context instanceof ServletContext) { - ServletContext servletContext = (ServletContext) context; - - String appContext = servletContext.getVirtualServerName() + " " + servletContext.getContextPath(); - registrationId = registerConfigProvider(new DefaultAuthConfigProvider(sam), "HttpServlet", appContext, - "Default authentication config provider"); - - servletContext.setAttribute(CONTEXT_REGISTRATION_ID, registrationId); - } - return registrationId; - } - - @Override - public void removeServerAuthModule(Object context) { - if (context instanceof ServletContext) { - ServletContext servletContext = (ServletContext) context; - String registrationId = (String) servletContext.getAttribute(CONTEXT_REGISTRATION_ID); - if (!isEmpty(registrationId)) { - removeRegistration(registrationId); - } - } - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java deleted file mode 100644 index 0330d918878..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegStoreFileParser.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -import static com.sun.jaspic.config.helper.JASPICLogManager.JASPIC_LOGGER; -import static com.sun.jaspic.config.helper.JASPICLogManager.RES_BUNDLE; -import static java.util.logging.Level.FINER; -import static java.util.logging.Level.INFO; -import static java.util.logging.Level.WARNING; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.logging.Logger; - -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; - -/** - * Used by ServerConfigProvider to parse the configuration file. If a file does not exist originally, the default - * providers are not used. A file is only created if needed, which happens if providers are registered or unregistered - * through the store() or delete() methods. - * - * @author Bobby Bissett - */ -public final class RegStoreFileParser { - - private static final Logger logger = Logger.getLogger(JASPIC_LOGGER, RES_BUNDLE); - - private static final String SEP = ":"; - private static final String CON_ENTRY = "con-entry"; - private static final String REG_ENTRY = "reg-entry"; - private static final String REG_CTX = "reg-ctx"; - private static final String LAYER = "layer"; - private static final String APP_CTX = "app-ctx"; - private static final String DESCRIPTION = "description"; - private static final String[] INDENT = { "", " ", " " }; - - private final File configurationFile; - private List entries; - private List defaultEntries; - - /** - * Loads the configuration file from the given filename. If a file is not found, then the default entries are used. - * Otherwise the file is parsed to load the entries. - * - */ - public RegStoreFileParser(String pathParent, String pathChild, List defaultEntries) { - configurationFile = new File(pathParent, pathChild); - this.defaultEntries = defaultEntries == null ? new ArrayList() : defaultEntries; - - try { - loadEntries(); - } catch (IOException ioe) { - logWarningDefault(ioe); - } catch (IllegalArgumentException iae) { - logWarningDefault(iae); - } - } - - /** - * Returns the in-memory list of entries. MUST Hold exclusive lock on calling factory while processing entries - */ - List getPersistedEntries() { - return entries; - } - - /** - * Adds the provider to the entry list if it is not already present, creates the configuration file if necessary, and - * writes the entries to the file. - */ - void store(String className, RegistrationContext registrationContext, Map properties) { - synchronized (configurationFile) { - if (checkAndAddToList(className, registrationContext, properties)) { - try { - writeEntries(); - } catch (IOException ioe) { - logWarningUpdated(ioe); - } - } - } - } - - /** - * Removes the provider from the entry list if it is already present, creates the configuration file if necessary, and - * writes the entries to the file. - */ - void delete(RegistrationContext registrationContext) { - synchronized (configurationFile) { - if (checkAndRemoveFromList(registrationContext)) { - try { - writeEntries(); - } catch (IOException ioe) { - logWarningUpdated(ioe); - } - } - } - } - - /** - * If this entry does not exist, this method stores it in the entries list and returns true to indicate that the - * configuration file should be written. - */ - private boolean checkAndAddToList(String className, RegistrationContext registrationContext, Map properties) { - - // Convention is to use null for empty properties - if (properties != null && properties.isEmpty()) { - properties = null; - } - - EntryInfo newEntry = new EntryInfo(className, properties, registrationContext); - EntryInfo entry = getMatchingRegistrationEntry(newEntry); - - // There is no matching entry, so add to list - if (entry == null) { - entries.add(newEntry); - return true; - } - - // Otherwise, check reg contexts to see if there is a match - if (entry.getRegistrationContexts().contains(registrationContext)) { - return false; - } - - // No matching context in existing entry, so add to existing entry - entry.getRegistrationContexts().add(new RegistrationContextImpl(registrationContext)); - - return true; - } - - /** - * If this registration context does not exist, this method returns false. Otherwise it removes the entry and returns - * true to indicate that the configuration file should be written. - * - * This only makes sense for registry entries. - */ - private boolean checkAndRemoveFromList(RegistrationContext target) { - boolean retValue = false; - try { - ListIterator lit = entries.listIterator(); - while (lit.hasNext()) { - - EntryInfo info = lit.next(); - if (info.isConstructorEntry()) { - continue; - } - - Iterator iter = info.getRegistrationContexts().iterator(); - while (iter.hasNext()) { - RegistrationContext ctx = iter.next(); - if (ctx.equals(target)) { - iter.remove(); - if (info.getRegistrationContexts().isEmpty()) { - lit.remove(); - } - retValue = true; - } - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - - return retValue; - } - - /** - * Used to find a matching registration entry in the 'entries' list without including registration contexts. If there is - * not a matching entry, return null. - */ - private EntryInfo getMatchingRegistrationEntry(EntryInfo target) { - for (EntryInfo info : entries) { - if (!info.isConstructorEntry() && info.matchConstructors(target)) { - return info; - } - } - - return null; - } - - /** - * This method overwrites the existing file with the current entries. - */ - private void writeEntries() throws IOException { - if (configurationFile.exists() && !configurationFile.canWrite() && logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_cannot_write_file", configurationFile.getPath()); - } - - clearExistingFile(); - - PrintWriter out = new PrintWriter(configurationFile); - int indent = 0; - for (EntryInfo info : entries) { - if (info.isConstructorEntry()) { - writeConEntry(info, out, indent); - } else { - writeRegEntry(info, out, indent); - } - } - out.close(); - } - - /** - * Writes constructor entry output of the form: - * - *

-     *  con-entry { className key:value key:value }
-     * 
- * - * The first appearance of a colon ":" separates the key and value of the property (so a value may contain a colon as - * part of the string). For instance: "mydir:c:foo" would have key "mydir" and value "c:foo". - */ - private void writeConEntry(EntryInfo info, PrintWriter out, int i) { - out.println(INDENT[i++] + CON_ENTRY + " {"); - out.println(INDENT[i] + info.getClassName()); - - Map properties = info.getProperties(); - if (properties != null) { - for (Map.Entry val : properties.entrySet()) { - out.println(INDENT[i] + val.getKey() + SEP + val.getValue()); - } - } - - out.println(INDENT[--i] + "}"); - } - - /* - * Write registration entry output of the form:
 reg-entry { con-entry { see writeConEntry() for detail } reg-ctx {
-     * layer:HttpServlet app-ctx:security-jaspic-https description:My provider } } 
- */ - private void writeRegEntry(EntryInfo info, PrintWriter out, int i) { - out.println(INDENT[i++] + REG_ENTRY + " {"); - if (info.getClassName() != null) { - writeConEntry(info, out, i); - } - - for (RegistrationContext registrationContext : info.getRegistrationContexts()) { - out.println(INDENT[i++] + REG_CTX + " {"); - if (registrationContext.getMessageLayer() != null) { - out.println(INDENT[i] + LAYER + SEP + registrationContext.getMessageLayer()); - } - - if (registrationContext.getAppContext() != null) { - out.println(INDENT[i] + APP_CTX + SEP + registrationContext.getAppContext()); - } - - if (registrationContext.getDescription() != null) { - out.println(INDENT[i] + DESCRIPTION + SEP + registrationContext.getDescription()); - } - - out.println(INDENT[--i] + "}"); - } - - out.println(INDENT[--i] + "}"); - } - - private void clearExistingFile() throws IOException { - boolean newCreation = !configurationFile.exists(); - - if (!newCreation) { - if (!configurationFile.delete()) { - throw new IOException(); - } - } - - if (newCreation) { - logger.log(INFO, "jaspic.factory_creating_conf_file", configurationFile.getPath()); - } - - if (!configurationFile.createNewFile()) { - throw new IOException(); - } - } - - /** - * Called from the constructor. This is the only time the file is read, though it is written when new entries are stored - * or deleted. - */ - private void loadEntries() throws IOException { - synchronized (configurationFile) { - entries = new ArrayList(); - if (configurationFile.exists()) { - try (BufferedReader reader = new BufferedReader(new FileReader(configurationFile))) { - String line = reader.readLine(); - while (line != null) { - String trimLine = line.trim(); // can't trim readLine() result - if (trimLine.startsWith(CON_ENTRY)) { - entries.add(readConEntry(reader)); - } else if (trimLine.startsWith(REG_ENTRY)) { - entries.add(readRegEntry(reader)); - } - line = reader.readLine(); - } - } - } else { - if (logger.isLoggable(FINER)) { - logger.log(FINER, "jaspic.factory_file_not_found", - configurationFile.getParent() + File.pathSeparator + configurationFile.getPath()); - } - - for (EntryInfo entry : defaultEntries) { - entries.add(new EntryInfo(entry)); - } - } - } - } - - private EntryInfo readConEntry(BufferedReader reader) throws IOException { - // Entry must contain class name as next line - String className = reader.readLine(); - if (className != null) { - className = className.trim(); - } - - return new EntryInfo(className, readProperties(reader)); - } - - /** - * Properties must be of the form "key:value." While the key String cannot contain a ":" character, the value can. The - * line will be broken into key and value based on the first appearance of the ":" character. - */ - private Map readProperties(BufferedReader reader) throws IOException { - String line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - - if ("}".equals(line)) { - return null; - } - - Map properties = new HashMap(); - while (!"}".equals(line)) { - properties.put(line.substring(0, line.indexOf(SEP)), line.substring(line.indexOf(SEP) + 1, line.length())); - line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - } - - return properties; - } - - private EntryInfo readRegEntry(BufferedReader reader) throws IOException { - String className = null; - Map properties = null; - List ctxs = new ArrayList(); - String line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - while (!"}".equals(line)) { - if (line.startsWith(CON_ENTRY)) { - EntryInfo conEntry = readConEntry(reader); - className = conEntry.getClassName(); - properties = conEntry.getProperties(); - } else if (line.startsWith(REG_CTX)) { - ctxs.add(readRegContext(reader)); - } - line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - - } - return new EntryInfo(className, properties, ctxs); - } - - private RegistrationContext readRegContext(BufferedReader reader) throws IOException { - String layer = null; - String appCtx = null; - String description = null; - String line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - - while (!"}".equals(line)) { - String value = line.substring(line.indexOf(SEP) + 1, line.length()); - if (line.startsWith(LAYER)) { - layer = value; - } else if (line.startsWith(APP_CTX)) { - appCtx = value; - } else if (line.startsWith(DESCRIPTION)) { - description = value; - } - - line = reader.readLine(); - if (line != null) { - line = line.trim(); - } - } - - return new RegistrationContextImpl(layer, appCtx, description, true); - } - - private void logWarningUpdated(Exception exception) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_could_not_persist", exception.toString()); - } - } - - private void logWarningDefault(Exception exception) { - if (logger.isLoggable(WARNING)) { - logger.log(WARNING, "jaspic.factory_could_not_read", exception.toString()); - } - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java deleted file mode 100644 index f432cd9ab31..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/AuthConfigRegistrationWrapper.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import jakarta.security.auth.message.config.RegistrationListener; - -// Adding package private class because specializing the listener implementation class would -// make the Payara JASPIC (JSR 196) implementation non-replaceable. -// -// This class would hold a RegistrationListener within. -public class AuthConfigRegistrationWrapper { - - private String layer; - private String applicationContextId; - private String jaspicProviderRegistrationId; - private boolean enabled; - private ConfigData data; - - private Lock wLock; - private ReadWriteLock rwLock; - - private AuthConfigRegistrationListener listener; - private int referenceCount = 1; - private RegistrationWrapperRemover removerDelegate; - - public AuthConfigRegistrationWrapper(String layer, String applicationContextId, RegistrationWrapperRemover removerDelegate) { - this.layer = layer; - this.applicationContextId = applicationContextId; - this.removerDelegate = removerDelegate; - this.rwLock = new ReentrantReadWriteLock(true); - this.wLock = rwLock.writeLock(); - - enabled = JaspicServices.factory != null; - listener = new AuthConfigRegistrationListener(layer, applicationContextId); - } - - public AuthConfigRegistrationListener getListener() { - return listener; - } - - public void setListener(AuthConfigRegistrationListener listener) { - this.listener = listener; - } - - public void disable() { - this.wLock.lock(); - - try { - setEnabled(false); - } finally { - this.wLock.unlock(); - data = null; - } - - if (JaspicServices.factory != null) { - JaspicServices.factory.detachListener(this.listener, layer, applicationContextId); - if (getJaspicProviderRegistrationId() != null) { - JaspicServices.factory.removeRegistration(getJaspicProviderRegistrationId()); - } - } - } - - // Detach the listener, but don't remove-registration - public void disableWithRefCount() { - if (referenceCount <= 1) { - disable(); - if (removerDelegate != null) { - removerDelegate.removeListener(this); - } - } else { - try { - this.wLock.lock(); - referenceCount--; - } finally { - this.wLock.unlock(); - } - - } - } - - public void incrementReference() { - try { - this.wLock.lock(); - referenceCount++; - } finally { - this.wLock.unlock(); - } - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getJaspicProviderRegistrationId() { - return this.jaspicProviderRegistrationId; - } - - public void setRegistrationId(String jaspicProviderRegistrationId) { - this.jaspicProviderRegistrationId = jaspicProviderRegistrationId; - } - - public ConfigData getConfigData() { - return data; - } - - public void setConfigData(ConfigData data) { - this.data = data; - } - - public class AuthConfigRegistrationListener implements RegistrationListener { - - private String layer; - private String appCtxt; - - public AuthConfigRegistrationListener(String layer, String appCtxt) { - this.layer = layer; - this.appCtxt = appCtxt; - } - - @Override - public void notify(String layer, String appContext) { - if (this.layer.equals(layer) - && ((this.appCtxt == null && appContext == null) || (appContext != null && appContext.equals(this.appCtxt)))) { - try { - wLock.lock(); - data = null; - } finally { - wLock.unlock(); - } - } - } - - } -} \ No newline at end of file diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java deleted file mode 100644 index 9f3666105ed..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/ConfigData.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - -import jakarta.security.auth.message.config.AuthConfig; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ServerAuthConfig; - -class ConfigData { - - private AuthConfigProvider provider; - private AuthConfig serverConfig; - private AuthConfig clientConfig; - - ConfigData() { - } - - ConfigData(AuthConfigProvider authConfigProvider, AuthConfig authConfig) { - provider = authConfigProvider; - - if (authConfig == null) { - serverConfig = null; - clientConfig = null; - } else if (authConfig instanceof ServerAuthConfig) { - serverConfig = authConfig; - } else if (authConfig instanceof ClientAuthConfig) { - clientConfig = authConfig; - } else { - throw new IllegalArgumentException(); - } - } - - public AuthConfigProvider getProvider() { - return provider; - } - - public AuthConfig getServerConfig() { - return serverConfig; - } - - public AuthConfig getClientConfig() { - return clientConfig; - } -} \ No newline at end of file diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java deleted file mode 100644 index 5659f9186ff..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/JaspicServices.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.config.AuthConfig; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; - -/** - * This is based Helper class for 196 Configuration. - */ -public abstract class JaspicServices { - - protected static final AuthConfigFactory factory = AuthConfigFactory.getFactory(); - - private ReadWriteLock readWriteLock; - private Lock readLock; - private Lock writeLock; - - protected String layer; - protected String appCtxt; - protected Map map; - protected CallbackHandler callbackHandler; - protected AuthConfigRegistrationWrapper listenerWrapper; - - protected void init(String layer, String appContext, Map map, CallbackHandler callbackHandler, RegistrationWrapperRemover removerDelegate) { - this.layer = layer; - this.appCtxt = appContext; - this.map = map; - this.callbackHandler = callbackHandler; - if (this.callbackHandler == null) { - this.callbackHandler = getCallbackHandler(); - } - - this.readWriteLock = new ReentrantReadWriteLock(true); - this.readLock = readWriteLock.readLock(); - this.writeLock = readWriteLock.writeLock(); - - listenerWrapper = new AuthConfigRegistrationWrapper(this.layer, this.appCtxt, removerDelegate); - } - - public void setRegistrationId(String registrationId) { - listenerWrapper.setRegistrationId(registrationId); - } - - public AuthConfigRegistrationWrapper getRegistrationWrapper() { - return listenerWrapper; - } - - public void setRegistrationWrapper(AuthConfigRegistrationWrapper wrapper) { - this.listenerWrapper = wrapper; - } - - public AuthConfigRegistrationWrapper.AuthConfigRegistrationListener getRegistrationListener() { - return listenerWrapper.getListener(); - } - - public void disable() { - listenerWrapper.disable(); - } - - public Object getProperty(String key) { - return map == null ? null : map.get(key); - } - - public String getAppContextID() { - return appCtxt; - } - - public ClientAuthConfig getClientAuthConfig() throws AuthException { - return (ClientAuthConfig) getAuthConfig(false); - } - - public ServerAuthConfig getServerAuthConfig() throws AuthException { - return (ServerAuthConfig) getAuthConfig(true); - } - - public ClientAuthContext getClientAuthContext(MessageInfo info, Subject clientSubject) throws AuthException { - ClientAuthConfig clientConfig = (ClientAuthConfig) getAuthConfig(false); - if (clientConfig != null) { - return clientConfig.getAuthContext(clientConfig.getAuthContextID(info), clientSubject, map); - } - - return null; - } - - public ServerAuthContext getServerAuthContext(MessageInfo info, Subject serviceSubject) throws AuthException { - ServerAuthConfig serverAuthConfig = (ServerAuthConfig) getAuthConfig(true); - if (serverAuthConfig != null) { - return serverAuthConfig.getAuthContext(serverAuthConfig.getAuthContextID(info), serviceSubject, map); - } - - return null; - } - - protected AuthConfig getAuthConfig(AuthConfigProvider authConfigProvider, boolean isServer) throws AuthException { - AuthConfig authConfig = null; - - if (authConfigProvider != null) { - if (isServer) { - authConfig = authConfigProvider.getServerAuthConfig(layer, appCtxt, callbackHandler); - } else { - authConfig = authConfigProvider.getClientAuthConfig(layer, appCtxt, callbackHandler); - } - } - - return authConfig; - } - - protected AuthConfig getAuthConfig(boolean isServer) throws AuthException { - - ConfigData configData = null; - AuthConfig authConfig = null; - boolean disabled = false; - AuthConfigProvider lastConfigProvider = null; - - try { - readLock.lock(); - disabled = !listenerWrapper.isEnabled(); - if (!disabled) { - configData = listenerWrapper.getConfigData(); - if (configData != null) { - authConfig = isServer ? configData.getServerConfig() : configData.getClientConfig(); - lastConfigProvider = configData.getProvider(); - } - } - - } finally { - readLock.unlock(); - if (disabled || authConfig != null || (configData != null && lastConfigProvider == null)) { - return authConfig; - } - } - - // d == null || (d != null && lastP != null && c == null) - if (configData == null) { - try { - writeLock.lock(); - if (listenerWrapper.getConfigData() == null) { - AuthConfigProvider nextConfigProvider = factory.getConfigProvider(layer, appCtxt, getRegistrationListener()); - - if (nextConfigProvider != null) { - listenerWrapper.setConfigData(new ConfigData(nextConfigProvider, getAuthConfig(nextConfigProvider, isServer))); - } else { - listenerWrapper.setConfigData(new ConfigData()); - } - } - configData = listenerWrapper.getConfigData(); - } finally { - writeLock.unlock(); - } - } - - return isServer ? configData.getServerConfig() : configData.getClientConfig(); - } - - /** - * Check if there is a provider register for a given layer and appCtxt. - */ - protected boolean hasExactMatchAuthProvider() { - boolean exactMatch = false; - - AuthConfigProvider configProvider = factory.getConfigProvider(layer, appCtxt, null); - - if (configProvider != null) { - for (String registrationId : factory.getRegistrationIDs(configProvider)) { - RegistrationContext registrationContext = factory.getRegistrationContext(registrationId); - if (layer.equals(registrationContext.getMessageLayer()) && appCtxt.equals(registrationContext.getAppContext())) { - exactMatch = true; - break; - } - } - } - - return exactMatch; - } - - /** - * Get the callback default handler - */ - protected CallbackHandler getCallbackHandler() { - return null; - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java deleted file mode 100644 index b593a72f2fc..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/services/RegistrationWrapperRemover.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.services; - - -public interface RegistrationWrapperRemover { - - /** - * remove the registration of the argument listener from the Pipe - * - * @param listener - */ - void removeListener(AuthConfigRegistrationWrapper listener); - -} diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java index 80b2cc68850..253eb82236e 100644 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java +++ b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package test.com.sun.jaspic.config; import java.util.concurrent.TimeUnit; @@ -48,9 +48,6 @@ import java.util.ArrayList; import java.util.List; import com.sun.jaspic.config.factory.EntryInfo; -import com.sun.jaspic.config.factory.AuthConfigFileFactory; -import com.sun.jaspic.config.factory.BaseAuthConfigFactory; -import com.sun.jaspic.config.factory.RegStoreFileParser; import java.security.Security; import org.junit.After; import java.util.HashMap; diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java index 038205a47a1..c8eefa5cb4a 100644 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java +++ b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java @@ -37,10 +37,9 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package test.com.sun.jaspic.config; -import com.sun.jaspic.config.factory.AuthConfigFileFactory; import com.sun.jaspic.config.servlet.JAASServletAuthConfigProvider; import java.io.IOException; import java.util.HashMap; @@ -59,6 +58,7 @@ import jakarta.security.auth.message.config.RegistrationListener; import jakarta.security.auth.message.config.ServerAuthConfig; import jakarta.security.auth.message.config.ServerAuthContext; +import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; /** * diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java index 67d9670a191..006e6423399 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package com.sun.web.security.realmadapter; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.AUTH_TYPE; @@ -93,7 +93,7 @@ import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.security.SecurityContext; -import com.sun.enterprise.security.jaspic.config.PayaraJaspicServletServices; +import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServletServices; import com.sun.enterprise.security.web.integration.WebPrincipal; import com.sun.jaspic.config.servlet.HttpMessageInfo; import com.sun.logging.LogDomains; @@ -130,7 +130,7 @@ public class JaspicRealm { private Container virtualServer; - private PayaraJaspicServletServices jaspicServices; + private PayaraEpicyroServletServices jaspicServices; private AtomicBoolean initialised = new AtomicBoolean(); public JaspicRealm(String realmName, boolean isSystemApp, WebBundleDescriptor webDescriptor, RequestTracingService requestTracing) { @@ -291,11 +291,11 @@ private ServerAuthContext getServerAuthContext(MessageInfo messageInfo) throws A /** * This must be invoked after virtualServer is set. */ - private PayaraJaspicServletServices getConfigHelper(ServletContext servletContext) { + private PayaraEpicyroServletServices getConfigHelper(ServletContext servletContext) { Map map = new HashMap<>(); map.put(WEB_BUNDLE, webDescriptor); - return new PayaraJaspicServletServices( + return new PayaraEpicyroServletServices( getAppContextID(servletContext), map, null, // null handler realmName, isSystemApp, jaspicSystemConfigProviderID); } diff --git a/appserver/security/webservices.security/pom.xml b/appserver/security/webservices.security/pom.xml index 490f94c6001..a14995ec401 100644 --- a/appserver/security/webservices.security/pom.xml +++ b/appserver/security/webservices.security/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -144,5 +144,15 @@ logging-annotation-processor true + + org.glassfish.epicyro + epicyro + + + fish.payara.server.internal.security + appclient.security + ${project.version} + true + diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java index 1bd4684ad53..08b59322298 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java @@ -37,17 +37,19 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jauth.jaspic.provider.config; -import static com.sun.enterprise.security.jaspic.AuthMessagePolicy.getMessageSecurityBinding; import static com.sun.enterprise.security.webservices.PipeConstants.BINDING; import static com.sun.enterprise.security.webservices.PipeConstants.ENDPOINT; import static com.sun.enterprise.security.webservices.PipeConstants.SEI_MODEL; import static com.sun.enterprise.security.webservices.PipeConstants.SERVICE_ENDPOINT; -import static com.sun.enterprise.security.webservices.PipeConstants.SOAP_LAYER; import static com.sun.xml.ws.api.SOAPVersion.SOAP_11; +import com.sun.enterprise.security.appclient.ConfigXMLParser; +import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; +import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; +import jakarta.security.auth.message.MessagePolicy; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; @@ -55,6 +57,8 @@ import java.security.PrivilegedExceptionAction; import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import jakarta.security.auth.message.AuthException; @@ -72,6 +76,8 @@ import org.glassfish.api.invocation.ComponentInvocation; import org.glassfish.api.invocation.InvocationManager; import org.glassfish.deployment.common.ModuleDescriptor; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; import org.glassfish.internal.api.Globals; import com.sun.enterprise.deployment.Application; @@ -88,10 +94,9 @@ import com.sun.enterprise.security.common.ClientSecurityContext; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; import com.sun.enterprise.security.ee.authorize.EJBPolicyContextDelegate; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; -import com.sun.enterprise.security.jaspic.config.GFServerConfigProvider; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; import com.sun.enterprise.security.jaspic.config.HandlerContext; -import com.sun.enterprise.security.jaspic.config.PayaraJaspicServices; +import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServices; import com.sun.enterprise.security.webservices.PipeConstants; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.io.FileUtils; @@ -106,7 +111,7 @@ import com.sun.xml.ws.api.model.wsdl.WSDLPort; import com.sun.xml.ws.api.server.WSEndpoint; -public class PipeHelper extends PayaraJaspicServices { +public class PipeHelper extends PayaraEpicyroServices { protected static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(PipeConstants.class); @@ -118,7 +123,7 @@ public class PipeHelper extends PayaraJaspicServices { private EJBPolicyContextDelegate ejbDelegate; public PipeHelper(String layer, Map properties, CallbackHandler callbackHandler) { - init(layer, getAppCtxt(properties), properties, callbackHandler, Globals.get(WebServicesDelegate.class)); + init(layer, getAppCtxt(properties), properties, callbackHandler, (RegistrationWrapperRemover) Globals.get(WebServicesDelegate.class)); isEjbEndpoint = processSunDeploymentDescriptor(); seiModel = (SEIModel) properties.get(SEI_MODEL); @@ -402,24 +407,44 @@ public String getRealmName() { } private boolean processSunDeploymentDescriptor() { - if (factory == null) { + if (authConfigFactory == null) { return false; } - MessageSecurityBindingDescriptor binding = getMessageSecurityBinding(SOAP_LAYER, map); + MessageSecurityBindingDescriptor binding = AuthMessagePolicy.getMessageSecurityBinding(com.sun.xml.wss.provider.wsit.PipeConstants.SOAP_LAYER, map); + + Function authContextIdGenerator = + e -> Globals.get(WebServicesDelegate.class).getAuthContextID(e); + + BiFunction, MessagePolicy[]> soapPolicyGenerator = + (authContextId, properties) -> AuthMessagePolicy.getSOAPPolicies( + AuthMessagePolicy.getMessageSecurityBinding("SOAP", properties), + authContextId, true); + + String authModuleId = AuthMessagePolicy.getProviderID(binding); + + map.put("authContextIdGenerator", authContextIdGenerator); + map.put("soapPolicyGenerator", soapPolicyGenerator); + + if (authModuleId != null) { + map.put("authModuleId", authModuleId); + } if (binding != null) { if (!hasExactMatchAuthProvider()) { - String jaspicProviderRegisID = factory.registerConfigProvider( - new GFServerConfigProvider(null, null), - layer, appCtxt, "GF AuthConfigProvider bound by Sun Specific Descriptor"); - - setRegistrationId(jaspicProviderRegisID); + String jmacProviderRegisID = authConfigFactory.registerConfigProvider( + new GFServerConfigProvider( + map, + isACC()? new ConfigXMLParser() : new ConfigDomainParser(), + authConfigFactory), + messageLayer, appContextId, + "GF AuthConfigProvider bound by Sun Specific Descriptor"); + + setRegistrationId(jmacProviderRegisID); } } WebServiceEndpoint webServiceEndpoint = (WebServiceEndpoint) map.get(SERVICE_ENDPOINT); - return webServiceEndpoint == null ? false : webServiceEndpoint.implementedByEjbComponent(); } @@ -538,4 +563,8 @@ private String ejbName() { WebServiceEndpoint wSE = (WebServiceEndpoint) getProperty(PipeConstants.SERVICE_ENDPOINT); return (wSE == null ? "unknown" : wSE.getEjbComponentImpl().getName()); } + + private static boolean isACC() { + return SecurityServicesUtil.getInstance() == null || SecurityServicesUtil.getInstance().isACC(); + } } diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java index 162a55e99f3..62c7771236a 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCloser.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static java.util.Collections.synchronizedMap; @@ -47,7 +47,7 @@ import java.util.WeakHashMap; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.jaspic.services.AuthConfigRegistrationWrapper; +import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; public class ClientPipeCloser { diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java index a0421be7125..f06686cfe72 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2022] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static com.sun.enterprise.security.webservices.PipeConstants.ASSEMBLER_CONTEXT; @@ -53,7 +53,7 @@ import java.util.HashMap; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.jaspic.services.AuthConfigRegistrationWrapper; +import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; import com.sun.xml.ws.api.pipe.ClientPipeAssemblerContext; import com.sun.xml.ws.api.pipe.Pipe; import com.sun.xml.ws.assembler.metro.dev.ClientPipelineHook; diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java index 554546d1ce7..e0145fad991 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import java.util.Iterator; @@ -63,11 +63,11 @@ import com.sun.enterprise.deployment.ServiceRefPortInfo; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.security.jaspic.WebServicesDelegate; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; import com.sun.enterprise.security.jauth.AuthParam; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.SOAPAuthParam; -import com.sun.jaspic.services.AuthConfigRegistrationWrapper; +import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; import com.sun.xml.ws.api.message.Message; import com.sun.xml.ws.api.message.Packet; import com.sun.xml.ws.api.model.wsdl.WSDLBoundOperation; diff --git a/core/core-parent/pom.xml b/core/core-parent/pom.xml index b8f77ac8617..dcaa351d5e0 100644 --- a/core/core-parent/pom.xml +++ b/core/core-parent/pom.xml @@ -617,6 +617,8 @@ io.opentelemetry.extension io.opentelemetry.instrumentation fish.payara.shaded + com.sun.enterprise.security + com.sun.jaspic.services diff --git a/core/pom.xml b/core/pom.xml index 71a2e666efe..76b4876e990 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -123,6 +123,7 @@ 1.0 4.12.0 2.0.21 + 3.1.0 3.2.3.payara-p1 @@ -913,6 +914,11 @@ jakarta.authentication-api ${jakarta.authentication-api.version} + + org.glassfish.epicyro + epicyro + ${epyciro.version} + jakarta.persistence jakarta.persistence-api diff --git a/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java b/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java index 84705677cb5..de361201707 100644 --- a/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java +++ b/nucleus/deployment/common/src/main/java/org/glassfish/deployment/common/DynamicAttributesDescriptor.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019] Payara Foundation and/or affiliates +// Portions Copyright [2019-2024] Payara Foundation and/or affiliates package org.glassfish.deployment.common; @@ -88,11 +88,11 @@ public void addExtraAttribute(String name, Object value) { * @param name the attribute name * @return the attribute value of null of non existent */ - public Object getExtraAttribute(String name) { + public T getExtraAttribute(String name) { if (dynamicAttributes == null) { return null; } - return dynamicAttributes.get(name); + return (T) dynamicAttributes.get(name); } /** diff --git a/nucleus/security/core/pom.xml b/nucleus/security/core/pom.xml index c103175bcf2..c80ae0d20fd 100644 --- a/nucleus/security/core/pom.xml +++ b/nucleus/security/core/pom.xml @@ -39,7 +39,7 @@ only if the new code is made subject to such option by the copyright holder. - Portions Copyright [2019-2022] [Payara Foundation and/or its affiliates] + Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] --> logging-annotation-processor true + + org.glassfish.epicyro + epicyro + org.javassist javassist diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java index 56a48d9063a..7c790c0aff9 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/audit/BaseAuditManager.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2021] Payara Services Ltd. +// Portions Copyright [2021-2024] Payara Services Ltd. package com.sun.enterprise.security.audit; @@ -193,7 +193,6 @@ public void loadAuditModules() { * Add the given audit module to the list of loaded audit module. * Adding the same name twice will override previous one. * @param name of auditModule - * @param am an instance of a class extending BaseAuditModule that has been * successfully loaded into the system. * @exception */ @@ -284,7 +283,6 @@ public Logger getLogger() { /** * logs the authentication call for all the loaded modules. - * @see com.sun.appserv.security.BaseAuditModule.authentication */ @Override public void authentication(final String user, final String realm, final boolean success){ diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java index 7064d60caa9..7918dc5a32d 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/common/ClientSecurityContext.java @@ -74,8 +74,8 @@ public final class ClientSecurityContext extends AbstractSecurityContext { /** * This creates a new ClientSecurityContext object. * - * @param The name of the user. - * @param The Credentials of the user. + * @param username name of the user. + * @param subject Credentials of the user. */ public ClientSecurityContext(String username, Subject subject) { this.callerPrincipal = new UserNameAndPassword(username); @@ -101,7 +101,6 @@ public static ClientSecurityContext getCurrent() { /** * This method sets the SecurityContext to be stored here. * - * @param The Security Context that should be stored. */ public static void setCurrent(ClientSecurityContext clientSecurityContext) { if (isPerThreadAuth) { From 45b26bdf816b037a610b32b3e7498d1cbe5a60e8 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Wed, 30 Oct 2024 23:45:30 -0600 Subject: [PATCH 15/34] FISH-8925: rebasing changes --- .../internal/notification/EventLevel.java | 85 ------------------- .../security/BasePasswordLoginModule.java | 2 +- 2 files changed, 1 insertion(+), 86 deletions(-) diff --git a/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java b/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java index 5378eadf13e..e69de29bb2d 100644 --- a/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java +++ b/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java @@ -1,85 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) [2024] Payara Foundation and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://github.com/payara/Payara/blob/main/LICENSE.txt - * See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at glassfish/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * The Payara Foundation designates this particular file as subject to the "Classpath" - * exception as provided by the Payara Foundation in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package fish.payara.internal.notification; - -import java.util.function.BiPredicate; -import java.util.logging.Level; - -/** - * - */ -public enum EventLevel { - INFO(800), - WARNING(900), - SEVERE(1000); - - private final int severityLevel; - - public static EventLevel fromNameOrWarning (String name) { - try { - return EventLevel.valueOf(name.toUpperCase()); - } catch (Exception e) { - return WARNING; - } - } - - public static EventLevel fromLogLevel (Level level) { - if (level.intValue() <= INFO.severityLevel) { - return INFO; - } - if (level.intValue() <= WARNING.severityLevel) { - return WARNING; - } - return SEVERE; - } - - EventLevel (int severityLevel) { - this.severityLevel = severityLevel; - } - - public int getSeverityLevel () { - return severityLevel; - } - - public boolean compare (EventLevel other, BiPredicate predicate) { - return predicate.test(this.severityLevel, other.severityLevel); - } -} diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java index 886ab59552a..04bcd37fdac 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/BasePasswordLoginModule.java @@ -151,7 +151,7 @@ public final boolean login() throws LoginException { * Commit the authentication. * *

- * Commit is called after all necessary login modules have succeeded. It adds (if not present) a UserPrincipal principal + * Commit is called after all necessary login modules have succeeded. It adds (if not present) a PrincipalImpl principal * and a LocalCredentials public credential to the Subject. * * @throws LoginException If commit fails. From 6f2192b612e6ae38a4063b9afc0fa292070a05d4 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Thu, 14 Nov 2024 22:27:02 -0600 Subject: [PATCH 16/34] FISH-8925: introducing epicyro for jakarta authentication in payara 7 --- .../glassfish/ejb/startup/EjbDeployer.java | 2 +- appserver/packager/appserver-core/pom.xml | 4 - .../registration/glassfish/ModuleMap.java | 95 +- appserver/security/appclient.security/pom.xml | 6 +- appserver/security/core-ee/pom.xml | 4 - .../security/ee/JavaEESecurityLifecycle.java | 2 +- .../jakarta/WebServicesDelegate.java | 16 +- .../jacc/JaccWebAuthorizationManager.java | 2 +- .../security/jacc/package-info.java | 2 +- .../security/jaspic/package-info.java | 2 +- .../enterprise/security/jauth/AuthConfig.java | 291 ----- .../security/jauth/AuthContext.java | 265 ----- .../security/jauth/AuthException.java | 71 -- .../enterprise/security/jauth/AuthParam.java | 52 - .../enterprise/security/jauth/AuthPolicy.java | 268 ----- .../security/jauth/ClientAuthContext.java | 147 --- .../security/jauth/ClientAuthModule.java | 144 --- .../jauth/DependentCallbackHandler.java | 56 - .../security/jauth/FailureException.java | 73 -- .../security/jauth/HttpServletAuthParam.java | 158 --- .../security/jauth/PendingException.java | 74 -- .../security/jauth/ServerAuthContext.java | 170 --- .../security/jauth/ServerAuthModule.java | 146 --- .../jauth/callback/CertStoreCallback.java | 71 -- .../jauth/callback/KerberosKeyCallback.java | 95 -- .../callback/PasswordValidationCallback.java | 64 -- .../jauth/callback/PrivateKeyCallback.java | 168 --- .../jauth/callback/SecretKeyCallback.java | 110 -- .../jauth/callback/SignatureKeyCallback.java | 115 -- .../jauth/callback/TrustStoreCallback.java | 66 -- .../security/permissionsxml/server.policy | 3 +- .../jaspic-provider-framework/auth.conf | 0 .../jaspic-provider-framework/osgi.bundle | 48 - .../jaspic-provider-framework/pom.xml | 91 -- .../delegate/MessagePolicyDelegate.java | 62 - .../factory/DefaultAuthConfigProvider.java | 116 -- .../factory/DefaultServerAuthConfig.java | 95 -- .../factory/DefaultServerAuthContext.java | 65 -- .../sun/jaspic/config/factory/EntryInfo.java | 198 ---- .../factory/RegistrationContextImpl.java | 114 -- .../config/helper/BaseAuthConfigImpl.java | 245 ---- .../config/helper/BaseAuthConfigProvider.java | 245 ---- .../config/helper/BaseAuthContextImpl.java | 169 --- .../config/helper/ClientAuthConfigImpl.java | 220 ---- .../jaspic/config/helper/EpochCarrier.java | 95 -- .../config/helper/JASPICLogManager.java | 58 - .../config/helper/ServerAuthConfigImpl.java | 221 ---- .../config/jaas/ExtendedConfigFile.java | 151 --- .../config/jaas/JAASAuthConfigProvider.java | 156 --- .../config/jaas/JAASAuthContextHelper.java | 344 ------ .../config/servlet/HttpMessageInfo.java | 85 -- .../JAASServletAuthConfigProvider.java | 142 --- .../jaspic/security/LogStrings.properties | 49 - .../com/sun/jaspic/config/FactoryTest.java | 1013 ----------------- .../sun/jaspic/config/RuntimeSurrogate.java | 339 ------ .../jaspic/config/SampleClientAuthModule.java | 78 -- .../jaspic/config/SampleServerAuthModule.java | 78 -- .../security/realmadapter/JaspicRealm.java | 2 +- .../security/webservices.security/pom.xml | 2 +- .../jauth/jaspic/provider/BaseAuthConfig.java | 608 ---------- .../jaspic/provider/ClientAuthConfig.java | 121 -- .../jauth/jaspic/provider/SOAPAuthParam.java | 5 +- .../jaspic/provider/ServerAuthConfig.java | 122 -- ...er.java => SoapAuthenticationService.java} | 4 +- .../webservices/ClientSecurityPipe.java | 12 +- ...or.java => ClientSecurityPipeCreator.java} | 44 +- .../webservices/ClientSecurityTube.java | 10 +- .../webservices/CommonServerSecurityPipe.java | 10 +- .../webservices/CommonServerSecurityTube.java | 10 +- .../webservices/SecurityServiceImpl.java | 60 +- ...or.java => ServerSecurityPipeCreator.java} | 26 +- .../webservices/WebServicesDelegateImpl.java | 33 +- .../webservices/SecurityService.java | 10 +- core/core-bom/pom.xml | 10 +- core/pom.xml | 2 - .../src/main/resources/config/server.policy | 1 + .../internal/notification/EventLevel.java | 85 ++ .../enterprise/security}/PolicyLoader.java | 3 +- .../src/main/resources/config/server.policy | 1 + nucleus/security/services/pom.xml | 6 +- 80 files changed, 245 insertions(+), 8161 deletions(-) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthConfig.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthContext.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthException.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthParam.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthPolicy.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthContext.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthModule.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/DependentCallbackHandler.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/FailureException.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/HttpServletAuthParam.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/PendingException.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthContext.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthModule.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/CertStoreCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/KerberosKeyCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PasswordValidationCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PrivateKeyCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SecretKeyCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SignatureKeyCallback.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/TrustStoreCallback.java delete mode 100644 appserver/security/jaspic-provider-framework/auth.conf delete mode 100644 appserver/security/jaspic-provider-framework/osgi.bundle delete mode 100644 appserver/security/jaspic-provider-framework/pom.xml delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/delegate/MessagePolicyDelegate.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultAuthConfigProvider.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthConfig.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthContext.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/EntryInfo.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegistrationContextImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigProvider.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthContextImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ClientAuthConfigImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/EpochCarrier.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/JASPICLogManager.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ServerAuthConfigImpl.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/ExtendedConfigFile.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthContextHelper.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/HttpMessageInfo.java delete mode 100755 appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/JAASServletAuthConfigProvider.java delete mode 100644 appserver/security/jaspic-provider-framework/src/main/resources/com/sun/logging/enterprise/system/jaspic/security/LogStrings.properties delete mode 100644 appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java delete mode 100644 appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java delete mode 100644 appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleClientAuthModule.java delete mode 100644 appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleServerAuthModule.java delete mode 100644 appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/BaseAuthConfig.java delete mode 100644 appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ClientAuthConfig.java delete mode 100644 appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ServerAuthConfig.java rename appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/{PipeHelper.java => SoapAuthenticationService.java} (99%) rename appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/{ClientPipeCreator.java => ClientSecurityPipeCreator.java} (79%) rename appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/{GFServerPipeCreator.java => ServerSecurityPipeCreator.java} (88%) rename {appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize => nucleus/security/core/src/main/java/com/sun/enterprise/security}/PolicyLoader.java (99%) diff --git a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java index 207f4258b46..46326ada624 100644 --- a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java +++ b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java @@ -89,7 +89,7 @@ import com.sun.enterprise.deployment.Application; import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.module.bootstrap.StartupContext; -import com.sun.enterprise.security.ee.authorize.PolicyLoader; +import com.sun.enterprise.security.PolicyLoader; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.util.IASSecurityException; import com.sun.enterprise.util.LocalStringManagerImpl; diff --git a/appserver/packager/appserver-core/pom.xml b/appserver/packager/appserver-core/pom.xml index ad610afd20d..d670ffc22a9 100644 --- a/appserver/packager/appserver-core/pom.xml +++ b/appserver/packager/appserver-core/pom.xml @@ -164,10 +164,6 @@ jacc.provider.inmemory ${project.version} - - fish.payara.server.core.security - jaspic.provider.framework - fish.payara.server.core.packager libpam4j-repackaged diff --git a/appserver/registration/glassfish-registration/src/main/java/com/sun/enterprise/registration/glassfish/ModuleMap.java b/appserver/registration/glassfish-registration/src/main/java/com/sun/enterprise/registration/glassfish/ModuleMap.java index 898269ed028..992e58e488b 100644 --- a/appserver/registration/glassfish-registration/src/main/java/com/sun/enterprise/registration/glassfish/ModuleMap.java +++ b/appserver/registration/glassfish-registration/src/main/java/com/sun/enterprise/registration/glassfish/ModuleMap.java @@ -282,54 +282,53 @@ public class ModuleMap { put("fish.payara.server.internal.security.appclient.security", 223); put("fish.payara.server.internal.security.ejb.security", 224); put("fish.payara.server.internal.security.inmemory.jacc.provider", 225); - put("fish.payara.server.core.security.jaspic.provider.framework", 226); - put("fish.payara.server.internal.security.jakarta.security.auth.message", 227); - put("fish.payara.server.internal.security.jakarta.security.jacc", 228); - put("fish.payara.server.core.security.ssl-impl", 229); - put("fish.payara.server.core.security.websecurity", 230); - put("fish.payara.server.internal.security.webservices.security", 231); - put("fish.payara.server.internal.transaction.internal-api", 232); - put("fish.payara.server.internal.transaction.jakarta.transaction", 233); - put("fish.payara.server.internal.transaction.jta", 234); - put("fish.payara.server.internal.transaction.jts", 235); - put("fish.payara.server.internal.web.cli", 236); - put("fish.payara.server.internal.web.core", 237); - put("fish.payara.server.core.web.gf-web-connector", 238); - put("fish.payara.server.core.web.glue", 239); - put("fish.payara.server.internal.web.gui-plugin-common", 240); - put("fish.payara.server.internal.web.ha", 241); - put("fish.payara.server.internal.web.jsf-connector", 242); - put("fish.payara.server.internal.web.jspcaching-connector", 243); - put("fish.payara.server.internal.web.jstl-connector", 244); - put("fish.payara.server.internal.web.naming", 245); - put("fish.payara.server.core.web.war-util", 246); - put("fish.payara.server.core.web.web-embed.api", 247); - put("fish.payara.server.internal.web.web-embed.impl", 248); - put("fish.payara.server.internal.web.weld-integration", 249); - put("fish.payara.server.internal.web.weld-integration-fragment", 250); - put("fish.payara.server.internal.webservices.connector", 251); - put("fish.payara.server.internal.webservices.jsr109-impl", 252); - put("fish.payara.server.internal.webservices.metro-glue", 253); - put("fish.payara.server.internal.webservices.soap-tcp", 254); - put("org.glassfish.metro.webservices-api-osgi", 255); - put("org.glassfish.metro.webservices-extra-jdk-packages", 256); - put("org.glassfish.metro.webservices-osgi", 257); - put("org.glassfish.web.el-impl", 258); - put("org.glassfish.web.jsp-impl", 259); - put("org.glassfish.web.jstl-impl", 260); - put("org.jboss.weld.osgi-bundle", 261); - put("org.jvnet.mimepull", 262); - put("org.shoal.cache", 263); - put("org.shoal.gms-api", 264); - put("org.shoal.gms-impl", 265); - put("stax2-api", 266); - put("woodstox-core-asl", 267); - put("com.fasterxml.jackson.dataformat.xml", 268); - put("org.objectweb.asm", 269); - put("org.objectweb.asm.commons", 270); - put("org.objectweb.asm.tree", 271); - put("org.objectweb.asm.tree.analysis", 272); - put("org.objectweb.asm.util", 273); + put("fish.payara.server.internal.security.jakarta.security.auth.message", 226); + put("fish.payara.server.internal.security.jakarta.security.jacc", 227); + put("fish.payara.server.core.security.ssl-impl", 228); + put("fish.payara.server.core.security.websecurity", 229); + put("fish.payara.server.internal.security.webservices.security", 230); + put("fish.payara.server.internal.transaction.internal-api", 231); + put("fish.payara.server.internal.transaction.jakarta.transaction", 232); + put("fish.payara.server.internal.transaction.jta", 233); + put("fish.payara.server.internal.transaction.jts", 234); + put("fish.payara.server.internal.web.cli", 235); + put("fish.payara.server.internal.web.core", 236); + put("fish.payara.server.core.web.gf-web-connector", 237); + put("fish.payara.server.core.web.glue", 238); + put("fish.payara.server.internal.web.gui-plugin-common", 239); + put("fish.payara.server.internal.web.ha", 240); + put("fish.payara.server.internal.web.jsf-connector", 241); + put("fish.payara.server.internal.web.jspcaching-connector", 242); + put("fish.payara.server.internal.web.jstl-connector", 243); + put("fish.payara.server.internal.web.naming", 244); + put("fish.payara.server.core.web.war-util", 245); + put("fish.payara.server.core.web.web-embed.api", 246); + put("fish.payara.server.internal.web.web-embed.impl", 247); + put("fish.payara.server.internal.web.weld-integration", 248); + put("fish.payara.server.internal.web.weld-integration-fragment", 249); + put("fish.payara.server.internal.webservices.connector", 250); + put("fish.payara.server.internal.webservices.jsr109-impl", 251); + put("fish.payara.server.internal.webservices.metro-glue", 252); + put("fish.payara.server.internal.webservices.soap-tcp", 253); + put("org.glassfish.metro.webservices-api-osgi", 254); + put("org.glassfish.metro.webservices-extra-jdk-packages", 255); + put("org.glassfish.metro.webservices-osgi", 256); + put("org.glassfish.web.el-impl", 257); + put("org.glassfish.web.jsp-impl", 258); + put("org.glassfish.web.jstl-impl", 259); + put("org.jboss.weld.osgi-bundle", 260); + put("org.jvnet.mimepull", 261); + put("org.shoal.cache", 262); + put("org.shoal.gms-api", 263); + put("org.shoal.gms-impl", 264); + put("stax2-api", 265); + put("woodstox-core-asl", 266); + put("com.fasterxml.jackson.dataformat.xml", 267); + put("org.objectweb.asm", 268); + put("org.objectweb.asm.commons", 269); + put("org.objectweb.asm.tree", 270); + put("org.objectweb.asm.tree.analysis", 271); + put("org.objectweb.asm.util", 272); }}); public ModuleMap() { diff --git a/appserver/security/appclient.security/pom.xml b/appserver/security/appclient.security/pom.xml index c76a04ce5b7..62d291ffaff 100644 --- a/appserver/security/appclient.security/pom.xml +++ b/appserver/security/appclient.security/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -117,5 +117,9 @@ fish.payara.server.core.orb orb-connector + + org.glassfish.epicyro + epicyro + diff --git a/appserver/security/core-ee/pom.xml b/appserver/security/core-ee/pom.xml index 3172d64f9c3..a8ce5bb84fe 100644 --- a/appserver/security/core-ee/pom.xml +++ b/appserver/security/core-ee/pom.xml @@ -232,10 +232,6 @@ jakarta.security.enterprise jakarta.security.enterprise-api provided - - - fish.payara.server.core.security - jaspic.provider.framework fish.payara.server.core.common diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java index fb41dad5358..9e4887308d5 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java @@ -44,7 +44,7 @@ import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; -import com.sun.enterprise.security.ee.authorize.PolicyLoader; +import com.sun.enterprise.security.PolicyLoader; import com.sun.logging.LogDomains; import jakarta.inject.Inject; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java index 7951de32a2f..e34465247d3 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java @@ -49,7 +49,6 @@ import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.security.jauth.AuthParam; import org.glassfish.epicyro.services.RegistrationWrapperRemover; /** @@ -88,18 +87,5 @@ public interface WebServicesDelegate extends RegistrationWrapperRemover { * @return the AuthContextID computed from the argument MessageInfo */ String getAuthContextID(MessageInfo messageInfo); - - /** - * @param messageInfo TheMessageInfo - * @return a new instance of SOAPAuthParam - */ - AuthParam newSOAPAuthParam(MessageInfo messageInfo); - - /** - * Return the SOAP Message from the invocation, to be used by JACC PolicyContextHandler - * - * @param componentInvocation the invocation - * @return the SOAP Message - */ - Object getSOAPMessage(ComponentInvocation componentInvocation); + } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java index b86bbf84028..81cefd76b61 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java @@ -49,7 +49,7 @@ import com.sun.enterprise.deployment.runtime.common.wls.SecurityRoleAssignment; import com.sun.enterprise.deployment.runtime.web.SunWebApp; import com.sun.enterprise.deployment.web.LoginConfiguration; -import com.sun.enterprise.security.ee.authorize.PolicyLoader; +import com.sun.enterprise.security.PolicyLoader; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityRoleMapperFactoryGen; import com.sun.enterprise.security.SecurityServicesUtil; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java index 96c34b3ef69..4fa54399e1c 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java @@ -59,7 +59,7 @@ * *

* The pluggable JACC components are loaded by a class in nucleus: - * {@link com.sun.enterprise.security.ee.authorize.PolicyLoader} + * {@link com.sun.enterprise.security.PolicyLoader} * */ package com.sun.enterprise.security.jacc; \ No newline at end of file diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java index 0938890cbf7..f980089d138 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java @@ -52,7 +52,7 @@ * *

* Code in this package builds upon the general (server independent) JASPIC Provider - * Framework Reference Implementation (org.glassfish.main.security:jaspic.provider.framework). + * Framework Reference Implementation. * It adds to this framework by implementing the Payara specific bits. * *

diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthConfig.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthConfig.java deleted file mode 100644 index c4ccbafd8c5..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthConfig.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import javax.security.auth.callback.CallbackHandler; - -/** - * This class manages the configuration AuthModules. - * - *

- * An AuthModule represents a pluggable component for performing security-related request and response processing, and - * can be configured for a particular interception point and provider ID. The provider ID is an administrator-defined - * value. The standard interception points include: - * - *

    - *
  • HTTP - *
  • EJB - *
  • SOAP - *
- * - *

- * Information may be associated with a configured module, including its fully qualified class name (so it can be - * instantiated), and module options (which help tune the behavior of the module). It is the responsibility of the - * AuthConfig implementation to load any required module information. - * - *

- * Callers do not operate on AuthModules directly. Instead they rely on a ClientAuthContext or ServerAuthContext to - * manage the invocation of modules. A caller obtains an instance of ClientAuthContext or ServerAuthContext by calling - * the getClientAuthContext or getServerAuthContext method, respectively. Each method takes as - * arguments an intercept, an id, a requestPolicy, and a responsePolicy. - * - *

- * An AuthConfig implementation determines the modules to be invoked via the intercept and id values. It - * then encapsulates those modules in a ClientAuthContext or ServerAuthContext instance, and returns that instance. The - * returned object is responsible for instantiating, initializing, and invoking the configured modules (when called - * upon). - * - *

- * The module initializion step involves calling each configured module's AuthModule.initialize method. The - * received requestPolicy and responsePolicy are passed to this method. It is then the modules' - * responsibility, when invoked, to enforce these policies. - * - *

- * A system-wide AuthConfig instance can be retrieved by invoking getConfig. A default implementation is - * provided, and can be replaced by setting the value of the "authconfig.provider" security property (in the Java - * security properties file) to the fully qualified name of the desired implementation class. The Java security - * properties file is located in the file named <JAVA_HOME>/lib/security/java.security, where <JAVA_HOME> - * refers to the directory where the JDK was installed. - * - * @version %I%, %G% - * @see ClientAuthContext - * @see ServerAuthContext - */ -public abstract class AuthConfig { - - /** - * HTTP interception point. - */ - public static final String HTTP = "HTTP"; - - /** - * EJB interception point. - */ - public static final String EJB = "EJB"; - - /** - * SOAP interception point. - */ - public static final String SOAP = "SOAP"; - - // security property to replace default AuthConfig implementation - private static final String AUTHCONFIG_PROPERTY = "authconfig.provider"; - - // class name of default AuthConfig implementation - private static final String DEFAULT_CLASS = "com.sun.enterprise.security.jauth.ConfigFile"; - - private static AuthConfig config; - - // package private for ConfigFile - static ClassLoader getClassLoader() { - - final ClassLoader rvalue; - - rvalue = (ClassLoader) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() { - @Override - public Object run() { - return Thread.currentThread().getContextClassLoader(); - } - }); - - return rvalue; - }; - - /** - * Sole constructor. (For invocation by subclass constructors, typically implicit.) - */ - protected AuthConfig() { - } - - /** - * Get a system-wide module configuration. - * - *

- * If an AuthConfig object was set via the setAuthConfig method, then that object is returned. Otherwise, - * an instance of the AuthConfig object configured in the authconfig.provider security property is returned. If - * that property is not set, a default implementation is returned. - * - * @return a system-wide AuthConfig instance. - * - * @exception SecurityException if the caller does not have permission to retrieve the configuration. - */ - public static synchronized AuthConfig getAuthConfig() { - /** - * XXX security check? SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new - * AuthPermission("getAuthConfig")); - */ - - if (config == null) { - String config_class = null; - config_class = (String) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() { - @Override - public Object run() { - return java.security.Security.getProperty(AUTHCONFIG_PROPERTY); - } - }); - if (config_class == null) { - config_class = DEFAULT_CLASS; - } - - try { - final String finalClass = config_class; - config = (AuthConfig) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws ClassNotFoundException, - InstantiationException, - IllegalAccessException { - return Class.forName(finalClass, - true, - getClassLoader()).newInstance(); - } - }); - } catch (java.security.PrivilegedActionException e) { - throw (SecurityException) new SecurityException().initCause(e.getException()); - } - } - return config; - } - - /** - * Set a system-wide module configuration. - * - * @param config the new configuration. - * - * @exception SecurityException if the caller does not have permission to set the configuration. - */ - public static void setAuthConfig(AuthConfig config) { - /** - * XXX security check? SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new - * AuthPermission("setAuthConfig")); } - */ - - AuthConfig.config = config; - } - - /** - * Get a ClientAuthContext. - * - *

- * The modules configured for the returned ClientAuthContext are determined by the intercept and provider - * id input parameters. The returned ClientAuthContext may be null, which signifies that there are no modules - * configured. - * - *

- * The returned ClientAuthContext encapsulates both the configured modules, as well as the module invocation semantics - * (for example the order modules are to be invoked, and whether certain modules must succeed). Individual - * ClientAuthContext implementations may enforce custom module invocation semantics. - * - * @param intercept the interception point used to determine the modules configured for the returned ClientAuthContext. - * Standard values include: - *

    - *
  • HTTP - *
  • EJB - *
  • SOAP - *
- * - * @param id the provider id used to determine the modules configured for the returned ClientAuthContext, or null. If - * null, a default ID may be used. - * - * @param requestPolicy the application request policy to be enfored by the modules, or null. If null, a default request - * policy may be used. - * - * @param responsePolicy the application response policy to be enfored by the modules, or null. If null, a default - * response policy may be used. - * - * @param handler the CallbackHandler to associate with the returned ClientAuthContext for use by configured modules to - * request information from the caller, or null. If null, a default handler may be used. - * - * @return a ClientAuthContext, or null. - */ - public abstract ClientAuthContext getClientAuthContext(String intercept, - String id, - AuthPolicy requestPolicy, - AuthPolicy responsePolicy, - CallbackHandler handler) - throws AuthException; - - /** - * Get a ServerAuthContext. - * - *

- * The modules configured for the returned ServerAuthContext are determined by the intercept and provider - * id, input parameters. The returned ServerAuthContext may be null, which signifies that there are no modules - * configured. - * - *

- * The returned ServerAuthContext encapsulates both the configured modules, as well as the module invocation semantics - * (for example the order modules are to be invoked, and whether certain modules must succeed). Individual - * ServerAuthContext implementations may enforce custom module invocation semantics. - * - * @param intercept the interception point used to determine the modules configured for the returned ServerAuthContext. - * Standard values include: - *

    - *
  • HTTP - *
  • EJB - *
  • SOAP - *
- * - * @param id the provider id used to determine the modules configured for the returned ClientAuthContext, or null. If - * null, a default id may be used. - * - * @param requestPolicy the application request policy to be enfored by the modules, or null. If null, a default request - * policy may be used. - * - * @param responsePolicy the application response policy to be enfored by the modules, or null. If null, a default - * response policy may be used. - * - * @param handler the CallbackHandler to associate with the returned ClientAuthContext, which can be used by configured - * modules to request information from the caller, or null. If null, a default handler may be used. - * - * @return a ServerAuthContext, or null. - */ - public abstract ServerAuthContext getServerAuthContext(String intercept, - String id, - AuthPolicy requestPolicy, - AuthPolicy responsePolicy, - CallbackHandler handler) - throws AuthException; - - /** - * Refresh the internal representation of the active configuration by re-reading the provider configs. - */ - public abstract void refresh() throws AuthException; -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthContext.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthContext.java deleted file mode 100644 index a1ca1193e32..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthContext.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import java.util.*; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.login.AppConfigurationEntry; - -/** - * Shared logic from Client and ServerAuthContext reside here. - */ -final class AuthContext { - - static final String INIT = "initialize"; - static final String DISPOSE_SUBJECT = "disposeSubject"; - - static final String SECURE_REQUEST = "secureRequest"; - static final String VALIDATE_RESPONSE = "validateResponse"; - - static final String VALIDATE_REQUEST = "validateRequest"; - static final String SECURE_RESPONSE = "secureResponse"; - - // managesSessions method is implemented by looking for - // corresponding option value in module configuration - static final String MANAGES_SESSIONS = "managesSessions"; - static final String MANAGES_SESSIONS_OPTION = "managessessions"; - - private ConfigFile.Entry[] entries; - private Logger logger; - - AuthContext(ConfigFile.Entry[] entries, - Logger logger) throws AuthException { - - this.entries = entries; - this.logger = logger; - } - - /** - * Invoke modules according to configuration - */ - Object[] invoke(final String methodName, final Object[] args) - throws AuthException { - - // invoke modules in a doPrivileged - final Object rValues[] = new Object[entries.length]; - - try { - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - @Override - public Object run() throws AuthException { - invokePriv(methodName, args, rValues); - return null; - } - }); - } catch (java.security.PrivilegedActionException pae) { - if (pae.getException() instanceof AuthException) { - throw (AuthException) pae.getException(); - } else { - AuthException ae = new AuthException(); - ae.initCause(pae.getException()); - throw ae; - } - } - return rValues; - } - - void invokePriv(String methodName, Object[] args, Object[] rValues) - throws AuthException { - - // special treatment for managesSessions until the module - // interface can be extended. - if (methodName.equals(AuthContext.MANAGES_SESSIONS)) { - for (int i = 0; i < entries.length; i++) { - Map options = entries[i].getOptions(); - String mS = (String) options.get(AuthContext.MANAGES_SESSIONS_OPTION); - rValues[i] = Boolean.valueOf(mS); - } - return; - } - - boolean success = false; - AuthException firstRequiredError = null; - AuthException firstError = null; - - // XXX no way to reverse module invocation - - for (int i = 0; i < entries.length; i++) { - - // get initialized module instance - - Object module = entries[i].module; - - // invoke the module - - try { - Method[] mArray = module.getClass().getMethods(); - for (int j = 0; j < mArray.length; j++) { - if (mArray[j].getName().equals(methodName)) { - - // invoke module - rValues[i] = mArray[j].invoke(module, args); - - // success - - // return if SUFFICIENT and no previous REQUIRED errors - - if (firstRequiredError == null && - entries[i].getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT) { - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " SUFFICIENT success"); - } - - return; - } - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " success"); - } - - success = true; - break; - } - } - - if (!success) { - // PLEASE NOTE: - // this exception will be thrown if any module - // in the context does not support the method. - NoSuchMethodException nsme = new NoSuchMethodException("module " + - module.getClass().getName() + - " does not implement " + - methodName); - AuthException ae = new AuthException(); - ae.initCause(nsme); - throw ae; - } - } catch (IllegalAccessException iae) { - AuthException ae = new AuthException(); - ae.initCause(iae); - throw ae; - } catch (InvocationTargetException ite) { - - // failure cases - - AuthException ae; - - if (ite.getCause() instanceof AuthException) { - ae = (AuthException) ite.getCause(); - } else { - ae = new AuthException(); - ae.initCause(ite.getCause()); - } - - if (entries[i].getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.REQUISITE) { - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " REQUISITE failure"); - } - - // immediately throw exception - - if (firstRequiredError != null) { - throw firstRequiredError; - } else { - throw ae; - } - - } else if (entries[i].getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.REQUIRED) { - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " REQUIRED failure"); - } - - // save exception and continue - - if (firstRequiredError == null) { - firstRequiredError = ae; - } - - } else { - - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine(entries[i].getLoginModuleName() + - "." + - methodName + - " OPTIONAL failure"); - } - - // save exception and continue - - if (firstError == null) { - firstError = ae; - } - } - } - } - - // done invoking entire stack of modules - - if (firstRequiredError != null) { - throw firstRequiredError; - } else if (firstError != null && !success) { - throw firstError; - } - - // if no errors, return gracefully - if (logger != null && logger.isLoggable(Level.FINE)) { - logger.fine("overall " + methodName + " success"); - } - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthException.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthException.java deleted file mode 100644 index 2dac232f1a2..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthException.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * A generic authentication exception. - * - * @version %I%, %G% - */ -public class AuthException extends jakarta.security.auth.message.AuthException { - - private static final long serialVersionUID = -1156951780670243758L; - - /** - * Constructs a AuthException with no detail message. A detail message is a String that describes this particular - * exception. - */ - public AuthException() { - super(); - } - - /** - * Constructs a AuthException with the specified detail message. A detail message is a String that describes this - * particular exception. - * - *

- * - * @param msg the detail message. - */ - public AuthException(String msg) { - super(msg); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthParam.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthParam.java deleted file mode 100644 index e2aabb1a542..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthParam.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * An authentication parameter used to encapsulate a request and response objects. - * - *

- * This is a marker interface for container-specific authentication parameters. - * - * @version %I%, %G% - */ -public interface AuthParam { -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthPolicy.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthPolicy.java deleted file mode 100644 index 71df8df6079..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/AuthPolicy.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2021] Payara Foundation and/or affiliates - -package com.sun.enterprise.security.jauth; - -import jakarta.security.auth.message.MessagePolicy; - -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy; -import static jakarta.security.auth.message.MessagePolicy.TargetPolicy; - -/* - * This class is used to define the message authentication policy that informs - * the actions of AuthModules. - * - *

This class is used to define source and recipient authentication - * policies. Source authentication is used to establish the identity of - * either the message sender or the party that established the message contents. - * Recipient authentication is used to establish the identity of the receiver - * of the message before it is sent. - * - *

This class is used used by the AuthConfig class to define the request and - * response authentication policies associated with Client and Server - * AuthModules. - * - * @version %I%, %G% - * @see AuthConfig - * @see ClientAuthModule - * @see ServerAuthModule - */ -//Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -public class AuthPolicy { - - public static final int SOURCE_AUTH_NONE = 0; - public static final int SOURCE_AUTH_SENDER = 1; - public static final int SOURCE_AUTH_CONTENT = 2; - - public static final String SENDER = "sender"; - public static final String CONTENT = "content"; - public static final String BEFORE_CONTENT = "before-content"; - public static final String AFTER_CONTENT = "after-content"; - - private int authenticateSource = SOURCE_AUTH_NONE; - private boolean authenticateRecipient = false; - private boolean recipientBeforeContent = false; - - private void setAuthenticationType(int sourceAuthType) { - switch (sourceAuthType) { - case SOURCE_AUTH_NONE: - case SOURCE_AUTH_SENDER: - case SOURCE_AUTH_CONTENT: - this.authenticateSource = sourceAuthType; - break; - default: - break; - } - } - - public AuthPolicy() { - } - - public AuthPolicy(int sourceAuthenticationType, - boolean authenticateRecipient, boolean beforeContent) { - setAuthenticationType(sourceAuthenticationType); - this.authenticateRecipient = authenticateRecipient; - this.recipientBeforeContent = beforeContent; - } - - public AuthPolicy(MessagePolicy messagePolicy) { - if (messagePolicy != null) { - TargetPolicy[] targetPolicies = messagePolicy.getTargetPolicies(); - if (targetPolicies != null && targetPolicies.length > 0) { - int contentInd = -1; - int recipientInd = -1; - for (int i = 0; i < targetPolicies.length; i++) { - ProtectionPolicy pp = targetPolicies[i].getProtectionPolicy(); - - if (ProtectionPolicy.AUTHENTICATE_RECIPIENT.equals( - pp.getID())) { - recipientInd = i; - this.authenticateRecipient = true; - } else if (ProtectionPolicy.AUTHENTICATE_SENDER.equals( - pp.getID())) { - contentInd = i; - setAuthenticationType(SOURCE_AUTH_SENDER); - } else if (ProtectionPolicy.AUTHENTICATE_CONTENT.equals( - pp.getID())) { - contentInd = i; - setAuthenticationType(SOURCE_AUTH_CONTENT); - } - } - - if (authenticateRecipient && contentInd >= 0) { - this.recipientBeforeContent = (recipientInd < contentInd); - } - } - } - } - - public void setSourceAuth(int sourceAuthenticationType) { - setAuthenticationType(sourceAuthenticationType); - } - - /* - * Set the source of the message content authentication policy. - * @param required boolean value. When true authentication of the source of the message content is required. When false, - * content authentication will not be required and if authentication of the message sender is required it will remain - * so. - */ - public void setContentAuth(boolean required) { - if (required) { - this.setSourceAuth(SOURCE_AUTH_CONTENT); - } else if (!isSenderAuthRequired()) { - this.setSourceAuth(SOURCE_AUTH_NONE); - } - } - - /* - * Set the message sender authentication policy. - * @param required boolean value. When true authentication of the message sender is required. When false, sender - * authentication will not be required and if authentication of the message content is required it will remain so. - */ - public void setSenderAuth(boolean required) { - if (required) { - this.setSourceAuth(SOURCE_AUTH_SENDER); - } else if (!isContentAuthRequired()) { - this.setSourceAuth(SOURCE_AUTH_NONE); - } - } - - public void setRecipientAuth(boolean required, boolean beforeContent) { - this.authenticateRecipient = required; - this.recipientBeforeContent = beforeContent; - } - - public int getSourceAuth() { - return this.authenticateSource; - } - - public boolean authRequired() { - return this.isSourceAuthRequired() || this.isRecipientAuthRequired(); - } - - public boolean isSourceAuthRequired() { - return this.authenticateSource == 0 ? false : true; - } - - public boolean isSenderAuthRequired() { - return (this.isSourceAuthRequired() ? (this.getSourceAuth() == SOURCE_AUTH_SENDER ? true : false) : false); - } - - public boolean isContentAuthRequired() { - return (this.isSourceAuthRequired() ? (this.getSourceAuth() == SOURCE_AUTH_CONTENT ? true : false) : false); - } - - public boolean isRecipientAuthRequired() { - return this.authenticateRecipient; - } - - // This method interprets order from the perspective of the - // message sender. The value returned by this method, is only - // relevant when recipientAuth is required. - public boolean isRecipientAuthBeforeContent() { - return this.recipientBeforeContent; - } - - // When orderForValidation is true, returns true if validator must - // validate recipient auth (e.g. decrypt) before content auth (e.g. verify - // signature); in which case msg sender did content auth before recipient auth. - // Behaves same as noArg variant when orderForValidation is false. In either - // case, the returned value is only relevant when recipientAuth is required. - public boolean isRecipientAuthBeforeContent(boolean orderForValidation) { - return (orderForValidation ? !this.recipientBeforeContent : this.recipientBeforeContent); - } - - @Override - public String toString() { - - // wait for 1.5 - // StringBuilder sb = new StringBuilder(); - StringBuilder sb = new StringBuilder(); - switch (authenticateSource) { - case SOURCE_AUTH_NONE: - sb.append("source-auth-type = SOURCE_AUTH_NONE"); - break; - case SOURCE_AUTH_SENDER: - sb.append("source-auth-type = SOURCE_AUTH_SENDER"); - break; - case SOURCE_AUTH_CONTENT: - sb.append("source-auth-type = SOURCE_AUTH_CONTENT"); - break; - default: - break; - } - - if (authenticateRecipient) { - sb.append("\n\tauthenticate-recipient=true" + - "\n\tbeforeContent=" + recipientBeforeContent); - } else { - sb.append("\n\tauthenticate-recipient=false"); - } - return sb.toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (!(o instanceof AuthPolicy)) { - return false; - } - - AuthPolicy that = (AuthPolicy) o; - if (this.authenticateSource == that.authenticateSource && - this.authenticateRecipient == that.authenticateRecipient && - this.recipientBeforeContent == that.recipientBeforeContent) { - return true; - } - - return false; - } - - @Override - public int hashCode() { - return authenticateSource + - (authenticateRecipient ? 5 : 0) + - (recipientBeforeContent ? 10 : 0); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthContext.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthContext.java deleted file mode 100644 index 5da320ce0eb..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthContext.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * This ClientAuthContext class manages AuthModules that may be used to secure requests made as a client. A caller - * typically uses this class in the following manner: - * - *

    - *
  1. Retrieve an instance of this class via AuthConfig.getClientAuthContext. - *
  2. Invoke secureRequest.
    - * ClientAuthContext implementation invokes configured plug-in modules. Modules attach credentials to initial request - * object (for example, a username and password), and/or secure the request (for example, sign and encrypt the request). - *
  3. Issue request. - *
  4. Receive response and pass it to validateResponse.
    - * ClientAuthContext implementation invokes configured plug-in modules. Modules verify or decrypt response as necessary. - *
  5. The disposeSubject method may be invoked if necessary to clean up any authentication state in the Subject. - *
- * - *

- * An instance may reuse module instances it previously created. As a result a single module instance may be used to - * issue different requests as different clients. It is the module implementation's responsibility to properly store and - * restore any necessary state. A module that does not need to do so may remain completely stateless. - * - *

- * Instances of this class have custom logic to determine what modules to invoke, and in what order. In addition, this - * custom logic may control whether subsequent modules are invoked based on the success or failure of previously invoked - * modules. - * - *

- * The caller is responsible for passing in a state Map that can be used by underlying modules to save state across a - * sequence of calls from secureRequest to validateResponse to disposeSubject. - * The same Map instance must be passed to all methods in the call sequence. Furthermore, each call sequence should be - * passed its own unique shared state Map instance. - * - * @version %I%, %G% - * @see AuthConfig - * @see SOAPAuthParam - */ -public interface ClientAuthContext { - - /** - * Secure a request message. - * - *

- * Attach authentication credentials to an initial request, sign/encrypt a request, or respond to a server challenge, - * for example. - * - *

- * This method invokes configured modules to secure the request. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to obtain Principals and credentials necessary to secure - * the request, or null. If null, the module may use a CallbackHandler to obtain any information necessary to secure the - * request. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void secureRequest(AuthParam param, - javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * Validate received response. - * - *

- * Validation may include verifying signature in response, or decrypting response contents, for example. - * - *

- * This method invokes configured modules to validate the response. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to store the Principals and credentials related to the - * identity validated in the response. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void validateResponse(AuthParam param, - javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * Dispose of the Subject (remove Principals or credentials from the Subject object that were stored during - * validateResponse). - * - *

- * This method invokes configured modules to dispose the Subject. - * - * @param subject the subject to be disposed. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void disposeSubject(javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthModule.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthModule.java deleted file mode 100644 index 624748ec5c0..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ClientAuthModule.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; - -/** - * This interface describes a module that can be configured for a ClientAuthContext. The main purpose of this module is - * to secure requests and to validate received responses. - * - *

- * A module implementation must assume it may be used to issue different requests as different clients. It is the module - * implementation's responsibility to properly store and restore any state as necessary. A module that does not need to - * do so may remain completely stateless. - * - *

- * Modules are passed a shared state Map that can be used to save state across a sequence of calls from - * secureRequest to validateResponse to disposeSubject. The same Map instance is - * guaranteed to be passed to all methods in the call sequence. Furthermore, it should be assumed that each call - * sequence is passed its own unique shared state Map instance. - * - * @version %I%, %G% - */ -public interface ClientAuthModule { - - /** - * Initialize this module with a policy to enforce, a CallbackHandler, and administrative options. - * - *

- * Either the the request policy or the response policy (or both) must be non-null. - * - * @param requestPolicy the request policy this module is to enforce, which may be null. - * - * @param responsePolicy the response policy this module is to enforce, which may be null. - * - * @param handler CallbackHandler used to request information from the caller. - * - * @param options administrative options. - */ - void initialize(AuthPolicy requestPolicy, - AuthPolicy responsePolicy, - CallbackHandler handler, - Map options); - - /** - * Secure a request message. - * - *

- * Attach authentication credentials to an initial request, sign/encrypt a request, or respond to a server challenge, - * for example. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to obtain Principals and credentials necessary to secure - * the request, or null. If null, the module may use a CallbackHandler to obtain any information necessary to secure the - * request. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void secureRequest(AuthParam param, - Subject subject, - Map sharedState) - throws AuthException; - - /** - * Validate received response. - * - *

- * Validation may include verifying signature in response, or decrypting response contents, for example. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to store the Principals and credentials related to the - * identity validated in the response. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void validateResponse(AuthParam param, - Subject subject, - Map sharedState) - throws AuthException; - - /** - * Dispose of the Subject. - * - *

- * Remove Principals or credentials from the Subject object that were stored during validateResponse. - * - * @param subject Subject instance to be disposed. - * - * @param sharedState a Map for modules to save state across a sequence of calls from secureRequest to - * validateResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void disposeSubject(Subject subject, Map sharedState) - throws AuthException; -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/DependentCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/DependentCallbackHandler.java deleted file mode 100644 index bafec7e8b76..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/DependentCallbackHandler.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * A marker interface that may be implemented by a CallBackHandler. - *

- * When a CallbackHandler that implements this interface, is passed as an argument to the getServerAuthContext or - * getClientAuthContext methods of the AuthConfig class, the AuthConfig system will wrap the handler in a special - * internal CallbackHandler that will delegate any unsupported Callbacks to the default CallbackHandler of the - * AuthConfig system. The modules of the context will receive this wrapping handler at initialization, and the effect - * will be to allow systems to extend or override the callbacks handled by the default handler of the config system with - * those handled by the wrapped handler. - * - * @version %I%, %G% - */ -public interface DependentCallbackHandler { -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/FailureException.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/FailureException.java deleted file mode 100644 index 827caf61726..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/FailureException.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * Authentication failed. - * - *

- * This exception is thrown by an AuthModule when authentication failed. This exception is only thrown when the module - * has updated the response message in the AuthParam. - * - * @version %I%, %G% - */ -public class FailureException extends AuthException { - - private static final long serialVersionUID = -6634814390418917726L; - - /** - * Constructs a FailureException with no detail message. A detail message is a String that describes this particular - * exception. - */ - public FailureException() { - super(); - } - - /** - * Constructs a FailureException with the specified detail message. A detail message is a String that describes this - * particular exception. - * - * @param msg the detail message. - */ - public FailureException(String msg) { - super(msg); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/HttpServletAuthParam.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/HttpServletAuthParam.java deleted file mode 100644 index 05621e80bc6..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/HttpServletAuthParam.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import jakarta.security.auth.message.MessageInfo; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -/** - * An HTTP Servlet authentication parameter that encapsulates HTTP Servlet request and response objects. - * - *

- * HttpServletAuthParam may be created with null request or response objects. The following table describes when it is - * appropriate to pass null: - * - *

- *                                        Request   Response
- *                                        -------   --------
- *
- * ClientAuthModule.secureRequest         non-null  null
- * ClientAuthModule.validateResponse      null      non-null
- *
- * ServerAuthModule.validateRequest       non-null  null
- * ServerAuthModule.secureResponse        null      non-null
- * 
- * - *

- * As noted above, in the case of ServerAuthModule.validateRequest the module receives a null response - * object. If the implementation of validateRequest encounters an authentication error, it may construct - * the appropriate response object itself and set it into the HttpServletAuthParam via the setResponse - * method. - * - * @version %I%, %G% - */ -public class HttpServletAuthParam implements AuthParam { - - private HttpServletRequest request; - private HttpServletResponse response; - // private static final MessageLayer layer = - // new MessageLayer(MessageLayer.HTTP_SERVLET); - - /** - * Create an HttpServletAuthParam with HTTP request and response objects. - * - * @param request the HTTP Servlet request object, or null. - * @param response the HTTP Servlet response object, or null. - */ - public HttpServletAuthParam(HttpServletRequest request, - HttpServletResponse response) { - this.request = request; - this.response = response; - } - - /** - * Create an HttpServletAuthParam with MessageInfo object. - * - * @param messageInfo - * - */ - public HttpServletAuthParam(MessageInfo messageInfo) { - this.request = (HttpServletRequest) messageInfo.getRequestMessage(); - this.response = (HttpServletResponse) messageInfo.getResponseMessage(); - } - - /** - * Get the HTTP Servlet request object. - * - * @return the HTTP Servlet request object, or null. - */ - public HttpServletRequest getRequest() { - return this.request; - } - - /** - * Get the HTTP Servlet response object. - * - * @return the HTTP Servlet response object, or null. - */ - public HttpServletResponse getResponse() { - return this.response; - } - - /** - * Set a new HTTP Servlet response object. - * - *

- * If a response has already been set (it is non-null), this method returns. The original response is not overwritten. - * - * @param response the HTTP Servlet response object. - * - * @exception IllegalArgumentException if the specified response is null. - */ - public void setResponse(HttpServletResponse response) { - if (response == null) { - throw new IllegalArgumentException("invalid null response"); - } - - if (this.response == null) { - this.response = response; - } - } - - /** - * Get a MessageLayer instance that identifies HttpServlet as the message layer. - * - * @return a MessageLayer instance that identifies HttpServlet as the message layer. - */ - // public MessageLayer getMessageLayer() { - // return layer; - // }; - - /** - * Get the operation related to the encapsulated HTTP Servlet request and response objects. - * - * @return the operation related to the encapsulated request and response objects, or null. - */ - public String getOperation() { - return null; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/PendingException.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/PendingException.java deleted file mode 100644 index 62e0d0fa039..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/PendingException.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * Authentication is pending. - * - *

- * This exception can be thrown by an AuthModule issuing a challenge, for example. - * - * @version %I%, %G% - */ -public class PendingException extends AuthException { - - private static final long serialVersionUID = 1735672964915327465L; - - /** - * Constructs a PendingException with no detail message. A detail message is a String that describes this particular - * exception. - */ - public PendingException() { - super(); - } - - /** - * Constructs a PendingException with the specified detail message. A detail message is a String that describes this - * particular exception. - * - *

- * - * @param msg the detail message. - */ - public PendingException(String msg) { - super(msg); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthContext.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthContext.java deleted file mode 100644 index 800f836cb8c..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthContext.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -/** - * This ServerAuthContext class manages AuthModules that may be used to validate client requests. A caller typically - * uses this class in the following manner: - * - *

    - *
  1. Retrieve an instance of this class via AuthConfig.getServerAuthContext. - *
  2. Receive initial client request and pass it to validateRequest.
    - * Configured plug-in modules validate credentials present in request (for example, decrypt and verify a signature). If - * credentials valid and sufficient, return. Otherwise throw an AuthException. - *
  3. Authentication complete.
    - * Perform authorization check on authenticated identity and, if successful, dispatch to requested service application. - *
  4. Service application finished. - *
  5. Invoke secureResponse.
    - * Configured modules secure response (sign and encrypt it, for example). - *
  6. Send final response to client. - *
  7. The disposeSubject method may be invoked it necessary to clean up any authentication state in the Subject. - *
- * - *

- * An instance may reuse module instances it previous created. As a result a single module instance may be used to - * process different requests from different clients. It is the module implementation's responsibility to properly store - * and restore any state necessary to associate new requests with previous responses. A module that does not need to do - * so may remain completely stateless. - * - *

- * Instances of this class have custom logic to determine what modules to invoke, and in what order. In addition, this - * custom logic may control whether subsequent modules are invoked based on the success or failure of previously invoked - * modules. - * - *

- * The caller is responsible for passing in a state Map that can be used by underlying modules to save state across a - * sequence of calls from validateRequest to secureResponse to disposeSubject. - * The same Map instance must be passed to all methods in the call sequence. Furthermore, each call sequence should be - * passed its own unique shared state Map instance. - * - * @version %I%, %G% - * @see AuthConfig - * @see SOAPAuthParam - */ -public interface ServerAuthContext { - - /** - * Authenticate a client request. (decrypt the message and verify a signature, for exmaple). - * - *

- * This method invokes configured modules to authenticate the request. - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to store and Principals and credentials validated in the - * request. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception PendingException if the operation is pending (for example, when a module issues a challenge). The module - * must have updated the response object in the AuthParam input parameter. - * - * @exception FailureException if the authentication failed. The module must have updated the response object in the - * AuthParam input parameter. - * - * @exception AuthException if the operation failed. - */ - void validateRequest(AuthParam param, - javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * Secure the response to the client (sign and encrypt the response, for example). - * - *

- * This method invokes configured modules to secure the response. - * - * @param param an authentication parameter that encapsulates the client request and server response objects - * - * @param subject the subject may be used by configured modules to obtain credentials needed to secure the response, or - * null. If null, the module may use a CallbackHandler to obtain the necessary information. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void secureResponse(AuthParam param, - javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * Dispose of the Subject (remove Principals or credentials from the Subject object that were stored during - * validateRequest). - * - *

- * This method invokes configured modules to dispose the Subject. - * - * @param subject the subject to be disposed. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void disposeSubject(javax.security.auth.Subject subject, - java.util.Map sharedState) - throws AuthException; - - /** - * modules manage sessions used by calling container to determine if it should delegate session management (including - * the mapping of requests to authentication results established from previous requests) to the underlying - * authentication modules of the context. - *

- * When this method returns true, the container should call validate on every request, and as such may depend on the - * invoked modules to determine when a request pertains to an existing authentication session. - *

- * When this method returns false, the container may employ is own session management functionality, and may use this - * functionality to recognize when an exiting request is to be interpretted in the context of an existing authentication - * session. - * - * @return true if the context should be allowed to manage sessions, and false if session management (if it is to occur) - * must be performed by the container. - * - * @exception AuthException if the operation failed. - */ - boolean managesSessions(java.util.Map sharedState) - throws AuthException; - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthModule.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthModule.java deleted file mode 100644 index c7515e443dc..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/ServerAuthModule.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2006-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth; - -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; - -/** - * This interface describes a module that can be configured for a ServerAuthContext. The main purpose of this module is - * to validate client requests and to secure responses back to the client. - * - *

- * A module implementation must assume it may be shared across different requests from different clients. It is the - * module implementation's responsibility to properly store and restore any state necessary to associate new requests - * with previous responses. A module that does not need to do so may remain completely stateless. - * - *

- * Modules are passed a shared state Map that can be used to save state across a sequence of calls from - * validateRequest to secureResponse to disposeSubject. The same Map instance is - * guaranteed to be passed to all methods in the call sequence. Furthermore, it should be assumed that each call - * sequence is passed its own unique shared state Map instance. - * - * @version %I%, %G% - */ -public interface ServerAuthModule { - - /** - * Initialize this module with a policy to enforce, a CallbackHandler, and administrative options. - * - *

- * Either the the request policy or the response policy (or both) must be non-null. - * - * @param requestPolicy the request policy this module is to enforce, which may be null. - * - * @param responsePolicy the response policy this module is to enforce, which may be null. - * - * @param handler CallbackHandler used to request information from the caller. - * - * @param options administrative options. - */ - void initialize(AuthPolicy requestPolicy, - AuthPolicy responsePolicy, - CallbackHandler handler, - Map options); - - /** - * Authenticate a client request. - * - *

- * The AuthParam input parameter encapsulates the client request and server response objects. This ServerAuthModule - * validates the client request object (decrypts content and verifies a signature, for example). - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to store and Principals and credentials validated in the - * request. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception PendingException if the operation is pending (for example, when a module issues a challenge). The module - * must have updated the response object in the AuthParam. - * - * @exception FailureException if the authentication failed. The module must have updated the response object in the - * AuthParam. - * - * @exception AuthException if the operation failed. - */ - void validateRequest(AuthParam param, - Subject subject, - Map sharedState) - throws AuthException; - - /** - * Secure the response to the client (sign and encrypt the response, for example). - * - * @param param an authentication parameter that encapsulates the client request and server response objects. - * - * @param subject the subject may be used by configured modules to obtain credentials needed to secure the response, or - * null. If null, the module may use a CallbackHandler to obtain the necessary information. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void secureResponse(AuthParam param, - Subject subject, - Map sharedState) - throws AuthException; - - /** - * Dispose of the Subject. - * - *

- * Remove Principals or credentials from the Subject object that were stored during validateRequest. - * - * @param subject the Subject instance to be disposed. - * - * @param sharedState a Map for modules to save state across a sequence of calls from validateRequest to - * secureResponse to disposeSubject. - * - * @exception AuthException if the operation failed. - */ - void disposeSubject(Subject subject, Map sharedState) - throws AuthException; -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/CertStoreCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/CertStoreCallback.java deleted file mode 100644 index fd48ab23dd3..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/CertStoreCallback.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.security.KeyStore; -import java.security.cert.CertStore; -import javax.security.auth.callback.Callback; - -/** - * Callback for CertStore. - * - *

A CertStore is a generic repository for certificates. - * CertStores may be searched to locate public key certificates, - * as well as to put together certificate chains. - * Such a search may be necessary when the caller needs to - * verify a signature. - * - * @version %I%, %G% - */ -public class CertStoreCallback extends - jakarta.security.auth.message.callback.CertStoreCallback { - - /** - * Set the CertStore. - * - * @param certStore the certificate store, which may be null - * If null, the requester is assumed to already have - * access to the relevant certificate and/or chain. - */ - public void setStore(CertStore certStore) { - setCertStore(certStore); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/KerberosKeyCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/KerberosKeyCallback.java deleted file mode 100644 index 550999f79c7..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/KerberosKeyCallback.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import javax.security.auth.Subject; -import javax.security.auth.kerberos.*; -import javax.security.auth.callback.Callback; - -/** - * Callback for Kerberos Key. - * - * @version 1.4, 03/03/04 - */ -public class KerberosKeyCallback implements Callback { - - private KerberosPrincipal owner; - private KerberosKey key; - - /** - * Constructs this KerberosSubjectCallback with a KerberosPrincipal. - * - *

The owner input parameter - * specifies the owner of the KerberosKey to be returned. - * - * @param owner the owner of the KerberosKey to be returned - */ - public KerberosKeyCallback(KerberosPrincipal owner) { - this.owner = owner; - } - - /** - * Get the owner. - * - * @return the owner - */ - public KerberosPrincipal getOwner() { - return owner; - } - - /** - * Set the requested Kerberos key. - * - * @param key the Kerberos key - */ - public void setKey(KerberosKey key) { - this.key = key; - } - - /** - * Get the requested Kerberos key. - * - * @return the Kerberos key - */ - public KerberosKey getKey() { - return key; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PasswordValidationCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PasswordValidationCallback.java deleted file mode 100644 index 86b77dd5871..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PasswordValidationCallback.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import javax.security.auth.callback.Callback; -import java.util.Arrays; - -/** - * Callback for PasswordValidation. - * - * @version %I%, %G% - */ -public class PasswordValidationCallback extends - jakarta.security.auth.message.callback.PasswordValidationCallback { - - /** - * Create a PasswordValidationCallback. - * - * @param username the username to authenticate - * - * @param password the user's password, which may be null. - */ - public PasswordValidationCallback(String username, char[] password) { - super(null, username, password); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PrivateKeyCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PrivateKeyCallback.java deleted file mode 100644 index bbb8c51756c..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/PrivateKeyCallback.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.math.BigInteger; -import java.security.PrivateKey; -import java.security.cert.Certificate; -import javax.security.auth.callback.Callback; -import javax.security.auth.x500.X500Principal; - -/** - * Callback for private key and corresponding certificate chain. - * - * @version %I%, %G% - */ -public class PrivateKeyCallback - extends jakarta.security.auth.message.callback.PrivateKeyCallback { - - /** - * Marker interface for private key request types. - */ - public static interface Request extends - jakarta.security.auth.message.callback.PrivateKeyCallback.Request { }; - - /** - * Request type for private keys that are identified via an alias. - */ - public static class AliasRequest extends - jakarta.security.auth.message.callback.PrivateKeyCallback.AliasRequest - implements Request { - - /** - * Construct an AliasRequest with an alias. - * - *

The alias is used to directly identify the private key - * to be returned. The corresponding certificate chain for the - * private key is also returned. - * - *

If the alias is null, - * the handler of the callback relies on its own default. - * - * @param alias name identifier for the private key, or null. - */ - public AliasRequest(String alias) { - super(alias); - } - } - - /** - * Request type for private keys that are identified via a SubjectKeyID - */ - public static class SubjectKeyIDRequest extends - jakarta.security.auth.message.callback.PrivateKeyCallback.SubjectKeyIDRequest - implements Request { - - /** - * Construct a SubjectKeyIDRequest with an subjectKeyID. - * - *

The subjectKeyID is used to directly identify the private key - * to be returned. The corresponding certificate chain for the - * private key is also returned. - * - *

If the subjectKeyID is null, - * the handler of the callback relies on its own default. - * - * @param subjectKeyID identifier for the private key, or null. - */ - public SubjectKeyIDRequest(byte[] subjectKeyID) { - super(subjectKeyID); - } - } - - /** - * Request type for private keys that are identified via an - * issuer/serial number. - */ - public static class IssuerSerialNumRequest extends - jakarta.security.auth.message.callback.PrivateKeyCallback.IssuerSerialNumRequest - implements Request { - - /** - * Constructs a IssuerSerialNumRequest with an issuer/serial number. - * - *

The issuer/serial number are used to identify a - * public key certificate. The corresponding private key - * is returned in the callback. The corresponding certificate chain - * for the private key is also returned. - * - * If the issuer/serialNumber parameters are null, - * the handler of the callback relies on its own defaults. - * - * @param issuer the X500Principal name of the certificate issuer, - * or null. - * - * @param serialNumber the serial number of the certificate, - * or null. - */ - public IssuerSerialNumRequest(X500Principal issuer, - BigInteger serialNumber) { - super(issuer, serialNumber); - } - } - - /** - * Constructs this PrivateKeyCallback with a private key Request object. - * - *

The request object identifies the private key - * to be returned. The corresponding certificate chain for the - * private key is also returned. - * - *

If the request object is null, - * the handler of the callback relies on its own default. - * - * @param request identifier for the private key, or null. - */ - public PrivateKeyCallback(Request request) { - super(request); - } - - /** - * Get the Request object which identifies the private key to be returned. - * - * @return the Request object which identifies the private key - * to be returned, or null. If null, the handler of the callback - * relies on its own default. - */ - public Request getRequest() { - return (Request)super.getRequest(); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SecretKeyCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SecretKeyCallback.java deleted file mode 100644 index b69af5715e7..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SecretKeyCallback.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.math.BigInteger; -import java.security.Principal; -import javax.crypto.SecretKey; -import javax.security.auth.callback.Callback; - -/** - * Callback for private key and corresponding certificate chain. - * - * @version %I%, %G% - */ -public class SecretKeyCallback - extends jakarta.security.auth.message.callback.SecretKeyCallback { - - /** - * Marker interface for private key request types. - */ - public static interface Request extends - jakarta.security.auth.message.callback.SecretKeyCallback.Request { }; - - /** - * Request type for secret keys that are identified via an alias. - */ - public static class AliasRequest extends - jakarta.security.auth.message.callback.SecretKeyCallback.AliasRequest - implements Request { - - /** - * Construct an AliasRequest with an alias. - * - *

The alias is used to directly identify the secret key - * to be returned. - * - *

If the alias is null, - * the handler of the callback relies on its own default. - * - * @param alias name identifier for the secret key, or null. - */ - public AliasRequest(String alias) { - super(alias); - } - } - - /** - * Constructs this SecretKeyCallback with a secret key Request object. - * - *

The request object identifies the secret key - * to be returned. - * - * If the alias is null, the handler of the callback - * relies on its own default. - * - * @param request request object identifying the secret key, or null. - */ - public SecretKeyCallback(Request request) { - super(request); - } - - /** - * Get the Request object which identifies the secret key to be returned. - * - * @return the Request object which identifies the private key - * to be returned, or null. If null, the handler of the callback - * relies on its own deafult. - */ - public Request getRequest() { - return (Request)super.getRequest(); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SignatureKeyCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SignatureKeyCallback.java deleted file mode 100644 index 01ec9bf8554..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/SignatureKeyCallback.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.security.KeyStore; -import java.security.PrivateKey; -import javax.crypto.SecretKey; -import java.security.cert.Certificate; -import javax.security.auth.callback.Callback; -import javax.security.auth.x500.X500Principal; - -/** - * Callback for Signing Key. - * - * @version 1.8, 03/03/04 - */ -public class SignatureKeyCallback implements Callback { - - private PrivateKey key; - private X500Principal authority; - private Certificate[] chain; - - /** - * Constructs this SignatureKeyCallback with an authority. - * - *

Both a PrivateKey and corresponding certificate chain - * will be returned. The authority input parameter - * specifies the X500Principal name of the root CA - * certificate returned in the chain. - * An authority does not have to be specified. - * - * @param authority the X500Principal name of the root CA - * certificate returned in the requested chain, - * or null - */ - public SignatureKeyCallback(X500Principal authority) { - this.authority = authority; - } - - /** - * Get the authority. - * - * @return the authority, or null - */ - public X500Principal getAuthority() { - return authority; - } - - /** - * Set the requested signing key. - * - * @param key the signing key - * @param chain the corresponding certificate chain - */ - public void setKey(PrivateKey key, Certificate[] chain) { - this.key = key; - this.chain = chain; - } - - /** - * Get the requested signing key. - * - * @return the signing key - */ - public PrivateKey getKey() { - return key; - } - - /** - * Get the certificate chain. - * - * @return the certificate chain - */ - public Certificate[] getChain() { - return chain; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/TrustStoreCallback.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/TrustStoreCallback.java deleted file mode 100644 index bc51540c0c6..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jauth/callback/TrustStoreCallback.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.enterprise.security.jauth.callback; - -import java.security.KeyStore; -import javax.security.auth.callback.Callback; - -/** - * Callback for trusted certificate KeyStore. - * - *

A trusted certificate KeyStore may be used to determine - * whether a given certificate chain can be trusted. - * - * @version %I%, %G% - */ -public class TrustStoreCallback - extends jakarta.security.auth.message.callback.TrustStoreCallback { - - /** - * Set the trusted certificate KeyStore. - * - * @param trustStore the trusted certificate KeyStore, - * which must already be loaded. - */ - public void setStore(KeyStore trustStore) { - setTrustStore(trustStore); - } -} diff --git a/appserver/security/core-ee/src/test/resources/com/sun/enterprise/security/permissionsxml/server.policy b/appserver/security/core-ee/src/test/resources/com/sun/enterprise/security/permissionsxml/server.policy index e66e53c943b..ef2e0a82fe0 100644 --- a/appserver/security/core-ee/src/test/resources/com/sun/enterprise/security/permissionsxml/server.policy +++ b/appserver/security/core-ee/src/test/resources/com/sun/enterprise/security/permissionsxml/server.policy @@ -118,7 +118,8 @@ grant { // Following needed for CTS to pass with SM on, bug 16344201 permission java.lang.RuntimePermission "closeClassLoader"; permission java.io.SerializablePermission "enableSubstitution"; - permission java.security.SecurityPermission "getProperty.package.definition"; + permission java.security.SecurityPermission "getProperty.package.definition"; + permission java.security.SecurityPermission "getProperty.authconfigprovider.factory.providers"; }; // Following grant block is only required by Connectors. If Connectors diff --git a/appserver/security/jaspic-provider-framework/auth.conf b/appserver/security/jaspic-provider-framework/auth.conf deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/appserver/security/jaspic-provider-framework/osgi.bundle b/appserver/security/jaspic-provider-framework/osgi.bundle deleted file mode 100644 index 46a378460ef..00000000000 --- a/appserver/security/jaspic-provider-framework/osgi.bundle +++ /dev/null @@ -1,48 +0,0 @@ -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. -# -# Copyright (c) 2010-2011 Oracle and/or its affiliates. All rights reserved. -# -# The contents of this file are subject to the terms of either the GNU -# General Public License Version 2 only ("GPL") or the Common Development -# and Distribution License("CDDL") (collectively, the "License"). You -# may not use this file except in compliance with the License. You can -# obtain a copy of the License at -# https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html -# or packager/legal/LICENSE.txt. See the License for the specific -# language governing permissions and limitations under the License. -# -# When distributing the software, include this License Header Notice in each -# file and include the License file at packager/legal/LICENSE.txt. -# -# GPL Classpath Exception: -# Oracle designates this particular file as subject to the "Classpath" -# exception as provided by Oracle in the GPL Version 2 section of the License -# file that accompanied this code. -# -# Modifications: -# If applicable, add the following below the License Header, with the fields -# enclosed by brackets [] replaced by your own identifying information: -# "Portions Copyright [year] [name of copyright owner]" -# -# Contributor(s): -# If you wish your version of this file to be governed by only the CDDL or -# only the GPL Version 2, indicate your decision by adding "[Contributor] -# elects to include this software in this distribution under the [CDDL or GPL -# Version 2] license." If you don't indicate a single choice of license, a -# recipient has the option to distribute your version of this file under -# either the CDDL, the GPL Version 2 or to extend the choice of license to -# its licensees as provided above. However, if you add GPL Version 2 code -# and therefore, elected the GPL Version 2 license, then the option applies -# only if the new code is made subject to such option by the copyright -# holder. -# -# Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] --exportcontents: \ - com.sun.jaspic.config.delegate; \ - com.sun.jaspic.config.factory; \ - com.sun.jaspic.config.jaas; \ - com.sun.jaspic.config.servlet; \ - com.sun.logging.enterprise.system.jaspic.security; \ - com.sun.jaspic.config.helper; version=${project.osgi.version} - diff --git a/appserver/security/jaspic-provider-framework/pom.xml b/appserver/security/jaspic-provider-framework/pom.xml deleted file mode 100644 index e923a2c6615..00000000000 --- a/appserver/security/jaspic-provider-framework/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - 4.0.0 - - - fish.payara.server.core - core-parent - 7.0.0.Alpha3-SNAPSHOT - ../../../core/core-parent - - - fish.payara.server.core.security - jaspic.provider.framework - glassfish-jar - - Jaspic Provider Framework - - JASPIC (JSR-196) Provider Framework Reference Implementation. - - This module contains a Payara/GlassFish independent partial reference implementation - of JASPIC. Due to the way JASPIC works this does not implement a full RI, as JASPIC - is not so much an independent library but an SPI for Servlet and SOAP container to call - out to external authentication mechanisms. - - Despite that, this module's goal is to implement as much JASPIC general reference functionality - without any server specific dependencies. - - - - - - jakarta.authentication - jakarta.authentication-api - - - jakarta.servlet - jakarta.servlet-api - - - org.glassfish.soteria - jakarta.security.enterprise - - - org.glassfish.epicyro - epicyro - - - diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/delegate/MessagePolicyDelegate.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/delegate/MessagePolicyDelegate.java deleted file mode 100644 index 245656b4e0f..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/delegate/MessagePolicyDelegate.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.jaspic.config.delegate; - -import java.util.Map; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; - -/** - * - * @author ronmonzillo - */ -public interface MessagePolicyDelegate { - - MessagePolicy getRequestPolicy(String authContextID, Map properties); - - MessagePolicy getResponsePolicy(String authContextID, Map properties); - - Class[] getMessageTypes(); - - String getAuthContextID(MessageInfo messageInfo); - - boolean isProtected(); -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultAuthConfigProvider.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultAuthConfigProvider.java deleted file mode 100644 index 2565cd4b8a7..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultAuthConfigProvider.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2015, 2020 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.jaspic.config.factory; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * This class functions as a kind of factory-factory for {@link ServerAuthConfig} instances, which are by themselves factories - * for {@link ServerAuthContext} instances, which are delegates for the actual {@link ServerAuthModule} (SAM) that we're after. - * - * @author Arjan Tijms - */ -public class DefaultAuthConfigProvider implements AuthConfigProvider { - - private static final String CALLBACK_HANDLER_PROPERTY_NAME = "authconfigprovider.client.callbackhandler"; - - private Map providerProperties; - private ServerAuthModule sam; - - public DefaultAuthConfigProvider(ServerAuthModule sam) { - this.sam = sam; - } - - /** - * Constructor with signature and implementation that's required by API. - * - * @param properties provider properties - * @param factory the auth config factory - */ - public DefaultAuthConfigProvider(Map properties, AuthConfigFactory factory) { - this.providerProperties = properties; - - // API requires self registration if factory is provided. Not clear - // where the "layer" (2nd parameter) - // and especially "appContext" (3rd parameter) values have to come from - // at this place. - if (factory != null) { - // If this method ever gets called, it may throw a SecurityException. - // Don't bother with a PrivilegedAction as we don't expect to ever be - // constructed this way. - factory.registerConfigProvider(this, null, null, "Auto registration"); - } - } - - /** - * The actual factory method that creates the factory used to eventually obtain the delegate for a SAM. - */ - @Override - public ServerAuthConfig getServerAuthConfig( - String layer, String appContext, CallbackHandler handler) - throws AuthException, SecurityException { - return new DefaultServerAuthConfig( - layer, appContext, - handler == null ? createDefaultCallbackHandler() : handler, - providerProperties, sam - ); - } - - @Override - public ClientAuthConfig getClientAuthConfig( - String layer, String appContext, CallbackHandler handler) - throws AuthException, SecurityException { - return null; - } - - @Override - public void refresh() { - } - - /** - * Creates a default callback handler via the system property - * "authconfigprovider.client.callbackhandler", as seemingly required by the - * API (API uses wording "may" create default handler). TODO: Isn't - * "authconfigprovider.client.callbackhandler" JBoss specific? - * - * @return - * @throws AuthException - */ - private CallbackHandler createDefaultCallbackHandler() throws AuthException { - String callBackClassName = System.getProperty(CALLBACK_HANDLER_PROPERTY_NAME); - - if (callBackClassName == null) { - throw new AuthException("No default handler set via system property: " + CALLBACK_HANDLER_PROPERTY_NAME); - } - - try { - return (CallbackHandler) Thread.currentThread().getContextClassLoader().loadClass(callBackClassName).newInstance(); - } catch (Exception e) { - throw new AuthException(e.getMessage()); - } - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthConfig.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthConfig.java deleted file mode 100644 index a3b0cda4459..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthConfig.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2015, 2020 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.jaspic.config.factory; - -import java.util.Map; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * This class functions as a kind of factory for {@link ServerAuthContext} instances, which are delegates for the actual - * {@link ServerAuthModule} (SAM) that we're after. - * - * @author Arjan Tijms - */ -public class DefaultServerAuthConfig implements ServerAuthConfig { - - private String layer; - private String appContext; - private CallbackHandler handler; - private Map providerProperties; - private ServerAuthModule serverAuthModule; - - public DefaultServerAuthConfig(String layer, String appContext, CallbackHandler handler, - Map providerProperties, ServerAuthModule serverAuthModule) { - this.layer = layer; - this.appContext = appContext; - this.handler = handler; - this.providerProperties = providerProperties; - this.serverAuthModule = serverAuthModule; - } - - @Override - public ServerAuthContext getAuthContext(String authContextID, Subject serviceSubject, - @SuppressWarnings("rawtypes") Map properties) throws AuthException { - return new DefaultServerAuthContext(handler, serverAuthModule); - } - - // ### The methods below mostly just return what has been passed into the - // constructor. - // ### In practice they don't seem to be called - - @Override - public String getMessageLayer() { - return layer; - } - - /** - * It's not entirely clear what the difference is between the "application context identifier" (appContext) and the - * "authentication context identifier" (authContext). In early iterations of the specification, authContext was called - * "operation" and instead of the MessageInfo it was obtained by something called an "authParam". - */ - @Override - public String getAuthContextID(MessageInfo messageInfo) { - return appContext; - } - - @Override - public String getAppContext() { - return appContext; - } - - @Override - public void refresh() { - } - - @Override - public boolean isProtected() { - return false; - } - - public Map getProviderProperties() { - return providerProperties; - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthContext.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthContext.java deleted file mode 100644 index 3c15f6ba4ee..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/DefaultServerAuthContext.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2015, 2020 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package com.sun.jaspic.config.factory; - -import java.util.Collections; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.ServerAuth; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * The Server Authentication Context is an extra (required) indirection between the Application Server and the actual Server - * Authentication Module (SAM). This can be used to encapsulate any number of SAMs and either select one at run-time, invoke - * them all in order, etc. - *

- * Since this simple example only has a single SAM, we delegate directly to that one. Note that this {@link ServerAuthContext} - * and the {@link ServerAuthModule} (SAM) share a common base interface: {@link ServerAuth}. - * - * @author Arjan Tijms - */ -public class DefaultServerAuthContext implements ServerAuthContext { - - private final ServerAuthModule sam; - - public DefaultServerAuthContext(CallbackHandler handler, ServerAuthModule sam) throws AuthException { - this.sam = sam; - this.sam.initialize(null, null, handler, Collections.emptyMap()); - } - - @Override - public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) - throws AuthException { - return sam.validateRequest(messageInfo, clientSubject, serviceSubject); - } - - @Override - public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException { - return sam.secureResponse(messageInfo, serviceSubject); - } - - @Override - public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { - sam.cleanSubject(messageInfo, subject); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/EntryInfo.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/EntryInfo.java deleted file mode 100644 index 488e79b2355..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/EntryInfo.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; - -/** - * Each entry is either a constructor entry or a registration entry. Use nulls rather than empty Strings or Lists for - * fields that have no value. - * - * This class will not be used outside of its package. - * - * @author Bobby Bissett - */ -public final class EntryInfo { - - private final String className; - private final Map properties; - - private List registrationContexts; - - /* - * This will create a constructor entry. The className must not be null. ONLY CONSTRUCTOR that should be used used to - * construct defaultEntries (passed RegStoreFileParser construction). DO NOT USE OTHER CONSTRUCTORS to define - * defaultEntries because they can create persisted registration entries which are not appropriate as defaultEntries. - */ - public EntryInfo(String className) { - this(className, null); - } - - /* - * This will create a constructor entry. The className must not be null. ONLY OTHER CONSTRUCTOR that should be used used - * to construct defaultEntries (passed RegStoreFileParser construction). DO NOT USE OTHER CONSTRUCTORS to define - * defaultEntries because they can create persisted registration entries which are not appropriate as defaultEntries. - */ - public EntryInfo(String className, Map properties) { - if (className == null) { - throw new IllegalArgumentException("Class name for registration entry cannot be null"); - } - - this.className = className; - this.properties = properties; - } - - /* - * This will create a registration entry. The list of registration contexts must not be null or empty. Each registration - * context will contain at least a non-null layer or appContextId. - */ - EntryInfo(String className, Map properties, List ctxs) { - if (ctxs == null || ctxs.isEmpty()) { - throw new IllegalArgumentException("Registration entry must contain one or more registration contexts"); - } - - this.className = className; - this.properties = properties; - this.registrationContexts = ctxs; - } - - /* - * THIS METHOD MAY BE USED FOR CONSTRUCTOR OR REGISTRATION ENTRIES A helper method for creating a registration entry - * with one registration context. If the context is null, this entry is a constructor entry. - */ - EntryInfo(String className, Map properties, RegistrationContext registrationContext) { - this.className = className; - this.properties = properties; - - if (registrationContext != null) { - - RegistrationContext ctxImpl = new RegistrationContextImpl( - registrationContext.getMessageLayer(), - registrationContext.getAppContext(), - registrationContext.getDescription(), - registrationContext.isPersistent()); - - List newList = new ArrayList(1); - newList.add(ctxImpl); - this.registrationContexts = newList; - } - } - - EntryInfo(EntryInfo parent) { - this.className = parent.className; - this.properties = parent.properties; - - if (parent.registrationContexts != null) { - this.registrationContexts = new ArrayList(1); - - for (RegistrationContext registrationContext : parent.registrationContexts) { - this.registrationContexts.add(registrationContext); - } - } - } - - boolean isConstructorEntry() { - return registrationContexts == null; - } - - String getClassName() { - return className; - } - - Map getProperties() { - return properties; - } - - List getRegistrationContexts() { - return registrationContexts; - } - - /* - * Compares an entry info to this one. They are considered to match if: - they are both constructor or are both - * registration entries - the classnames are equal or are both null - the property maps are equal or are both null If - * the entry is a registration entry, registration contexts are not considered for our purposes. For instance, we may - * want to get a certain registration entry in order to add a registration context to it. - * @see com.sun.enterprise.security.jaspic.config.RegStoreFileParser - */ - boolean matchConstructors(EntryInfo target) { - if (target == null) { - return false; - } - - return (!(isConstructorEntry() ^ target.isConstructorEntry()) && matchStrings(className, target.getClassName()) - && matchMaps(properties, target.getProperties())); - } - - /* - * Utility method for comparing strings such that two null strings are considered "equal." - */ - static boolean matchStrings(String s1, String s2) { - if (s1 == null && s2 == null) { - return true; - } - - if (s1 == null || s2 == null) { - return false; - } - - return s1.equals(s2); - } - - /* - * Utility method for comparing maps such that two null maps are considered "equal." - */ - static boolean matchMaps(Map map1, Map map2) { - if (map1 == null && map2 == null) { - return true; - } - - if (map1 == null || map2 == null) { - return false; - } - - return map1.equals(map2); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegistrationContextImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegistrationContextImpl.java deleted file mode 100644 index 4d18a59e3cf..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/factory/RegistrationContextImpl.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.factory; - -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; - -/** - * Class used by {@link BaseAuthConfigFactory}, {@link EntryInfo} and {@link RegStoreFileParser} - * - * This class will *not* be used outside of its package. - */ -final class RegistrationContextImpl implements RegistrationContext { - - private final String messageLayer; - private final String appContext; - private final String description; - private final boolean isPersistent; - - RegistrationContextImpl(String messageLayer, String appContext, String description, boolean persistent) { - this.messageLayer = messageLayer; - this.appContext = appContext; - this.description = description; - this.isPersistent = persistent; - } - - // helper method to create impl class - RegistrationContextImpl(RegistrationContext registrationContext) { - this.messageLayer = registrationContext.getMessageLayer(); - this.appContext = registrationContext.getAppContext(); - this.description = registrationContext.getDescription(); - this.isPersistent = registrationContext.isPersistent(); - } - - @Override - public String getMessageLayer() { - return messageLayer; - } - - @Override - public String getAppContext() { - return appContext; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public boolean isPersistent() { - return isPersistent; - } - - @Override - public boolean equals(Object o) { - if (o == null || !(o instanceof RegistrationContext)) { - return false; - } - - RegistrationContext target = (RegistrationContext) o; - - return (EntryInfo.matchStrings(messageLayer, target.getMessageLayer()) && - EntryInfo.matchStrings(appContext, target.getAppContext()) && - isPersistent() == target.isPersistent()); - } - - @Override - public int hashCode() { - int hash = 7; - hash = 17 * hash + (this.messageLayer != null ? this.messageLayer.hashCode() : 0); - hash = 17 * hash + (this.appContext != null ? this.appContext.hashCode() : 0); - hash = 17 * hash + (this.isPersistent ? 1 : 0); - - return hash; - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigImpl.java deleted file mode 100644 index b1161a96d9f..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigImpl.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.helper; - -import static java.util.logging.Level.FINE; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; - -/** - * Base class for the {@link ClientAuthConfigImpl} and {@link ServerAuthConfigImpl}. - * - * @author Ron Monzillo - */ -public abstract class BaseAuthConfigImpl { - - String loggerName; - EpochCarrier providerEpoch; - long epoch; - MessagePolicyDelegate policyDelegate; - String layer; - String appContext; - CallbackHandler callbackHandler; - - private ReentrantReadWriteLock instanceReadWriteLock = new ReentrantReadWriteLock(); - private Lock instanceReadLock = instanceReadWriteLock.readLock(); - private Lock instanceWriteLock = instanceReadWriteLock.writeLock(); - - public BaseAuthConfigImpl(String loggerName, EpochCarrier providerEpoch, MessagePolicyDelegate mpDelegate, String layer, - String appContext, CallbackHandler cbh) throws AuthException { - this.loggerName = loggerName; - this.providerEpoch = providerEpoch; - this.policyDelegate = mpDelegate; - this.layer = layer; - this.appContext = appContext; - this.callbackHandler = cbh; - - initialize(); - } - - public String getMessageLayer() { - return layer; - } - - public String getAppContext() { - return appContext; - } - - public String getAuthContextID(MessageInfo messageInfo) { - return policyDelegate.getAuthContextID(messageInfo); - } - - public void refresh() { - try { - initialize(); - } catch (AuthException ae) { - throw new RuntimeException(ae); - } - } - - private void initialize() throws AuthException { - instanceWriteLock.lock(); - try { - this.epoch = providerEpoch.getEpoch(); - initializeContextMap(); - } finally { - instanceWriteLock.unlock(); - } - } - - private void doRefreshIfNeeded() { - boolean hasChanged = false; - instanceReadLock.lock(); - try { - hasChanged = providerEpoch.hasChanged(epoch); - } finally { - instanceReadLock.unlock(); - } - - if (hasChanged) { - refresh(); - } - } - - private Integer getHashCode(Map properties) { - if (properties == null) { - return Integer.valueOf("0"); - } - - return Integer.valueOf(properties.hashCode()); - } - - private M getContextFromMap(Map> contextMap, String authContextID, Map properties) { - M context = null; - - Map internalMap = contextMap.get(authContextID); - if (internalMap != null) { - context = internalMap.get(getHashCode(properties)); - } - - if (context != null) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "AuthContextID found in Map: ", authContextID); - } - } - - return context; - } - - @SuppressWarnings("unchecked") - protected final M getContext(Map> contextMap, String authContextID, Subject subject, - Map properties) - throws AuthException { - - M context = null; - - doRefreshIfNeeded(); - - instanceReadLock.lock(); - try { - context = getContextFromMap(contextMap, authContextID, properties); - if (context != null) { - return context; - } - } finally { - instanceReadLock.unlock(); - } - - instanceWriteLock.lock(); - try { - context = getContextFromMap(contextMap, authContextID, properties); - if (context == null) { - - context = (M) createAuthContext(authContextID, properties); - - Map internalMap = contextMap.get(authContextID); - if (internalMap == null) { - internalMap = new HashMap(); - contextMap.put(authContextID, internalMap); - } - - internalMap.put(getHashCode(properties), context); - } - return context; - } finally { - instanceWriteLock.unlock(); - } - } - - protected boolean isLoggable(Level level) { - return Logger.getLogger(loggerName).isLoggable(level); - } - - protected void logIfLevel(Level level, Throwable t, String... msgParts) { - Logger logger = Logger.getLogger(loggerName); - - if (logger.isLoggable(level)) { - StringBuilder messageBuffer = new StringBuilder(""); - - for (String m : msgParts) { - messageBuffer.append(m); - } - - String msg = messageBuffer.toString(); - - if (!msg.isEmpty() && t != null) { - logger.log(level, msg, t); - } else if (!msg.isEmpty()) { - logger.log(level, msg); - } - } - } - - protected void checkMessageTypes(Class[] supportedMessageTypes) throws AuthException { - Class[] requiredMessageTypes = policyDelegate.getMessageTypes(); - for (Class requiredType : requiredMessageTypes) { - boolean supported = false; - for (Class supportedType : supportedMessageTypes) { - if (requiredType.isAssignableFrom(supportedType)) { - supported = true; - } - } - - if (!supported) { - throw new AuthException("module does not support message type: " + requiredType.getName()); - } - } - } - - /** - * Only called from initialize (while lock is held). - */ - protected abstract void initializeContextMap(); - - protected abstract M createAuthContext(String authContextID, Map properties) throws AuthException; -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigProvider.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigProvider.java deleted file mode 100644 index 9f889d8823f..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthConfigProvider.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.helper; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; -import java.util.HashSet; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.module.ClientAuthModule; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * - * @author Ron Monzillo - */ -public abstract class BaseAuthConfigProvider implements AuthConfigProvider { - - public static final String LAYER_NAME_KEY = "message.layer"; - public static final String ALL_LAYERS = "*"; - public static final String LOGGER_NAME_KEY = "logger.name"; - public static final String AUTH_MODULE_KEY = "auth.module.type"; - public static final String SERVER_AUTH_MODULE = "server.auth.module"; - public static final String CLIENT_AUTH_MODULE = "client.auth.module"; - - private ReentrantReadWriteLock instanceReadWriteLock = new ReentrantReadWriteLock(); - private Lock writeLock = instanceReadWriteLock.writeLock(); - private HashSet selfRegistered = new HashSet<>(); - private EpochCarrier epochCarrier = new EpochCarrier(); - - @Override - public ClientAuthConfig getClientAuthConfig(String layer, String appContext, CallbackHandler callbackHandler) throws AuthException { - return new ClientAuthConfigImpl( - getLoggerName(), - epochCarrier, - getAuthContextHelper(appContext, true), - getMessagePolicyDelegate(appContext), - layer, - appContext, - getClientCallbackHandler(callbackHandler)); - } - - @Override - public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler callbackHandler) throws AuthException { - return new ServerAuthConfigImpl( - getLoggerName(), - epochCarrier, - getAuthContextHelper(appContext, true), - getMessagePolicyDelegate(appContext), - layer, - appContext, - getServerCallbackHandler(callbackHandler)); - } - - public boolean contextsAreEqual(RegistrationContext context1, RegistrationContext context2) { - if (context1 == null || context2 == null) { - return false; - } - - if (context1.isPersistent() != context2.isPersistent()) { - return false; - } - - if (!context1.getAppContext().equals(context2.getAppContext())) { - return false; - } - - if (!context1.getMessageLayer().equals(context2.getMessageLayer())) { - return false; - } - - if (!context1.getDescription().equals(context2.getDescription())) { - return false; - } - - return true; - } - - @Override - public void refresh() { - epochCarrier.increment(); - selfRegister(); - } - - public String getLoggerName() { - return getProperty(LOGGER_NAME_KEY, BaseAuthConfigProvider.class.getName()); - } - - protected final String getProperty(String key, String defaultValue) { - Map properties = getProperties(); - if (properties != null && properties.containsKey(key)) { - return (String) properties.get(key); - } - - return defaultValue; - } - - protected String getLayer() { - return getProperty(LAYER_NAME_KEY, ALL_LAYERS); - } - - protected Class[] getModuleTypes() { - Class[] moduleTypes = new Class[] { ServerAuthModule.class, ClientAuthModule.class }; - - Map properties = getProperties(); - if (properties.containsKey(AUTH_MODULE_KEY)) { - String keyValue = (String) properties.get(AUTH_MODULE_KEY); - - if (SERVER_AUTH_MODULE.equals(keyValue)) { - moduleTypes = new Class[] { ServerAuthModule.class }; - } else if (CLIENT_AUTH_MODULE.equals(keyValue)) { - moduleTypes = new Class[] { ClientAuthModule.class }; - } - } - - return moduleTypes; - } - - protected void selfRegister() { - if (getFactory() != null) { - writeLock.lock(); - try { - RegistrationContext[] contexts = getSelfRegistrationContexts(); - if (!selfRegistered.isEmpty()) { - HashSet toBeUnregistered = new HashSet(); - - // Get the current self-registrations - String[] registrationIDs = getFactory().getRegistrationIDs(this); - - for (String registrationId : registrationIDs) { - if (selfRegistered.contains(registrationId)) { - RegistrationContext context = getFactory().getRegistrationContext(registrationId); - if (context != null && !context.isPersistent()) { - toBeUnregistered.add(registrationId); - } - } - } - - // Remove self-registrations that already exist and should continue - for (String registrationId : toBeUnregistered) { - RegistrationContext context = getFactory().getRegistrationContext(registrationId); - for (int j = 0; j < contexts.length; j++) { - if (contextsAreEqual(contexts[j], context)) { - toBeUnregistered.remove(registrationId); - contexts[j] = null; - } - } - } - - // Unregister those that should not continue to exist - for (String registrationId : toBeUnregistered) { - selfRegistered.remove(registrationId); - getFactory().removeRegistration(registrationId); - } - } - - // Add new self-segistrations - for (RegistrationContext context : contexts) { - if (context != null) { - String id = getFactory().registerConfigProvider(this, context.getMessageLayer(), context.getAppContext(), - context.getDescription()); - selfRegistered.add(id); - } - } - } finally { - writeLock.unlock(); - } - - } - } - - protected CallbackHandler getClientCallbackHandler(CallbackHandler callbackHandler) throws AuthException { - if (callbackHandler == null) { - throw (AuthException) new AuthException("AuthConfigProvider does not support null Client Callbackhandler") - .initCause(new UnsupportedOperationException()); - } - - return callbackHandler; - } - - protected CallbackHandler getServerCallbackHandler(CallbackHandler callbackHandler) throws AuthException { - if (callbackHandler == null) { - throw (AuthException) new AuthException("AuthConfigProvider does not support null Server Callbackhandler") - .initCause(new UnsupportedOperationException()); - } - - return callbackHandler; - } - - public abstract Map getProperties(); - - public abstract AuthConfigFactory getFactory(); - - public abstract RegistrationContext[] getSelfRegistrationContexts(); - - public abstract BaseAuthContextImpl getAuthContextHelper(String appContext, boolean returnNullContexts) throws AuthException; - - public abstract MessagePolicyDelegate getMessagePolicyDelegate(String appContext) throws AuthException; - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthContextImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthContextImpl.java deleted file mode 100644 index 141cfc77a0e..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/BaseAuthContextImpl.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2021] Payara Foundation and/or affiliates - -package com.sun.jaspic.config.helper; - -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * - * @author Ron Monzillo - */ -public abstract class BaseAuthContextImpl { - - private String loggerName; - private boolean returnNullContexts; - - // Include this to force subclasses to call constructor with LoggerName - @SuppressWarnings("unused") - private BaseAuthContextImpl() { - - } - - protected BaseAuthContextImpl(String loggerName, boolean returnNullContexts) { - this.loggerName = loggerName; - this.returnNullContexts = returnNullContexts; - } - - protected boolean isLoggable(Level level) { - Logger logger = Logger.getLogger(loggerName); - return logger.isLoggable(level); - } - - protected void logIfLevel(Level level, Throwable t, String... msgParts) { - Logger logger = Logger.getLogger(loggerName); - if (logger.isLoggable(level)) { - StringBuilder msgB = new StringBuilder(""); - for (String m : msgParts) { - msgB.append(m); - } - String msg = msgB.toString(); - if (!msg.isEmpty() && t != null) { - logger.log(level, msg, t); - } else if (!msg.isEmpty()) { - logger.log(level, msg); - } - } - } - - /** - * - * @param level - * @return - */ - protected Logger getLogger(Level level) { - Logger rvalue = Logger.getLogger(loggerName); - if (rvalue.isLoggable(level)) { - return rvalue; - } - return null; - } - - protected abstract void refresh(); - - public boolean returnsNullContexts() { - return returnNullContexts; - } - - public boolean isProtected(M[] template, String authContextID) throws AuthException { - try { - if (returnNullContexts) { - return hasModules(template, authContextID); - } else { - return true; - } - } catch (AuthException ae) { - throw new RuntimeException(ae); - } - } - - /** - * - * @param - * @param template - * @param authContextID - * @return - * @throws AuthException - */ - public abstract boolean hasModules(M[] template, String authContextID) throws AuthException; - - /** - * - * @param - * @param template - * @param authContextID - * @return - * @throws AuthException - */ - public abstract M[] getModules(M[] template, String authContextID) throws AuthException; - - /** - * - * @param i - * @param properties - * @return - */ - public abstract Map getInitProperties(int i, Map properties); - - /** - * - * @param successValue - * @param i - * @param moduleStatus - * @return - */ - public abstract boolean exitContext(AuthStatus[] successValue, int i, AuthStatus moduleStatus); - - /** - * - * @param successValue - * @param defaultFailStatus - * @param status - * @param position - * @return - */ - public abstract AuthStatus getReturnStatus(AuthStatus[] successValue, AuthStatus defaultFailStatus, AuthStatus[] status, int position); -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ClientAuthConfigImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ClientAuthConfigImpl.java deleted file mode 100644 index 73642fde19e..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ClientAuthConfigImpl.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.helper; - -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; -import static jakarta.security.auth.message.AuthStatus.SEND_FAILURE; -import static jakarta.security.auth.message.AuthStatus.SEND_SUCCESS; -import static jakarta.security.auth.message.AuthStatus.SUCCESS; - -import java.util.HashMap; -import java.util.Map; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.module.ClientAuthModule; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; - -/** - * - * @author Ron Monzillo - */ -public class ClientAuthConfigImpl extends BaseAuthConfigImpl implements ClientAuthConfig { - - private final static AuthStatus[] validateResponseSuccessValues = { SUCCESS }; - private final static AuthStatus[] secureResponseSuccessValues = { SEND_SUCCESS }; - - private Map> contextMap; - private BaseAuthContextImpl authContextHelper; - - protected ClientAuthConfigImpl(String loggerName, EpochCarrier providerEpoch, BaseAuthContextImpl acHelper, - MessagePolicyDelegate mpDelegate, String layer, String appContext, CallbackHandler cbh) throws AuthException { - super(loggerName, providerEpoch, mpDelegate, layer, appContext, cbh); - - this.authContextHelper = acHelper; - } - - @Override - protected void initializeContextMap() { - contextMap = new HashMap<>(); - } - - protected void refreshContextHelper() { - authContextHelper.refresh(); - } - - @Override - @SuppressWarnings("unchecked") - protected M createAuthContext(String authContextID, Map properties) throws AuthException { - - if (!authContextHelper.isProtected(new ClientAuthModule[0], authContextID)) { - return null; - } - - ClientAuthContext context = new ClientAuthContext() { - - ClientAuthModule[] module = init(); - - ClientAuthModule[] init() throws AuthException { - - ClientAuthModule[] clientModules; - try { - clientModules = authContextHelper.getModules(new ClientAuthModule[0], authContextID); - } catch (AuthException ae) { - logIfLevel(SEVERE, ae, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "unable to load client auth modules"); - throw ae; - } - - MessagePolicy requestPolicy = policyDelegate.getRequestPolicy(authContextID, properties); - MessagePolicy responsePolicy = policyDelegate.getResponsePolicy(authContextID, properties); - - boolean noModules = true; - for (int i = 0; i < clientModules.length; i++) { - if (clientModules[i] != null) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "initializing module"); - } - - noModules = false; - checkMessageTypes(clientModules[i].getSupportedMessageTypes()); - - clientModules[i].initialize(requestPolicy, responsePolicy, callbackHandler, - authContextHelper.getInitProperties(i, properties)); - } - } - - if (noModules) { - logIfLevel(WARNING, null, "CLientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "contains no Auth Modules"); - } - - return clientModules; - } - - @Override - public AuthStatus validateResponse(MessageInfo arg0, Subject arg1, Subject arg2) throws AuthException { - AuthStatus[] status = new AuthStatus[module.length]; - - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling vaidateResponse on module"); - } - - status[i] = module[i].validateResponse(arg0, arg1, arg2); - - if (authContextHelper.exitContext(validateResponseSuccessValues, i, status[i])) { - return authContextHelper.getReturnStatus(validateResponseSuccessValues, SEND_FAILURE, status, i); - } - } - - return authContextHelper.getReturnStatus(validateResponseSuccessValues, SEND_FAILURE, status, status.length - 1); - } - - @Override - public AuthStatus secureRequest(MessageInfo arg0, Subject arg1) throws AuthException { - AuthStatus[] status = new AuthStatus[module.length]; - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling secureResponse on module"); - } - - status[i] = module[i].secureRequest(arg0, arg1); - - if (authContextHelper.exitContext(secureResponseSuccessValues, i, status[i])) { - return authContextHelper.getReturnStatus(secureResponseSuccessValues, AuthStatus.SEND_FAILURE, status, i); - } - } - return authContextHelper.getReturnStatus(secureResponseSuccessValues, AuthStatus.SEND_FAILURE, status, status.length - 1); - } - - @Override - public void cleanSubject(MessageInfo arg0, Subject arg1) throws AuthException { - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ClientAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling cleanSubject on module"); - } - - module[i].cleanSubject(arg0, arg1); - } - } - }; - - return (M) context; - } - - @Override - @SuppressWarnings("unchecked") - public ClientAuthContext getAuthContext(String authContextID, Subject subject, @SuppressWarnings("rawtypes") Map properties) - throws AuthException { - return super.getContext(contextMap, authContextID, subject, properties); - } - - @Override - public boolean isProtected() { - return !authContextHelper.returnsNullContexts() || policyDelegate.isProtected(); - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/EpochCarrier.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/EpochCarrier.java deleted file mode 100644 index 5c2d26c0d32..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/EpochCarrier.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.jaspic.config.helper; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * - * @author Ron Monzillo - */ - -public class EpochCarrier { - - private Lock instanceReadLock; - private Lock instanceWriteLock; - - private long epoch; - - public EpochCarrier() { - ReentrantReadWriteLock instanceReadWriteLock = new ReentrantReadWriteLock(); - instanceReadLock = instanceReadWriteLock.readLock(); - instanceWriteLock = instanceReadWriteLock.writeLock(); - epoch = 0L; - } - - public long increment() { - instanceWriteLock.lock(); - long before; - try { - before = epoch; - epoch = epoch + 1; - } finally { - instanceWriteLock.unlock(); - } - return before; - } - - public long getEpoch() { - instanceReadLock.lock(); - try { - return epoch; - } finally { - instanceReadLock.unlock(); - } - } - - public boolean hasChanged(long reference) { - instanceReadLock.lock(); - try { - return epoch != reference; - } finally { - instanceReadLock.unlock(); - } - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/JASPICLogManager.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/JASPICLogManager.java deleted file mode 100644 index 579a66a9223..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/JASPICLogManager.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.jaspic.config.helper; - -public class JASPICLogManager { - - /** - * PACKAGE_ROOT the prefix for the packages where logger resource bundles reside. - */ - public static final String PACKAGE_ROOT = "com.sun.logging."; - - /** - * RESOURCE_BUNDLE the name of the logging resource bundles. - */ - public static final String RESOURCE_BUNDLE = "LogStrings"; - - public static final String JASPIC_LOGGER = "enterprise.system.jaspic.security"; - - public static final String RES_BUNDLE = PACKAGE_ROOT + JASPIC_LOGGER + "." + RESOURCE_BUNDLE; -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ServerAuthConfigImpl.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ServerAuthConfigImpl.java deleted file mode 100644 index e21a55aeab2..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/helper/ServerAuthConfigImpl.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.helper; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; - -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; -import static jakarta.security.auth.message.AuthStatus.SEND_FAILURE; -import static jakarta.security.auth.message.AuthStatus.SEND_SUCCESS; -import static jakarta.security.auth.message.AuthStatus.SUCCESS; - -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.security.auth.message.module.ServerAuthModule; - -/** - * - * @author Ron Monzillo - */ -public class ServerAuthConfigImpl extends BaseAuthConfigImpl implements ServerAuthConfig { - - private final static AuthStatus[] validateRequestSuccessValues = { SUCCESS, SEND_SUCCESS }; - private final static AuthStatus[] secureResponseSuccessValues = { SEND_SUCCESS }; - - private Map> contextMap; - private BaseAuthContextImpl authContextHelperHelper; - - protected ServerAuthConfigImpl(String loggerName, EpochCarrier providerEpoch, BaseAuthContextImpl authContextHelper, - MessagePolicyDelegate policyDelegate, String layer, String appContext, CallbackHandler cbh) throws AuthException { - - super(loggerName, providerEpoch, policyDelegate, layer, appContext, cbh); - - this.authContextHelperHelper = authContextHelper; - this.policyDelegate = policyDelegate; - } - - @Override - protected void initializeContextMap() { - contextMap = new HashMap<>(); - } - - @Override - @SuppressWarnings("unchecked") - protected M createAuthContext(String authContextID, Map properties) throws AuthException { - - if (!authContextHelperHelper.isProtected(new ServerAuthModule[0], authContextID)) { - return null; - } - - // Need to coordinate calls to CallerPrincipalCallback; especially optional - // modules that might reset the result of a required module - return (M) new ServerAuthContext() { - - ServerAuthModule[] module = init(); - - ServerAuthModule[] init() throws AuthException { - ServerAuthModule[] serverAuthModules; - - try { - serverAuthModules = authContextHelperHelper.getModules(new ServerAuthModule[0], authContextID); - } catch (AuthException ae) { - logIfLevel(SEVERE, ae, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "unable to load server auth modules"); - throw ae; - } - - MessagePolicy requestPolicy = policyDelegate.getRequestPolicy(authContextID, properties); - MessagePolicy responsePolicy = policyDelegate.getResponsePolicy(authContextID, properties); - - boolean noModules = true; - for (int i = 0; i < serverAuthModules.length; i++) { - if (serverAuthModules[i] != null) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "initializing module"); - } - noModules = false; - checkMessageTypes(serverAuthModules[i].getSupportedMessageTypes()); - - serverAuthModules[i].initialize( - requestPolicy, responsePolicy, - callbackHandler, authContextHelperHelper.getInitProperties(i, properties)); - } - } - - if (noModules) { - logIfLevel(WARNING, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "contains no Auth Modules"); - } - - return serverAuthModules; - } - - @Override - public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { - AuthStatus[] status = new AuthStatus[module.length]; - - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling vaidateRequest on module"); - } - - status[i] = module[i].validateRequest(messageInfo, clientSubject, serviceSubject); - - if (authContextHelperHelper.exitContext(validateRequestSuccessValues, i, status[i])) { - return authContextHelperHelper.getReturnStatus(validateRequestSuccessValues, SEND_FAILURE, status, i); - } - } - - return authContextHelperHelper.getReturnStatus(validateRequestSuccessValues, SEND_FAILURE, status, status.length - 1); - } - - @Override - public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException { - AuthStatus[] status = new AuthStatus[module.length]; - - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling secureResponse on module"); - } - - status[i] = module[i].secureResponse(messageInfo, serviceSubject); - - if (authContextHelperHelper.exitContext(secureResponseSuccessValues, i, status[i])) { - return authContextHelperHelper.getReturnStatus(secureResponseSuccessValues, SEND_FAILURE, status, i); - } - } - - return authContextHelperHelper.getReturnStatus(secureResponseSuccessValues, SEND_FAILURE, status, status.length - 1); - } - - @Override - public void cleanSubject(MessageInfo arg0, Subject arg1) throws AuthException { - for (int i = 0; i < module.length; i++) { - if (module[i] == null) { - continue; - } - - if (isLoggable(Level.FINE)) { - logIfLevel(Level.FINE, null, "ServerAuthContext: ", authContextID, "of AppContext: ", getAppContext(), - "calling cleanSubject on module"); - } - - module[i].cleanSubject(arg0, arg1); - } - } - }; - } - - @Override - @SuppressWarnings("unchecked") - public ServerAuthContext getAuthContext(String authContextID, Subject subject, @SuppressWarnings("rawtypes") Map properties) - throws AuthException { - return super.getContext(contextMap, authContextID, subject, properties); - } - - @Override - public boolean isProtected() { - return !authContextHelperHelper.returnsNullContexts() || policyDelegate.isProtected(); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/ExtendedConfigFile.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/ExtendedConfigFile.java deleted file mode 100644 index d3370ce17da..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/ExtendedConfigFile.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.jaas; - -import static com.sun.jaspic.config.helper.JASPICLogManager.JASPIC_LOGGER; -import static com.sun.jaspic.config.helper.JASPICLogManager.RES_BUNDLE; - -import java.lang.reflect.Field; -import java.net.URI; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.HashMap; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.security.auth.login.AppConfigurationEntry; - -import com.sun.security.auth.login.ConfigFile; - -/** - * - * @author Ron Monzillo - */ -public class ExtendedConfigFile extends ConfigFile { - - private static final Logger logger = Logger.getLogger(JASPIC_LOGGER, RES_BUNDLE); - // may be more than one delegate for a given jaas config file - - public ExtendedConfigFile() { - } - - /** - * - * @param uri - */ - public ExtendedConfigFile(URI uri) { - super(uri); - } - - /** - * The ExtendedConfigFile subclass was created because the Configuration interface does not provide a way to do what - * this method does; i.e. get all the app names from the config. - * - * @param authModuleClass an Array of Class objects or null. When this parameter is not null, the appnames are filtered - * by removing all names that are not associated via an AppConfigurationEntry with at least one LoginModule that - * implements an authModuleClass. - * @return String[] containing all the AppNames appearing in the config file. - * @throws SecurityException - */ - public String[] getAppNames(final Class[] authModuleClass) { - - final Set nameSet; - try { - nameSet = (Set) AccessController.doPrivileged(new PrivilegedExceptionAction() { - - @Override - public Object run() throws Exception { - HashMap map; - Field field = ConfigFile.class.getDeclaredField("configuration"); - field.setAccessible(true); - map = (HashMap) field.get(ExtendedConfigFile.this); - return map.keySet(); - } - }); - - } catch (PrivilegedActionException pae) { - throw new SecurityException(pae.getCause()); - } - - // remove any modules that don't implement specified interface - if (authModuleClass != null) { - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - - @Override - public Object run() throws Exception { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - String[] names = nameSet.toArray(new String[nameSet.size()]); - for (String id : names) { - boolean hasAuthModule = false; - AppConfigurationEntry[] entry = getAppConfigurationEntry(id); - for (int i = 0; i < entry.length && !hasAuthModule; i++) { - String clazz = entry[i].getLoginModuleName(); - try { - Class c = Class.forName(clazz, true, loader); - for (Class required : authModuleClass) { - if (required.isAssignableFrom(c)) { - hasAuthModule = true; - break; - } - } - } catch (Throwable t) { - String msg = "skipping unloadable class: " + clazz + " of entry: " + id; - logger.log(Level.WARNING, msg); - } - } - if (!hasAuthModule) { - nameSet.remove(id); - } - } - return null; - } - }); - } catch (java.security.PrivilegedActionException pae) { - throw new SecurityException(pae.getCause()); - } - - } - return nameSet.toArray(new String[nameSet.size()]); - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java deleted file mode 100644 index 3b912b34a44..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package com.sun.jaspic.config.jaas; - -import com.sun.jaspic.config.helper.BaseAuthContextImpl; -import com.sun.jaspic.config.helper.BaseAuthConfigProvider; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Locale; -import java.util.Map; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; - -/** - * - * @author Ron Monzillo - */ -public abstract class JAASAuthConfigProvider extends BaseAuthConfigProvider { - - private static final String CONFIG_FILE_NAME_KEY = "config.file.name"; - private static final String DEFAULT_JAAS_APP_NAME = "other"; - private static final String ALL_APPS = "*"; - - private String configFileName; - private ExtendedConfigFile jaasConfig; - - private Map properties; - private AuthConfigFactory factory; - - public JAASAuthConfigProvider(Map properties, AuthConfigFactory factory) { - this.properties = properties; - this.factory = factory; - - configFileName = getProperty(CONFIG_FILE_NAME_KEY, null); - - if (configFileName == null) { - jaasConfig = new ExtendedConfigFile(); - } else { - try { - URI uri = new URI(configFileName); - jaasConfig = new ExtendedConfigFile(uri); - } catch (URISyntaxException use) { - IllegalArgumentException iae = new IllegalArgumentException(use); - throw iae; - } - } - selfRegister(); - } - - @Override - public Map getProperties() { - return properties; - } - - @Override - public AuthConfigFactory getFactory() { - return factory; - } - - private RegistrationContext getRegistrationContext(String id) { - - final String layer = getLayer(); - final String appContext; - if (id.toLowerCase(Locale.getDefault()).equals(DEFAULT_JAAS_APP_NAME)) { - appContext = ALL_APPS; - } else { - appContext = id; - } - - return new RegistrationContext() { - - final String description = "JAAS AuthConfig: " + appContext; - - @Override - public String getMessageLayer() { - return layer; - } - - @Override - public String getAppContext() { - return appContext; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public boolean isPersistent() { - return false; - } - }; - } - - @Override - public AuthConfigFactory.RegistrationContext[] getSelfRegistrationContexts() { - final String[] appContexts = jaasConfig.getAppNames(getModuleTypes()); - RegistrationContext[] rvalue = new RegistrationContext[appContexts.length]; - for (int i = 0; i < appContexts.length; i++) { - rvalue[i] = getRegistrationContext(appContexts[i]); - } - return rvalue; - } - - @Override - public BaseAuthContextImpl getAuthContextHelper(String appContext, boolean returnNullContexts) throws AuthException { - return new JAASAuthContextHelper(getLoggerName(), returnNullContexts, jaasConfig, properties, appContext); - } - - @Override - public void refresh() { - jaasConfig.refresh(); - super.refresh(); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthContextHelper.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthContextHelper.java deleted file mode 100644 index aa05064363e..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthContextHelper.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.jaas; - -import com.sun.jaspic.config.helper.BaseAuthContextImpl; - -import static java.security.AccessController.doPrivileged; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.INFO; -import static javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL; -import static javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; -import static javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.REQUISITE; -import static javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.logging.Level; -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; - -/** - * - * @author Ron Monzillo - */ -public class JAASAuthContextHelper extends BaseAuthContextImpl { - - private static final String DEFAULT_ENTRY_NAME = "other"; - private static final Class[] PARAMS = {}; - private static final Object[] ARGS = {}; - - // may be more than one delegate for a given jaas config file - private ReentrantReadWriteLock instanceReadWriteLock = new ReentrantReadWriteLock(); - private Lock instanceWriteLock = instanceReadWriteLock.writeLock(); - private ExtendedConfigFile jaasConfig; - private final String appContext; - private AppConfigurationEntry[] entry; - private Constructor[] constructors; - - public JAASAuthContextHelper(String loggerName, boolean returnNullContexts, ExtendedConfigFile jaasConfig, Map properties, - String appContext) throws AuthException { - super(loggerName, returnNullContexts); - this.jaasConfig = jaasConfig; - this.appContext = appContext; - - initialize(); - } - - private void initialize() { - boolean found = false; - boolean foundDefault = false; - instanceWriteLock.lock(); - try { - entry = jaasConfig.getAppConfigurationEntry(appContext); - if (entry == null) { - - // NEED TO MAKE SURE THIS LOOKUP only occurs when registered for * - entry = jaasConfig.getAppConfigurationEntry(DEFAULT_ENTRY_NAME); - if (entry == null) { - entry = new AppConfigurationEntry[0]; - } else { - foundDefault = true; - } - } else { - found = true; - } - constructors = null; - } finally { - instanceWriteLock.unlock(); - } - - if (!found) { - if (!foundDefault) { - logIfLevel(INFO, null, "JAASAuthConfig no entries matched appContext (", appContext, ") or (", DEFAULT_ENTRY_NAME, - ")"); - } else { - logIfLevel(INFO, null, "JAASAuthConfig appContext (", appContext, ") matched (", DEFAULT_ENTRY_NAME, ")"); - } - } - } - - private void loadConstructors(M[] template, String authContextID) throws AuthException { - if (constructors == null) { - try { - final Class moduleType = template.getClass().getComponentType(); - constructors = (Constructor[]) AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - - @Override - public Object run() - throws java.lang.ClassNotFoundException, java.lang.NoSuchMethodException, java.lang.InstantiationException, - java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException { - Constructor[] ctor = new Constructor[entry.length]; - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - for (int i = 0; i < entry.length; i++) { - ctor[i] = null; - String clazz = entry[i].getLoginModuleName(); - try { - Class c = Class.forName(clazz, true, loader); - if (moduleType.isAssignableFrom(c)) { - ctor[i] = c.getConstructor(PARAMS); - } - - } catch (Throwable t) { - logIfLevel(Level.WARNING, null, "skipping unloadable class: ", clazz, " of appCOntext: ", appContext); - } - } - return ctor; - } - }); - } catch (java.security.PrivilegedActionException pae) { - AuthException ae = new AuthException(); - ae.initCause(pae.getCause()); - throw ae; - } - } - } - - @Override - protected final void refresh() { - jaasConfig.refresh(); - initialize(); - } - - /** - * This implementation does not depend on authContextID - * - * @param - * @param template - * @param authContextID (ignored by this context system) - * @return - * @throws AuthException - */ - @Override - public boolean hasModules(M[] template, String authContextID) throws AuthException { - loadConstructors(template, authContextID); - - for (Constructor constructor : constructors) { - if (constructor != null) { - return true; - } - } - - return false; - } - - /** - * this implementation does not depend on authContextID - * - * @param - * @param template - * @param authContextID (ignored by this context system) - * @return - * @throws AuthException - */ - @Override - public M[] getModules(M[] template, String authContextID) throws AuthException { - loadConstructors(template, authContextID); - ArrayList list = new ArrayList(); - - for (int i = 0; i < constructors.length; i++) { - if (constructors[i] == null) { - list.add(i, null); - } else { - final int j = i; - try { - list.add(j, doPrivileged(new PrivilegedExceptionAction() { - - @Override - @SuppressWarnings("unchecked") - public M run() - throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - return (M) constructors[j].newInstance(ARGS); - } - })); - } catch (PrivilegedActionException pae) { - throw (AuthException) new AuthException().initCause(pae.getCause()); - } - } - } - - return list.toArray(template); - } - - @Override - public Map getInitProperties(int i, Map properties) { - Map initProperties = new HashMap<>(); - - if (entry[i] != null) { - if (properties != null && !properties.isEmpty()) { - initProperties.putAll(properties); - } - - @SuppressWarnings("unchecked") - Map options = (Map) entry[i].getOptions(); - if (options != null && !options.isEmpty()) { - initProperties.putAll(options); - } - } - - return initProperties; - } - - @Override - public boolean exitContext(AuthStatus[] successValue, int i, AuthStatus moduleStatus) { - if (entry[i] != null && constructors[i] != null) { - LoginModuleControlFlag flag = entry[i].getControlFlag(); - - if (REQUISITE.equals(flag)) { - for (AuthStatus authStatus : successValue) { - if (moduleStatus == authStatus) { - return false; - } - } - - return true; - } else if (SUFFICIENT.equals(flag)) { - for (AuthStatus s : successValue) { - if (moduleStatus == s) { - return true; - } - } - - return false; - } - } - - return false; - } - - @Override - public AuthStatus getReturnStatus(AuthStatus[] successValue, AuthStatus defaultFailStatus, AuthStatus[] status, int position) { - AuthStatus returnStatus = null; - - for (int i = 0; i <= position; i++) { - if (entry[i] != null && constructors[i] != null) { - - LoginModuleControlFlag flag = entry[i].getControlFlag(); - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "getReturnStatus - flag: ", flag.toString()); - } - - if (flag == REQUIRED || flag == REQUISITE) { - boolean isSuccessValue = false; - for (AuthStatus authStatus : successValue) { - if (status[i] == authStatus) { - isSuccessValue = true; - } - } - - if (isSuccessValue) { - if (returnStatus == null) { - returnStatus = status[i]; - } - continue; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ReturnStatus - REQUIRED or REQUISITE failure: ", status[i].toString()); - } - return status[i]; - } else if (flag == SUFFICIENT) { - if (exitContext(successValue, i, status[i])) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ReturnStatus - Sufficient success: ", status[i].toString()); - } - - return status[i]; - } - - } else if (flag == OPTIONAL) { - if (returnStatus == null) { - for (AuthStatus authStatus : successValue) { - if (status[i] == authStatus) { - returnStatus = status[i]; - } - } - } - } - } - } - - if (returnStatus != null) { - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ReturnStatus - result: ", returnStatus.toString()); - } - - return returnStatus; - } - - if (isLoggable(FINE)) { - logIfLevel(FINE, null, "ReturnStatus - Default faiure status: ", defaultFailStatus.toString()); - } - - return defaultFailStatus; - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/HttpMessageInfo.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/HttpMessageInfo.java deleted file mode 100644 index 02006a40788..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/HttpMessageInfo.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDLGPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.servlet; - -import java.util.HashMap; -import java.util.Map; - -import jakarta.security.auth.message.MessageInfo; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -public class HttpMessageInfo implements MessageInfo { - - private HttpServletRequest request = null; - private HttpServletResponse response = null; - private Map map = new HashMap<>(); - - public HttpMessageInfo(HttpServletRequest request, HttpServletResponse response) { - this.request = request; - this.response = response; - } - - @Override - public HttpServletRequest getRequestMessage() { - return request; - } - - @Override - public HttpServletResponse getResponseMessage() { - return response; - } - - @Override - public void setRequestMessage(Object request) { - this.request = (HttpServletRequest) request; - } - - @Override - public void setResponseMessage(Object response) { - this.response = (HttpServletResponse) response; - } - - @Override - public Map getMap() { - return map; - } -} \ No newline at end of file diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/JAASServletAuthConfigProvider.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/JAASServletAuthConfigProvider.java deleted file mode 100755 index 19b96ba9593..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/servlet/JAASServletAuthConfigProvider.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.jaspic.config.servlet; - -import static jakarta.security.auth.message.MessagePolicy.ProtectionPolicy.AUTHENTICATE_SENDER; - -import java.util.Map; - -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.MessagePolicy.TargetPolicy; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.module.ServerAuthModule; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -import com.sun.jaspic.config.delegate.MessagePolicyDelegate; -import com.sun.jaspic.config.helper.BaseAuthContextImpl; -import com.sun.jaspic.config.jaas.JAASAuthConfigProvider; - -/** - * - * @author Ron Monzillo - */ -public class JAASServletAuthConfigProvider extends JAASAuthConfigProvider { - - private static final String HTTP_SERVLET_LAYER = "HttpServlet"; - private static final String MANDATORY_KEY = "jakarta.security.auth.message.MessagePolicy.isMandatory"; - private static final String MANDATORY_AUTH_CONTEXT_ID = "mandatory"; - private static final String OPTIONAL_AUTH_CONTEXT_ID = "optional"; - - private static final Class[] moduleTypes = new Class[] { ServerAuthModule.class }; - private static final Class[] messageTypes = new Class[] { HttpServletRequest.class, HttpServletResponse.class }; - - private static final MessagePolicy mandatoryPolicy = new MessagePolicy( - new TargetPolicy[] { - new TargetPolicy( - null, - () -> AUTHENTICATE_SENDER) - }, - true); - - private static final MessagePolicy optionalPolicy = new MessagePolicy( - new TargetPolicy[] { - new TargetPolicy( - null, - () -> AUTHENTICATE_SENDER) - }, - false); - - public JAASServletAuthConfigProvider(Map properties, AuthConfigFactory factory) { - super(properties, factory); - } - - @Override - public MessagePolicyDelegate getMessagePolicyDelegate(String appContext) throws AuthException { - - return new MessagePolicyDelegate() { - - @Override - public MessagePolicy getRequestPolicy(String authContextID, Map properties) { - return MANDATORY_AUTH_CONTEXT_ID.equals(authContextID) ? mandatoryPolicy : optionalPolicy; - } - - @Override - public MessagePolicy getResponsePolicy(String authContextID, Map properties) { - return null; - } - - @Override - public Class[] getMessageTypes() { - return messageTypes; - } - - @Override - public String getAuthContextID(MessageInfo messageInfo) { - return messageInfo.getMap().containsKey(MANDATORY_KEY) ? MANDATORY_AUTH_CONTEXT_ID : OPTIONAL_AUTH_CONTEXT_ID; - } - - @Override - public boolean isProtected() { - return true; - } - - }; - } - - @Override - protected Class[] getModuleTypes() { - return moduleTypes; - } - - @Override - protected String getLayer() { - return HTTP_SERVLET_LAYER; - } - - @Override - public BaseAuthContextImpl getAuthContextHelper(String appContext, boolean returnNullContexts) throws AuthException { - // overrides returnNullContexts to false (as required by Servlet Profile) - return super.getAuthContextHelper(appContext, false); - } -} diff --git a/appserver/security/jaspic-provider-framework/src/main/resources/com/sun/logging/enterprise/system/jaspic/security/LogStrings.properties b/appserver/security/jaspic-provider-framework/src/main/resources/com/sun/logging/enterprise/system/jaspic/security/LogStrings.properties deleted file mode 100644 index c6d9307ab72..00000000000 --- a/appserver/security/jaspic-provider-framework/src/main/resources/com/sun/logging/enterprise/system/jaspic/security/LogStrings.properties +++ /dev/null @@ -1,49 +0,0 @@ -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. -# -# Copyright (c) 2004-2011 Oracle and/or its affiliates. All rights reserved. -# -# The contents of this file are subject to the terms of either the GNU -# General Public License Version 2 only ("GPL") or the Common Development -# and Distribution License("CDDL") (collectively, the "License"). You -# may not use this file except in compliance with the License. You can -# obtain a copy of the License at -# https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html -# or packager/legal/LICENSE.txt. See the License for the specific -# language governing permissions and limitations under the License. -# -# When distributing the software, include this License Header Notice in each -# file and include the License file at packager/legal/LICENSE.txt. -# -# GPL Classpath Exception: -# Oracle designates this particular file as subject to the "Classpath" -# exception as provided by Oracle in the GPL Version 2 section of the License -# file that accompanied this code. -# -# Modifications: -# If applicable, add the following below the License Header, with the fields -# enclosed by brackets [] replaced by your own identifying information: -# "Portions Copyright [year] [name of copyright owner]" -# -# Contributor(s): -# If you wish your version of this file to be governed by only the CDDL or -# only the GPL Version 2, indicate your decision by adding "[Contributor] -# elects to include this software in this distribution under the [CDDL or GPL -# Version 2] license." If you don't indicate a single choice of license, a -# recipient has the option to distribute your version of this file under -# either the CDDL, the GPL Version 2 or to extend the choice of license to -# its licensees as provided above. However, if you add GPL Version 2 code -# and therefore, elected the GPL Version 2 license, then the option applies -# only if the new code is made subject to such option by the copyright -# holder. -# -# Portions Copyright [2019] [Payara Foundation and/or its affiliates] - -# JASPIC: start at 1200 : security/core has some of these as duplicates need to cleanup -jaspic.factory_unable_to_load_provider=SEC1203: GFAuthConfigFactory unable to load Provider: {0}, exception : {1}, cause : {2}. -jaspic.factory_auth_config_loader_failure=SEC1204: GFAuthConfigFactory loader failure -jaspic.factory_cannot_write_file=SEC1205: Cannot write to file {0}. Updated provider list will not be persisted. -jaspic.factory_could_not_persist=SEC1206: Could not persist updated provider list due to {0}. Will use default providers when reloaded. -jaspic.factory_could_not_read=SEC1207: Could not read auth configuration file due to {0} Will use default providers. -jaspic.factory_file_not_found=SEC1208: Configuration file does not exist at {0}. Will use default providers. -jaspic.factory_creating_conf_file=SEC1210: Creating JASPIC Configuration file {0}. diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java deleted file mode 100644 index 253eb82236e..00000000000 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/FactoryTest.java +++ /dev/null @@ -1,1013 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] -package test.com.sun.jaspic.config; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.Future; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.ExecutorService; -import java.util.ArrayList; -import java.util.List; -import com.sun.jaspic.config.factory.EntryInfo; -import java.security.Security; -import org.junit.After; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.StringTokenizer; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.config.RegistrationListener; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; - -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Ron Monzillo - */ -public class FactoryTest { - - /** switch definition of default test factory to test native factory - * will also need to configure proper dependencies - */ - private static final String DEFAULT_TEST_FACTORY_CLASS_NAME = AuthConfigFileFactory.class.getName(); - private static String testFactoryClassName = DEFAULT_TEST_FACTORY_CLASS_NAME; - public static final String DEFAULT_FACTORY_SECURITY_PROPERTY = - "authconfigprovider.factory"; - public static final String USER_DIR_PROPERTY = "user.dir"; - static final String THREAD_COUNT_KEY = "test.thread.count"; - static final String MAX_JOIN_SECONDS_KEY = "test.max.join.seconds"; - static final String TEST_FACTORY_CLASS_NAME_KEY = "test.factory.class.name"; - static final int DEFAULT_THREAD_COUNT = 32; - static final int DEFAULT_MAX_JOIN_SECONDS = 600; - static final Logger logger = Logger.getLogger(FactoryTest.class.getName()); - private static String defaultFactoryClassName; - private static AuthConfigFactory testFactory; - static HashMap options = new HashMap(); - private static ExecutorService threadPool; - static int consumerCount; - static int activeConsumers; - static Random random = new Random(); - static final String[] layers = new String[4]; - static final String[] contexts = new String[16]; - - static { - layers[0] = null; - for (int i = 1; i < layers.length; i++) { - layers[i] = "layer" + Integer.toString(i); - } - contexts[0] = null; - for (int i = 1; i < contexts.length; i++) { - contexts[i] = "context" + Integer.toString(i); - } - } - static AuthConfigProvider[] providers = new AuthConfigProvider[4]; - - public FactoryTest() { - } - - public static String getStringOption(String key, String defaultValue) { - String s = options == null ? null : (String) options.get(key); - if (s == null) { - return defaultValue; - } - return s; - } - - public static int getIntOption(String key, int defaultValue) { - String s = options == null ? null : (String) options.get(key); - if (s == null) { - return defaultValue; - } - return Integer.valueOf(s).intValue(); - } - - public static boolean getbooleanOption(String key, boolean defaultValue) { - String s = options == null ? null : (String) options.get(key); - if (s == null) { - return defaultValue; - } - return Boolean.valueOf(s).booleanValue(); - } - - public static String[] splitStringOption(String s) { - if (s == null) { - return new String[0]; - } - return s.split(",|:| |;"); - } - - static Map getProviderProperties() { - return new HashMap(); - } - - static AuthConfigFactory loadFactory(final String className) { - AuthConfigFactory factory = null; - try { - factory = (AuthConfigFactory) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - - @Override - public Object run() - throws ClassNotFoundException, - InstantiationException, - IllegalAccessException { - ClassLoader loader = - Thread.currentThread(). - getContextClassLoader(); - - Class clazz = Class.forName(className, true, loader); - return clazz.newInstance(); - } - }); - } catch (java.security.PrivilegedActionException pae) { - throw new SecurityException(pae.getException()); - } finally { - assertNotNull("loadFactory returned null", factory); - } - return factory; - } - - public static void main(String[] args) { - - for (String s : args) { - StringTokenizer tokenizer = new StringTokenizer(s, "="); - if (tokenizer.countTokens() == 2) { - String key = tokenizer.nextToken(); - String value = tokenizer.nextToken(); - System.out.println("key: " + key + " value: " + value); - options.put(key, value); - } - } - - testFactoryClassName = getStringOption(TEST_FACTORY_CLASS_NAME_KEY, - DEFAULT_TEST_FACTORY_CLASS_NAME); - - new FactoryTest().beforeTest(); - new FactoryTest().testSetFactory(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testOverrideForDefaultEntries(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testRemoveRegistration(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testListeners(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().stressFactory( - getIntOption(THREAD_COUNT_KEY, DEFAULT_THREAD_COUNT), - getIntOption(MAX_JOIN_SECONDS_KEY, DEFAULT_MAX_JOIN_SECONDS)); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testRegistrationWithNonStringProperty(); - new FactoryTest().afterTest(); - - new FactoryTest().beforeTest(); - new FactoryTest().testRegistrationWithNonStringPropertyAndPreviousRegistration(); - new FactoryTest().afterTest(); - } - - @Before - public void beforeTest() { - try { - defaultFactoryClassName = Security.getProperty(DEFAULT_FACTORY_SECURITY_PROPERTY); - logger.log(Level.INFO, "\n\tSecurity Manager is {0}\n\t{1} is {2}\n\t{3} is {4}\n\t{5} is {6}\n", - new Object[]{ - (System.getSecurityManager() == null ? "OFF" : "ON"), - DEFAULT_FACTORY_SECURITY_PROPERTY, defaultFactoryClassName, - "Test Factory Class Name", testFactoryClassName, - USER_DIR_PROPERTY, System.getProperty(USER_DIR_PROPERTY)}); - testFactory = loadFactory(testFactoryClassName); - AuthConfigFactory.setFactory(testFactory); - } catch (Throwable t) { - logger.log(Level.SEVERE, "Exception in test setup", t); - fail("exception in test setup: " + t.toString()); - } - assertNotNull("at exit of beforeTest getFactory returns null",AuthConfigFactory.getFactory()); - } - - @After - public void afterTest() { - AuthConfigFactory.setFactory(null); - } - - @Test - public void testSetFactory() { - logger.info("BEGIN Set FACTORY TEST"); - AuthConfigFactory.setFactory(null); - assertTrue(defaultFactoryClassName == null - ? AuthConfigFactory.getFactory() == null - : defaultFactoryClassName.equals(AuthConfigFactory.getFactory().getClass().getName())); - if (defaultFactoryClassName != null) { - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, testFactoryClassName); - AuthConfigFactory.setFactory(null); - assertTrue(testFactoryClassName.equals(AuthConfigFactory.getFactory().getClass().getName())); - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, defaultFactoryClassName); - AuthConfigFactory.setFactory(null); - assertTrue(defaultFactoryClassName.equals(AuthConfigFactory.getFactory().getClass().getName())); - } - AuthConfigFactory.setFactory(testFactory); - assertTrue(testFactoryClassName.equals(AuthConfigFactory.getFactory().getClass().getName())); - } - - @Test - public void testRegistrationWithNonStringProperty() { - logger.info("BEGIN Registration with NonString Property FACTORY TEST"); - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, testFactoryClassName); - String className = _AuthConfigProvider.class.getName(); - HashMap properties = new HashMap(); - ArrayList list = new ArrayList(); - list.add("larry was here"); - properties.put("test", list); - String layer = "HttpServlet"; - String appContext = "context"; - String description = null; - String regId = null; - try { - regId = AuthConfigFactory.getFactory().registerConfigProvider(className, properties, layer, appContext, description); - } catch (IllegalArgumentException iae) { - assertNull("Failed Registration Should Have Resulted in a NULL RegistrationID returned but did not.", regId); - } - AuthConfigProvider acp = null; - acp = AuthConfigFactory.getFactory().getConfigProvider(layer, appContext, null); - assertNull("Registration Should Have Failed and Therefore No ACP Should Have been Found.", acp); - } - - @Test - public void testRegistrationWithNonStringPropertyAndPreviousRegistration() { - logger.info("BEGIN Registration with NonString Property and Previous Registration FACTORY TEST"); - Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, testFactoryClassName); - - // first register a valid acp configuration - String className = _AuthConfigProvider.class.getName(); - HashMap properties = null; - String layer = "HttpServlet"; - String appContext = "context"; - String description = null; - String regId = null; - regId = AuthConfigFactory.getFactory().registerConfigProvider(className, properties, layer, appContext, description); - assertNotNull("Registration Should Have Succeeded returning a nonNULL RegistrationID but did not.", regId); - AuthConfigProvider previousAcp = null; - previousAcp = AuthConfigFactory.getFactory().getConfigProvider(layer, appContext, null); - assertNotNull("Registration Should Have Succeeded returning a nonNULL ACP but did not.", previousAcp); - String previousRegId = regId; - - // now for an invalid configuration - properties = new HashMap(); - ArrayList list = new ArrayList(); - list.add("larry was here"); - properties.put("test", list); - layer = "HttpServlet"; - appContext = "context"; - description = null; - regId = null; - try { - regId = AuthConfigFactory.getFactory().registerConfigProvider(className, properties, layer, appContext, description); - } catch (IllegalArgumentException iae) { - assertNull("Failed Registration Should Have Resulted in a NULL RegistrationID returned but did not.", regId); - } - AuthConfigProvider acp = null; - acp = AuthConfigFactory.getFactory().getConfigProvider(layer, appContext, null); - assertTrue("Registration Should Have Failed for Invalid Config and Therefore returned the Previously Registered ACP", previousAcp == acp); - - assertTrue("Failed to remove the previously registered provider.", AuthConfigFactory.getFactory().removeRegistration(previousRegId)); - } - - @Test - public void testOverrideForDefaultEntries() { - logger.info("BEGIN overrideGetDefaultEntries TEST"); - AuthConfigFactory f = new _ExtendsBaseAuthConfigFactory(); - f = new _Extends_ExtendsAuthConfigFactory(); - } - - static class _ExtendsBaseAuthConfigFactory extends BaseAuthConfigFactory { - - // regStore MUST hide regStore of bade class - private static RegStoreFileParser regStore = null; - - /** - * To specialize the defaultEntries passed to the RegStoreFileParser, - * construct EntryInfo objects within this constructor. - * THE EentyInfo OBJECTS MUST ONLY BE CONSTRCTED USING THE FOLLOWING - * CONSTRUCTOR: EntryInfo(String className, Map properties) - * NO Entries are passed by this test, because to do so, the parent - * test class would need to import EntryInfo (which it can't). - */ - public _ExtendsBaseAuthConfigFactory() { - readLock.lock(); - try { - if (regStore != null) { - return; - } - } finally { - readLock.unlock(); - } - String userDir = System.getProperty("user.dir"); - writeLock.lock(); - try { - if (regStore == null) { - EntryInfo e = new EntryInfo(_AuthConfigProvider.class.getName(),null); - List defaultEntries = new ArrayList(); - defaultEntries.add(e); - regStore = new RegStoreFileParser(userDir, - BaseAuthConfigFactory.CONF_FILE_NAME,defaultEntries); - _loadFactory(); - } - } finally { - writeLock.unlock(); - } - RegStoreFileParser rS = getRegStore(); - assertTrue(rS == _ExtendsBaseAuthConfigFactory.regStore); - } - - @Override - protected RegStoreFileParser getRegStore() { - readLock.lock(); - try { - return regStore; - } finally { - readLock.unlock(); - } - } - } - - static class _Extends_ExtendsAuthConfigFactory extends _ExtendsBaseAuthConfigFactory { - - // regStore MUST hide regStore of base class - private static RegStoreFileParser regStore = null; - - /** - * To specialize the defaultEntries passed to the RegStoreFileParser, - * construct EntryInfo objects within this constructor. - * THE EentyInfo OBJECTS MUST ONLY BE CONSTRCTED USING THE FOLLOWING - * CONSTRUCTOR: EntryInfo(String className, Map properties) - * NO Entries are passed by this test, because to do so, the parent - * test class would need to import EntryInfo (which it can't). - */ - public _Extends_ExtendsAuthConfigFactory() { - readLock.lock(); - try { - if (regStore != null) { - return; - } - } finally { - readLock.unlock(); - } - String userDir = System.getProperty("user.dir"); - writeLock.lock(); - try { - if (regStore == null) { - EntryInfo e = new EntryInfo(_AuthConfigProvider.class.getName(),null); - List defaultEntries = new ArrayList(); - defaultEntries.add(e); - regStore = new RegStoreFileParser(userDir, - BaseAuthConfigFactory.CONF_FILE_NAME,defaultEntries); - _loadFactory(); - } - } finally { - writeLock.unlock(); - } - RegStoreFileParser rS = getRegStore(); - assertTrue(rS == _Extends_ExtendsAuthConfigFactory.regStore); - } - - @Override - protected RegStoreFileParser getRegStore() { - readLock.lock(); - try { - return regStore; - } finally { - readLock.unlock(); - } - } - } - - @Test - public void testRemoveRegistration() { - logger.info("BEGIN Remove Registration TEST"); - final AuthConfigFactory f = AuthConfigFactory.getFactory(); - f.refresh(); - // does self registration - AuthConfigProvider p = new _AuthConfigProvider(new HashMap(), f); - RegistrationContext rc; - String[] rids = f.getRegistrationIDs(p); - boolean removed; - assertTrue("provider did not self register", rids != null && rids.length > 0); - for (String i : rids) { - rc = f.getRegistrationContext(i); - removed = f.removeRegistration(i); - assertTrue("expected true from removeRegistration - rid: " + i, - rc != null && removed); - } - for (String i : rids) { - rc = f.getRegistrationContext(i); - removed = f.removeRegistration(i); - assertTrue("expected false from removeRegistration - rid: " + i, - rc == null && !removed); - } - - //testing registration and removal of null provider; - String rid = f.registerConfigProvider(null, null, null, "null registration"); - rc = f.getRegistrationContext(rid); - removed = f.removeRegistration(rid); - assertTrue("testing null provider - expected true from removeRegistration - rid: " + rid, - rc != null && removed); - //testing for interferece with null provider - rc = f.getRegistrationContext(rid); - removed = f.removeRegistration(rid); - assertTrue("testing null provider - expected false from removeRegistration - rid: " + rid, - rc == null && !removed); - rid = f.registerConfigProvider(null, null, null, "null registration"); - //temporary to force call to decomposeRegId in getEffectedListeners - p = f.getConfigProvider(null, null, new _Listener(null, null, false)); - rc = f.getRegistrationContext(rid); - assertTrue("testing null provider - getRegistrationContext - rid: " + rid, - rid != null); - String badRid = "someInvalidId"; - rc = f.getRegistrationContext(badRid); - removed = f.removeRegistration(badRid); - assertTrue("expected false from removeRegistration - rid: " + badRid, - rc == null && !removed); - rc = f.getRegistrationContext(rid); - removed = f.removeRegistration(rid); - assertTrue("testing null provider - expected true from removeRegistration - rid: " + rid, - rc != null && removed); - } - - @Test - public void testListeners() { - logger.info("BEGIN Listener TEST"); - final AuthConfigFactory f = AuthConfigFactory.getFactory(); - final AuthConfigProvider p = new _AuthConfigProvider(new HashMap(), null); - - String layer[] = {null, "11", "l2"}; - String context[] = {null, "c1", "c2"}; - String rid[] = new String[(layer.length - 1) * (context.length - 1)]; - String ridLayer[] = new String[rid.length]; - String ridContext[] = new String[rid.length]; - - int z = 0; - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 2; j++) { - ridLayer[z] = layer[i]; - ridContext[z] = context[j]; - rid[z] = f.registerConfigProvider(p, ridLayer[z], ridContext[z], - ridLayer[z] + ridContext[z]); - z++; - } - } - - _Listener listener[] = new _Listener[rid.length]; - - z = 0; - for (int i = 1; i < layer.length; i++) { - for (int j = 1; j < context.length; j++) { - listener[z] = new _Listener(layer[i], context[j], true); - f.getConfigProvider(layer[i], context[j], listener[z]); - z++; - } - } - - for (int i = 0; i < rid.length; i++) { - f.removeRegistration(rid[i]); - } - - - f.detachListener(listener[0], null, null); - f.detachListener(listener[1], listener[1].getLayer(), null); - f.detachListener(listener[2], null, listener[2].getAppContext()); - f.detachListener(listener[3], listener[3].getLayer(), listener[3].getAppContext()); - - //should not find any left to detach - for (int i = 0; i < listener.length; i++) { - f.detachListener(listener[i], listener[i].getLayer(), listener[i].getAppContext()); - } - - for (int i = 0; i < rid.length; i++) { - rid[i] = f.registerConfigProvider(p, ridLayer[i], ridContext[i], ridLayer[i] + ridContext[i]); - } - - z = 0; - for (int i = 1; i < layer.length; i++) { - for (int j = 1; j < context.length; j++) { - listener[z] = new _Listener(layer[i], context[j], false); - f.getConfigProvider(layer[i], context[j], listener[z]); - z++; - } - } - for (int i = 0; i < rid.length; i++) { - for (int j = 0; j < listener.length; j++) { - if (listener[j].notified) { - assertTrue("Test Setup Failure - listener could not be registered", - listener[j].register()); - } - } - f.removeRegistration(rid[i]); - - for (int j = 0; j < listener.length; j++) { - listener[j].check(ridLayer[i], ridContext[i]); - } - } - - //repeat with null provider registrations - for (int i = 0; i < rid.length; i++) { - rid[i] = f.registerConfigProvider(null, ridLayer[i], ridContext[i], ridLayer[i] + ridContext[i]); - } - - z = 0; - for (int i = 1; i < layer.length; i++) { - for (int j = 1; j < context.length; j++) { - listener[z] = new _Listener(layer[i], context[j], false); - f.getConfigProvider(layer[i], context[j], listener[z]); - z++; - } - } - for (int i = 0; i < rid.length; i++) { - for (int j = 0; j < listener.length; j++) { - if (listener[j].notified) { - assertTrue("Test Setup Failure - listener could not be registered", - listener[j].register()); - } - } - f.removeRegistration(rid[i]); - - for (int j = 0; j < listener.length; j++) { - listener[j].check(ridLayer[i], ridContext[i]); - } - } - } - - static class _Listener implements RegistrationListener { - - String layer; - String appContext; - boolean reRegister; - boolean notified; - - _Listener(String layer, String appContext, boolean reRegister) { - this.layer = layer; - this.appContext = appContext; - this.reRegister = reRegister; - this.notified = false; - } - - String getLayer() { - return layer; - } - - String getAppContext() { - return appContext; - } - - synchronized boolean register() { - boolean rvalue = false; - if (notified) { - notified = false; - rvalue = true; - AuthConfigFactory.getFactory().getConfigProvider(layer, appContext, this); - } - return rvalue; - } - - synchronized boolean notified() { - return notified; - } - - void check(String l, String c) { - boolean shouldHaveBeenNotified = false; - if ((l == null || layer.equals(l)) && (c == null || appContext.equals(c))) { - shouldHaveBeenNotified = true; - } - if (shouldHaveBeenNotified) { - String msg = "listener at layer,context: " + layer + "," + appContext + " should have been notified at: " - + l + "," + c; - assertTrue(msg, notified()); - } else { - String msg = "listener at layer,context: " + layer + "," + appContext + " should NOT have been notified at: " - + l + "," + c; - assertFalse(msg, notified()); - } - } - - @Override - public void notify(String l, String c) { - synchronized (this) { - notified = true; - } - boolean validNotification = (layer == l || layer.equals(l)) - && (appContext == c || appContext.equals(c)); - String msg = "listener notified at wrong layer: " + l + " or context: " + c; - assertTrue(msg, validNotification); - if (validNotification && reRegister) { - register(); - } - } - } - - @Test - public void stressFactory() { - stressFactory(DEFAULT_THREAD_COUNT, DEFAULT_MAX_JOIN_SECONDS); - } - - public void stressFactory(int threadCount, int maxJoinSeconds) { - - logger.info("BEGIN stress FACTORY TEST"); - AuthConfigFactory f = AuthConfigFactory.getFactory(); - f.refresh(); - providers[0] = null; - - for (int i = 1; i < providers.length; i++) { - providers[i] = new _AuthConfigProvider(getProviderProperties(), null); - } - threadPool = Executors.newFixedThreadPool(threadCount); - synchronized (_Thread.class) { - activeConsumers = threadCount; - consumerCount = threadCount; - } - - ArrayList> tasks = new ArrayList>(); - - for (int i = 0; i < threadCount; i++) { - _ResultCarrier carrier = new _ResultCarrier(); - Callable<_ResultCarrier> task = - Executors.callable(new _Thread(threadCount,carrier),carrier); - tasks.add(task); - } - - logger.log(Level.INFO, "STARTING {0} THREADS", threadCount); - try { - List> futures = threadPool.invokeAll(tasks,maxJoinSeconds,TimeUnit.SECONDS); - for (Future<_ResultCarrier> future : futures) { - if (future.isCancelled()) { - logger.log(Level.WARNING, - "try increasing maxJoinSeconds in {0}: test aborted because it did not terminate in {1} seconds", - new Object[]{this.getClass().getName(),maxJoinSeconds}); - fail("test did not terminate in: " + maxJoinSeconds + " seconds"); - } else if (future.isDone()) { - String errorMessage = future.get().getResult(); - if (errorMessage != null) { - logger.log(Level.SEVERE, errorMessage); - fail(errorMessage); - } - } - } - } catch (Throwable t) { - String exceptionMessage = "exception from invoking tasks or from invoked task"; - logger.log(Level.SEVERE, exceptionMessage,t); - fail(exceptionMessage + t.toString()); - } - - synchronized (_Thread.class) { - logger.log(Level.INFO, "ALL THREADS JOINED - producers: {0} consumers: {1}", - new Object[]{threadCount - consumerCount, consumerCount}); - } - - String[] rids = f.getRegistrationIDs(null); - for (String i : rids) { - RegistrationContext rc = f.getRegistrationContext(i); - f.removeRegistration(i); - } - logger.info("ALL REGISTRATIONS REMOVED"); - - f.refresh(); - } - - static class _ResultCarrier { - String result; - synchronized String getResult() { - return result; - } - synchronized void setResult(String result) { - this.result = result; - } - } - - static class _Thread extends Thread implements RegistrationListener { - - _ResultCarrier resultCarrier; - boolean runAsConsumer; - boolean stop; - - _Thread(int threadCount, _ResultCarrier carrier) { - this.resultCarrier = carrier; - synchronized (_Thread.class) { - if (consumerCount == threadCount) { - runAsConsumer = false; - } else { - runAsConsumer = (random.nextInt(10) != 1); - } - if (!runAsConsumer) { - consumerCount--; - activeConsumers--; - logger.log(Level.FINE, "creating producer, remaining consumers: {0}", consumerCount); - } - } - setResult(null); - stop = false; - } - - private void setResult(String result) { - resultCarrier.setResult(result); - } - - @Override - public void run() { - AuthConfigFactory f = AuthConfigFactory.getFactory(); - if (f == null) { - String msg = "new thread: " + getId() + " found null factory"; - logger.log(Level.SEVERE,msg); - setResult(msg); - } - else if (runAsConsumer) { - doConsumer(f, layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)]); - } else while (true) { - - synchronized (_Thread.class) { - if (activeConsumers == 0) { - setResult(null); - return; - } - } - - switch (random.nextInt(5)) { - case 0: - if (random.nextInt(25) == 1) { - try { - f.refresh(); - } catch (Exception e) { - String msg = "producer thread(refresh): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - } - } - break; - case 1: - if (random.nextInt(1000) == 1) { - try { - f = AuthConfigFactory.getFactory(); - if (f == null) { - String msg = "producer thread(get/set): " + getId() + " found null factory"; - logger.log(Level.SEVERE, msg); - setResult(msg); - return; - } - AuthConfigFactory.setFactory(f); - } catch (Exception e) { - String msg = "producer thread(get/setFactory): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - } - } - break; - case 2: - try { - f.registerConfigProvider( - _AuthConfigProvider.class.getName(), - getProviderProperties(), - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "persistent registration"); - } catch (Exception e) { - String msg = "producer thread(register persistent): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - } - break; - case 3: - try { - f.registerConfigProvider( - providers[random.nextInt(providers.length)], - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "transient registration"); - } catch (Exception e) { - String msg = "producer thread(register transient): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - } - break; - case 4: - try { - String[] rids = f.getRegistrationIDs( - providers[random.nextInt(providers.length)]); - int length = rids.length; - boolean removeNext = true; - for (String rid : rids) { - RegistrationContext rc = f.getRegistrationContext(rid); - if (rc == null) { - removeNext = true; - } else if (removeNext) { - f.removeRegistration(rid); - removeNext = false; - } else { - removeNext = true; - } - } - } catch (Exception e) { - String msg = "producer thread(remove registration): " + getId() + " caught exception: "; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - return; - - } - break; - - } - } - } - - public void doConsumer(AuthConfigFactory f, String layer, String context) { - - String msg = null; - - synchronized (_Thread.class) { - logger.log(Level.FINE, "creating consumer"); - this.stop = false; - } - - try { - f.getConfigProvider(layer, context, this); - while (true) { - sleep(10); - synchronized (_Thread.class) { - if (this.stop) { - break; - } - } - } - f.detachListener(this, null, null); - } catch (Exception e) { - msg = "consumer thread: " + getId() + " caught exception"; - logger.log(Level.SEVERE, msg, e); - setResult(msg + e.toString()); - } finally { - synchronized (_Thread.class) { - activeConsumers--; - logger.log(Level.INFO, "consumer thread: {0} stopping - remaining: {1}", - new Object[]{getId(), activeConsumers}); - } - } - } - - public void notify(String layer, String context) { - if (random.nextInt(100) == 1) { - synchronized (_Thread.class) { - setResult(null); - this.stop = true; - } - } else { - AuthConfigFactory factory = AuthConfigFactory.getFactory(); - if (factory != null) { - factory.getConfigProvider(layer, context, this); - } else { - synchronized (_Thread.class) { - setResult("factory is null in notify call on consumer"); - this.stop = true; - } - } - } - } - } - - - public static class _AuthConfigProvider implements AuthConfigProvider { - - public _AuthConfigProvider(Map properties, AuthConfigFactory f) { - if (f != null) { - f.registerConfigProvider(this, - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "self registration"); - } - } - - public ClientAuthConfig getClientAuthConfig(final String layer, - final String appCtxt, CallbackHandler ch) throws AuthException { - - return new ClientAuthConfig() { - - public ClientAuthContext getAuthContext(String string, Subject sbjct, Map map) throws AuthException { - throw new UnsupportedOperationException(); - } - - public String getMessageLayer() { - return layer; - } - - public String getAppContext() { - return appCtxt; - } - - public String getAuthContextID(MessageInfo mi) { - throw new UnsupportedOperationException(); - } - - public void refresh() { - } - - public boolean isProtected() { - throw new UnsupportedOperationException(); - } - }; - } - - public ServerAuthConfig getServerAuthConfig(final String layer, - final String appCtxt, CallbackHandler ch) throws AuthException { - - return new ServerAuthConfig() { - - public ServerAuthContext getAuthContext(String string, Subject sbjct, Map map) throws AuthException { - throw new UnsupportedOperationException(); - } - - public String getMessageLayer() { - return layer; - } - - public String getAppContext() { - return appCtxt; - } - - public String getAuthContextID(MessageInfo mi) { - throw new UnsupportedOperationException(); - } - - public void refresh() { - } - - public boolean isProtected() { - throw new UnsupportedOperationException(); - } - }; - } - - public void refresh() { - } - } - - - -} diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java deleted file mode 100644 index c8eefa5cb4a..00000000000 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/RuntimeSurrogate.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] -package test.com.sun.jaspic.config; - -import com.sun.jaspic.config.servlet.JAASServletAuthConfigProvider; -import java.io.IOException; -import java.util.HashMap; -import java.util.Random; -import java.util.StringTokenizer; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.config.AuthConfigFactory; -import jakarta.security.auth.message.config.AuthConfigFactory.RegistrationContext; -import jakarta.security.auth.message.config.AuthConfigProvider; -import jakarta.security.auth.message.config.RegistrationListener; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; - -/** - * - * @author Ron Monzillo - */ -public class RuntimeSurrogate { - - static final Logger logger = Logger.getLogger(RuntimeSurrogate.class.getName()); - private static final String CONFIG_FILE_NAME_KEY = "config.file.name"; - static HashMap providerProperties = new HashMap(); - AuthConfigFactory factory; - AuthConfigProvider provider; - - public RuntimeSurrogate(AuthConfigProvider provider, AuthConfigFactory factory) { - String[] regIDS = factory.getRegistrationIDs(provider); - for (String i : regIDS) { - try { - RegistrationContext r = factory.getRegistrationContext(i); - System.out.println(contextToString(r)); - AuthConfigProvider p = factory.getConfigProvider(r.getMessageLayer(), r.getAppContext(), null); - ServerAuthConfig c = p.getServerAuthConfig(r.getMessageLayer(), r.getAppContext(), - new CallbackHandler() { - - public void handle(Callback[] clbcks) - throws IOException, UnsupportedCallbackException { - throw new UnsupportedOperationException("Not supported yet."); - } - }); - ServerAuthContext s = c.getAuthContext("0", new Subject(), new HashMap()); - } catch (AuthException ex) { - Logger.getLogger(RuntimeSurrogate.class.getName()).log(Level.SEVERE, null, ex); - } - } - } - - public final String contextToString(RegistrationContext r) { - String rvalue = r.getDescription() + "\n\t" + r.getAppContext() + "\n\t" - + r.getMessageLayer() + "\n\t" + r.isPersistent() + "\n"; - return rvalue; - } - - public static void main(String[] args) { - System.out.println("Security Manager is " - + (System.getSecurityManager() == null ? "OFF" : "ON")); - System.out.println("user.dir: " + System.getProperty("user.dir")); - - for (String s : args) { - StringTokenizer tokenizer = new StringTokenizer(s, "="); - if (tokenizer.countTokens() == 2) { - String key = tokenizer.nextToken(); - String value = tokenizer.nextToken(); - System.out.println("key: " + key + " value: " + value); - providerProperties.put(key, value); - } - } - - AuthConfigFactory.setFactory(new AuthConfigFileFactory()); - final AuthConfigFactory f = AuthConfigFactory.getFactory(); - - final AuthConfigProvider p = new JAASServletAuthConfigProvider(providerProperties, f); - RuntimeSurrogate rS = new RuntimeSurrogate(p, f); - /* - p = new SpringServletAuthConfigProvider(properties, f); - rS = new RuntimeSurrogate(p, f); - */ - //listenertest - RegistrationListener listener = - new RegistrationListener() { - - public void notify(String layer, String context) { - System.out.println("listener notified - layer: " + layer + " context: " + context); - f.getConfigProvider(layer, context, this); - } - }; - - String rid1 = f.registerConfigProvider(p, "x", null, "test"); - String rid2 = f.registerConfigProvider(p, "x", "y1", "test"); - - f.getConfigProvider("x", "y1", listener); - f.getConfigProvider("x", "y2", listener); - - f.removeRegistration(rid2); - f.removeRegistration(rid1); - - providers[0] = null; - for (int i = 1; i < providers.length; i++) { - providers[i] = new JAASServletAuthConfigProvider(providerProperties, null); - } - f.detachListener(listener, null, null); - testFactory(); - } - static AuthConfigProvider[] providers = new AuthConfigProvider[4]; - static final TestThread[] threads = new TestThread[1024]; - - public static void testFactory() { - - AuthConfigFactory.setFactory(new AuthConfigFileFactory()); - - for (int i = 0; i < threads.length; i++) { - threads[i] = new TestThread(); - } - for (int i = 0; i < threads.length; i++) { - threads[i].start(); - } - for (TestThread t : threads) { - try { - t.join(); - } catch (InterruptedException ex) { - logger.log(Level.SEVERE, "thread: " + t.getId() + " caught exception", ex); - } finally { - logger.log(Level.INFO, "thread: {0} completed: {1}", new Object[]{t.getId(), t.runAsConsumer() ? "comsumer" : "producer"}); - } - } - logger.info("ALL THREADS JOINED"); - AuthConfigFactory f = AuthConfigFactory.getFactory(); - String[] rids = f.getRegistrationIDs(null); - for (String i : rids) { - RegistrationContext rc = f.getRegistrationContext(i); - logger.log(Level.INFO, "removing registration - layer: {0} appContext: {1} description: {2} persistent: {3}", - new Object[]{rc.getMessageLayer(), rc.getAppContext(), - rc.getDescription(), rc.isPersistent()}); - f.removeRegistration(i); - } - logger.info("ALL REGISTRATIONS REMOVED"); - } - - static class TestThread extends Thread implements RegistrationListener { - - static Random random = new Random(); - static String[] layers = new String[4]; - static String[] contexts = new String[16]; - static int consumerCount = threads.length; - boolean runAsConsumer = false; - boolean stop; - - static { - layers[0] = null; - for (int i = 1; i < layers.length; i++) { - layers[i] = "layer" + Integer.toString(i); - } - contexts[0] = null; - for (int i = 1; i < contexts.length; i++) { - contexts[i] = "context" + Integer.toString(i); - } - } - - @Override - public void run() { - synchronized (TestThread.class) { - if (consumerCount == threads.length) { - runAsConsumer = false; - } else { - runAsConsumer = (random.nextInt(threads.length / 10) != 1); - } - } - AuthConfigFactory f = AuthConfigFactory.getFactory(); - if (runAsConsumer) { - doConsumer(f, layers[random.nextInt(layers.length)], contexts[random.nextInt(contexts.length)]); - } else { - synchronized (TestThread.class) { - consumerCount--; - logger.log(Level.INFO, "creating producer, remaining consumers: " + consumerCount); - } - while (true) { - synchronized (TestThread.class) { - if (consumerCount == 0) { - return; - } - } - switch (random.nextInt(5)) { - case 0: - if (random.nextInt(25) == 1) { - try { - f.refresh(); - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - } - break; - case 1: - if (random.nextInt(1000) == 1) { - try { - f = AuthConfigFactory.getFactory(); - AuthConfigFactory.setFactory(f); - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - } - break; - case 2: - try { - f.registerConfigProvider( - "servlet.JAASServletAuthConfigProvider", providerProperties, - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "persistent registration"); - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - break; - case 3: - try { - f.registerConfigProvider( - providers[random.nextInt(providers.length)], - layers[random.nextInt(layers.length)], - contexts[random.nextInt(contexts.length)], - "transient registration"); - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - break; - case 4: - try { - String[] rids = f.getRegistrationIDs( - providers[random.nextInt(providers.length)]); - int length = rids.length; - boolean removeNext = true; - for (String rid : rids) { - RegistrationContext rc = f.getRegistrationContext(rid); - if (rc == null) { - removeNext = true; - } else if (removeNext) { - f.removeRegistration(rid); - removeNext = false; - } else { - removeNext = true; - } - } - } catch (Exception e) { - logger.log(Level.SEVERE, "producer thread: " + getId(), e); - } - break; - - } - } - } - } - - public boolean runAsConsumer() { - return runAsConsumer; - } - - public void doConsumer(AuthConfigFactory f, String layer, String context) { - - synchronized (TestThread.class) { - logger.log(Level.INFO, "creating consumer"); - this.stop = false; - } - try { - while (true) { - f.getConfigProvider(layer, context, this); - sleep(100); - synchronized (TestThread.class) { - if (this.stop) { - break; - } - } - } - f.detachListener(this, null, null); - } catch (Exception e) { - logger.log(Level.SEVERE, "consumer thread: " + getId(), e); - } finally { - synchronized (TestThread.class) { - consumerCount--; - logger.log(Level.INFO, "consumer thread: " + getId() + "stopping - remaining: " + consumerCount); - } - } - } - - public void notify(String layer, String context) { - if (random.nextInt(100) == 1) { - synchronized (TestThread.class) { - this.stop = true; - } - } - } - } -} diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleClientAuthModule.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleClientAuthModule.java deleted file mode 100644 index 7a4c2c3087d..00000000000 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleClientAuthModule.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package test.com.sun.jaspic.config; - -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.module.ClientAuthModule; - -/** - * - * @author Ron Monzillo - */ -public class SampleClientAuthModule implements ClientAuthModule { - - public void initialize(MessagePolicy mp, MessagePolicy mp1, CallbackHandler ch, Map map) throws AuthException { - throw new UnsupportedOperationException("Not supported yet."); - } - - public Class[] getSupportedMessageTypes() { - throw new UnsupportedOperationException("Not supported yet."); - } - - public AuthStatus secureRequest(MessageInfo mi, Subject sbjct) throws AuthException { - throw new UnsupportedOperationException("Not supported yet."); - } - - public AuthStatus validateResponse(MessageInfo mi, Subject sbjct, Subject sbjct1) throws AuthException { - throw new UnsupportedOperationException("Not supported yet."); - } - - public void cleanSubject(MessageInfo mi, Subject sbjct) throws AuthException { - throw new UnsupportedOperationException("Not supported yet."); - } - -} diff --git a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleServerAuthModule.java b/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleServerAuthModule.java deleted file mode 100644 index 2c2768b258b..00000000000 --- a/appserver/security/jaspic-provider-framework/src/test/java/test/com/sun/jaspic/config/SampleServerAuthModule.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package test.com.sun.jaspic.config; - -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.MessagePolicy; -import jakarta.security.auth.message.module.ServerAuthModule; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -/** - * - * @author Ron Monzillo - */ -public class SampleServerAuthModule implements ServerAuthModule { - - public void initialize(MessagePolicy mp, MessagePolicy mp1, CallbackHandler ch, Map map) throws AuthException { - } - - public Class[] getSupportedMessageTypes() { - return new Class[]{HttpServletRequest.class, HttpServletResponse.class}; - } - - public AuthStatus validateRequest(MessageInfo mi, Subject sbjct, Subject sbjct1) throws AuthException { - return AuthStatus.SUCCESS; - } - - public AuthStatus secureResponse(MessageInfo mi, Subject sbjct) throws AuthException { - return AuthStatus.SEND_SUCCESS; - } - - public void cleanSubject(MessageInfo mi, Subject sbjct) throws AuthException { - } -} - diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java index 006e6423399..df85a30a6d6 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java @@ -95,7 +95,6 @@ import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServletServices; import com.sun.enterprise.security.web.integration.WebPrincipal; -import com.sun.jaspic.config.servlet.HttpMessageInfo; import com.sun.logging.LogDomains; import com.sun.web.security.HttpRequestWrapper; import com.sun.web.security.HttpResponseWrapper; @@ -104,6 +103,7 @@ import fish.payara.notification.requesttracing.RequestTraceSpan; import fish.payara.nucleus.requesttracing.RequestTracingService; +import org.glassfish.epicyro.config.servlet.HttpMessageInfo; public class JaspicRealm { diff --git a/appserver/security/webservices.security/pom.xml b/appserver/security/webservices.security/pom.xml index a14995ec401..04749472473 100644 --- a/appserver/security/webservices.security/pom.xml +++ b/appserver/security/webservices.security/pom.xml @@ -52,7 +52,7 @@ webservices.security glassfish-jar - WebServices Security and JSR 196 implementation + WebServices Security and Jakarta Authentication implementation diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/BaseAuthConfig.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/BaseAuthConfig.java deleted file mode 100644 index 596cf0164a0..00000000000 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/BaseAuthConfig.java +++ /dev/null @@ -1,608 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth.jaspic.provider; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.xml.namespace.QName; -import jakarta.xml.soap.MimeHeaders; -import jakarta.xml.soap.Name; -import jakarta.xml.soap.SOAPBody; -import jakarta.xml.soap.SOAPElement; -import jakarta.xml.soap.SOAPEnvelope; -import jakarta.xml.soap.SOAPException; -import jakarta.xml.soap.SOAPMessage; -import jakarta.xml.soap.SOAPPart; -import jakarta.xml.ws.handler.MessageContext; -import jakarta.xml.ws.handler.soap.SOAPMessageContext; - -import com.sun.enterprise.deployment.MethodDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; -import com.sun.enterprise.deployment.runtime.common.ProtectionDescriptor; -import com.sun.enterprise.security.jauth.AuthPolicy; -import com.sun.enterprise.security.webservices.LogUtils; - -/** - * This class is the container's base interface to the AuthConfig subsystem to get AuthContext - * objects on which to invoke message layer authentication providers. It is not intended to be layer - * or web services specific (see getMechanisms method at end). The ServerAuthConfig and - * ClientAuthConfig classes extend this class. - */ -public class BaseAuthConfig { - - private static final Logger logger = LogUtils.getLogger(); - - private Object defaultContext_; - - // holds protected msd that applies to all methods (if there is one) - private MessageSecurityDescriptor superMSD_; - private int superIndex_; - - private ArrayList contexts_; - - private List messageSecurityDescriptors_; - - private ArrayList contextsForOpcodes_; - - private HashMap contextsForOpNames_; - - private boolean onePolicy_; - - private final Object contextLock = new Object(); - - private ExplicitNull explicitNull = new ExplicitNull(); - - protected BaseAuthConfig(Object context) { - - defaultContext_ = context; - superMSD_ = null; - superIndex_ = -1; - - messageSecurityDescriptors_ = null; - contexts_ = null; - contextsForOpcodes_ = null; - contextsForOpNames_ = null; - - onePolicy_ = true; - - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: New BAC defaultContext: {0}", defaultContext_); - } - } - - protected BaseAuthConfig(List descriptors, ArrayList authContexts) { - - defaultContext_ = null; - superMSD_ = null; - superIndex_ = -1; - - messageSecurityDescriptors_ = descriptors; - contexts_ = authContexts; - contextsForOpcodes_ = null; - contextsForOpNames_ = null; - - onePolicy_ = true; - - for (int i = 0; i < descriptors.size(); i++) { - - MessageSecurityDescriptor msd = (MessageSecurityDescriptor) descriptors.get(i); - - // determine if all the different messageSecurityDesriptors have the - // same policy which will help us interpret the effective policy if - // we cannot determine the opcode of a request at runtime. - - for (int j = 0; j < descriptors.size(); j++) { - if (j != i && !policiesAreEqual(msd, ((MessageSecurityDescriptor) descriptors.get(j)))) { - onePolicy_ = false; - } - } - } - - for (int i = 0; defaultContext_ == null && i < descriptors.size(); i++) { - - MessageSecurityDescriptor msd = (MessageSecurityDescriptor) descriptors.get(i); - - AuthPolicy requestPolicy = getAuthPolicy(msd.getRequestProtectionDescriptor()); - AuthPolicy responsePolicy = getAuthPolicy(msd.getResponseProtectionDescriptor()); - - boolean noProtection = (!requestPolicy.authRequired() && !responsePolicy.authRequired()); - - // if there is one policy, and it is null set the associated context as the - // defaultContext used for all messages. - if (i == 0 && onePolicy_ && noProtection) { - defaultContext_ = explicitNull; - break; - } - - List mDs = msd.getMessageDescriptors(); - - for (int j = 0; mDs != null && j < mDs.size(); j++) { - - MessageDescriptor mD = (MessageDescriptor) mDs.get(j); - MethodDescriptor methD = mD.getMethodDescriptor(); - - // if any msd covers all methods and operations. - if ((mD.getOperationName() == null && methD == null) || (methD != null && methD.getStyle() == 1)) { - - if (onePolicy_) { - // if there is only one policy make it the default. - defaultContext_ = contexts_.get(i); - if (defaultContext_ == null) { - defaultContext_ = explicitNull; - } - break; - } else if (superIndex_ == -1) { - // if it has a noProtection policy make it the default. - if (noProtection) { - defaultContext_ = explicitNull; - } else { - superIndex_ = i; - } - } else if (!policiesAreEqual(msd, ((MessageSecurityDescriptor) descriptors.get(superIndex_)))) { - // if there are conflicting policies that cover all methods - // set the default policy to noProtection - defaultContext_ = explicitNull; - superIndex_ = -1; - break; - } - } - } - } - // if there is protected policy that applies to all methods remember the descriptor. - // Note that the corresponding policy is not null, and thus it is not the default. - // wherever there is a conflicting policy the effective policy will be noProtection. - if (superIndex_ >= 0) { - superMSD_ = (MessageSecurityDescriptor) descriptors.get(superIndex_); - } - - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: new BAC defaultContext_: {0} superMSD index: {1} onePolicy_: {2}", - new Object[] { defaultContext_, superIndex_, onePolicy_ }); - } - } - - protected static AuthPolicy getAuthPolicy(ProtectionDescriptor pd) { - int sourceAuthType = AuthPolicy.SOURCE_AUTH_NONE; - boolean recipientAuth = false; - boolean beforeContent = false; - if (pd != null) { - String source = pd.getAttributeValue(ProtectionDescriptor.AUTH_SOURCE); - if (source != null) { - if (source.equals(AuthPolicy.SENDER)) { - sourceAuthType = AuthPolicy.SOURCE_AUTH_SENDER; - } else if (source.equals(AuthPolicy.CONTENT)) { - sourceAuthType = AuthPolicy.SOURCE_AUTH_CONTENT; - } - } - String recipient = pd.getAttributeValue(ProtectionDescriptor.AUTH_RECIPIENT); - if (recipient != null) { - recipientAuth = true; - if (recipient.equals(AuthPolicy.BEFORE_CONTENT)) { - beforeContent = true; - } else if (recipient.equals(AuthPolicy.AFTER_CONTENT)) { - beforeContent = false; - } - } - } - - return new AuthPolicy(sourceAuthType, recipientAuth, beforeContent); - } - - private static boolean isMatchingMSD(MethodDescriptor targetMD, MessageSecurityDescriptor mSD) { - List messageDescriptors = mSD.getMessageDescriptors(); - if (messageDescriptors.isEmpty()) { - // If this happens the deployment descriptor is invalid. - // - // Unfortunately the deployment system does not catch such problems. - // This case will be treated the same as if there was an empty message - // element, and the deployment will be allowed to succeed. - return true; - } - - for (int i = 0; i < messageDescriptors.size(); i++) { - MessageDescriptor nextMD = (MessageDescriptor) messageDescriptors.get(i); - MethodDescriptor mD = nextMD.getMethodDescriptor(); - String opName = nextMD.getOperationName(); - - if (opName == null && (mD == null || mD.implies(targetMD))) { - return true; - } - } - - return false; - } - - private static boolean policiesAreEqual(MessageSecurityDescriptor reference, MessageSecurityDescriptor other) { - if (!getAuthPolicy(reference.getRequestProtectionDescriptor()).equals(getAuthPolicy(other.getRequestProtectionDescriptor())) || - - !getAuthPolicy(reference.getResponseProtectionDescriptor()) - .equals(getAuthPolicy(other.getResponseProtectionDescriptor()))) { - - return false; - } - return true; - } - - /* - * When method argument is null, returns the default AC if there is one, or the onePolicy shared by - * all methods if there is one, or throws an error. method is called with null argument when the - * method cannot be determined (e.g. when the message is encrypted) - */ - private Object getContextForMethod(Method m) { - Object rvalue = null; - synchronized (contextLock) { - if (defaultContext_ != null) { - rvalue = defaultContext_; - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForMethod returning default_context: {0}", rvalue); - } - return rvalue; - } - } - if (m != null) { - int match = -1; - MethodDescriptor targetMD = new MethodDescriptor(m); - for (int i = 0; i < messageSecurityDescriptors_.size(); i++) { - if (isMatchingMSD(targetMD, (MessageSecurityDescriptor) messageSecurityDescriptors_.get(i))) { - if (match < 0) { - match = i; - } else if (!policiesAreEqual((MessageSecurityDescriptor) messageSecurityDescriptors_.get(match), - (MessageSecurityDescriptor) messageSecurityDescriptors_.get(i))) { - - // set to unprotected because of conflicting policies - - rvalue = explicitNull; - match = -1; - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForMethod detected conflicting policies: {0}.{1}", new Object[] { match, i }); - } - break; - } - } - } - if (match >= 0) { - rvalue = contexts_.get(match); - if (rvalue == null) { - rvalue = explicitNull; - } - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForMethod returning matched context: {0}", rvalue); - } - } - } else if (onePolicy_ && contexts_.size() > 0) { - // ISSUE: since the method is undefined we will not be - // able to tell if the defined policy covers this method. - // We will be optimistic and try the policy, because - // the server will reject the call if the method is not - // covered by the policy. - // If the policy is not null, there remains a problem at the - // client on the response side, as it is possible that the - // client will enforce the wrong policy on the response. - // For this reason, messages in sun-application-client.xml - // should be keyed by operation-name. - - rvalue = contexts_.get(0); - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForMethod resorting to first context: {0}", rvalue); - } - - } else { - if (logger.isLoggable(Level.FINE)) { - logger.fine("WSS: Unable to select policy for SOAP Message"); - } - throw new RuntimeException("Unable to select policy for Message"); - } - return rvalue; - } - - private static String getOpName(SOAPMessage message) { - - String rvalue = null; - - // first look for a SOAPAction header. - // this is what .net uses to identify the operation - - MimeHeaders headers = message.getMimeHeaders(); - if (headers != null) { - String[] actions = headers.getHeader("SOAPAction"); - if (actions != null && actions.length > 0) { - rvalue = actions[0]; - if (rvalue != null && rvalue.equals("\"\"")) { - rvalue = null; - } - } - } - - // if that doesn't work then we default to trying the name - // of the first child element of the SOAP envelope. - - if (rvalue == null) { - Name name = getName(message); - if (name != null) { - rvalue = name.getLocalName(); - } - } - - return rvalue; - } - - private static String getOpName(SOAPMessageContext soapMC) { - - String rvalue; - - // first look for a the property value in the context - QName qName = (QName) soapMC.get(MessageContext.WSDL_OPERATION); - if (qName != null) { - rvalue = qName.getLocalPart(); - } else { - rvalue = getOpName(soapMC.getMessage()); - } - - return rvalue; - } - - private Object getContextForOpName(String operation) { - - synchronized (contextLock) { - if (contextsForOpNames_ == null) { - - // one time initialization of the opName to authContext array. - - contextsForOpNames_ = new HashMap(); - for (int i = 0; messageSecurityDescriptors_ != null && i < messageSecurityDescriptors_.size(); i++) { - - MessageSecurityDescriptor mSD = (MessageSecurityDescriptor) messageSecurityDescriptors_.get(i); - - List mDs = mSD.getMessageDescriptors(); - - for (int j = 0; mDs != null && j < mDs.size(); j++) { - - MessageDescriptor mD = (MessageDescriptor) mDs.get(j); - String opName = mD.getOperationName(); - - if (opName != null) { - - if (contextsForOpNames_.containsKey(opName)) { - - Integer k = (Integer) contextsForOpNames_.get(opName); - if (k != null) { - - MessageSecurityDescriptor other = (MessageSecurityDescriptor) messageSecurityDescriptors_ - .get(k.intValue()); - - // set to null if different policies on operation - - if (!policiesAreEqual(mSD, other)) { - contextsForOpNames_.put(opName, null); - } - } - } else if (superMSD_ != null && !policiesAreEqual(mSD, superMSD_)) { - // set to null if operation policy differs from superPolicy - contextsForOpNames_.put(opName, null); - } else { - contextsForOpNames_.put(opName, Integer.valueOf(i)); - } - } - } - } - } - } - - Object rvalue = null; - if (operation != null) { - if (contextsForOpNames_.containsKey(operation)) { - Integer k = (Integer) contextsForOpNames_.get(operation); - if (k != null) { - rvalue = contexts_.get(k.intValue()); - } - } else if (superIndex_ >= 0) { - // if there is a msb that matches all methods, use the - // associatedContext - rvalue = contexts_.get(superIndex_); - } - - if (rvalue == null) { - // else return explicitNull under the assumption - // that methodName was known, and no match was found - rvalue = explicitNull; - } - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: ForOpName={0} context: {1}", new Object[] { operation, rvalue }); - } - } - return rvalue; - } - - // DO NOT CALL THIS ON THE SERVER SIDE, as it will return a null - // context if there is no default context and there isn't a message - // element defined with the corresponding operation name (even though the - // corresponding method may be protected). - // - // This method is intended to be used by clients where it serves as a - // work-around for not being able to map the message to the method (due - // to lack of access to a streaming handler equivalent). - // - // This method will not be called when the handler argument passed in - // a call to getContext or getContextForOpCode is not null. - // Thus, server-side calls to these methods must pass a non-null - // handler argument. - - private Object getContextForMessage(SOAPMessage message) { - - String opName = getOpName(message); - - Object rvalue = getContextForOpName(opName); - if (rvalue == null) { - - // opName is not mapped or msg body is encrypted, and the best - // we can do is try to return a policy that applies to all - // operations, if there is one. - - rvalue = getContextForMethod(null); - - } - return rvalue; - } - - // used by jaxws system handler delegates and handlers - protected Object getContext(SOAPMessageContext soapMC) { - - Object rvalue = null; - - synchronized (contextLock) { - if (defaultContext_ != null) { - rvalue = defaultContext_; - } - } - - if (rvalue == null) { - - Method m = getMethod(soapMC); - String opName = null; - - if (m != null) { - rvalue = getContextForMethod(m); - } - - if (rvalue == null) { - opName = getOpName(soapMC); - if (opName != null) { - rvalue = getContextForOpName(opName); - } - } - - if (rvalue == null && (m == null || opName == null)) { - - // we were unable to determine either method or - // opName, so lets see if one policy applies to all - - rvalue = getContextForMethod(null); - } - } - - if (rvalue != null && rvalue instanceof ExplicitNull) { - rvalue = null; - } - - return rvalue; - } - - private static Name getName(SOAPMessage message) { - Name rvalue = null; - SOAPPart soap = message.getSOAPPart(); - if (soap != null) { - try { - SOAPEnvelope envelope = soap.getEnvelope(); - if (envelope != null) { - SOAPBody body = envelope.getBody(); - if (body != null) { - Iterator it = body.getChildElements(); - while (it.hasNext()) { - Object o = it.next(); - if (o instanceof SOAPElement) { - rvalue = ((SOAPElement) o).getElementName(); - break; - } - } - } - } - } catch (SOAPException se) { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "WSS: Unable to get SOAP envelope", se); - } - } - } - - return rvalue; - } - - public static Method getMethod(SOAPMessageContext soapMC) { - - // It should never come here - return null; - } - - // each instance of AuthConfig maps to one provider - // configuration, either via a message-security-binding, or a default - // provider-config. - - // mechanisms are temporarily encapsulated here, until a method that - // returns the list of supported mechanisms is added to - // jauth.ServerAuthContext and jauth.ClientAuthContext. - public QName[] getMechanisms() { - return mechanisms; - } - - // WSS security header QName - private static QName mechanisms[] = new QName[] { - new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", "wsse") }; - - // internal class used to differentiate not protected from policy undefined or - // not determined. - - static class ExplicitNull { - - ExplicitNull() { - } - - @Override - public boolean equals(Object other) { - return (other != null && other instanceof ExplicitNull ? true : false); - } - - @Override - public int hashCode() { - return super.hashCode(); - } - - @Override - public String toString() { - return "ExplicitNull"; - } - } -} diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ClientAuthConfig.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ClientAuthConfig.java deleted file mode 100644 index bcd28dc59e1..00000000000 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ClientAuthConfig.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth.jaspic.provider; - -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; - -import java.util.ArrayList; -import java.util.List; - -import javax.security.auth.callback.CallbackHandler; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; -import com.sun.enterprise.security.jauth.AuthConfig; -import com.sun.enterprise.security.jauth.AuthException; -import com.sun.enterprise.security.jauth.AuthPolicy; -import com.sun.enterprise.security.jauth.ClientAuthContext; - -/** - * This class is the client container's interface to the AuthConfig subsystem to get AuthContext objects on which to - * invoke message layer authentication providers. It is not intended to be layer or web services specific (see - * getMechanisms method at end). - */ -public class ClientAuthConfig extends BaseAuthConfig { - - private ClientAuthConfig(ClientAuthContext defaultContext) { - super(defaultContext); - } - - private ClientAuthConfig(List descriptors, ArrayList authContexts) { - super(descriptors, authContexts); - } - - public static ClientAuthConfig getConfig(String authLayer, MessageSecurityBindingDescriptor binding, CallbackHandler cbh) throws AuthException { - ClientAuthConfig rvalue = null; - String provider = null; - List descriptors = null; - ClientAuthContext defaultContext = null; - if (binding != null) { - String layer = binding.getAttributeValue(AUTH_LAYER); - if (authLayer != null && layer.equals(authLayer)) { - provider = binding.getAttributeValue(PROVIDER_ID); - descriptors = binding.getMessageSecurityDescriptors(); - } - } - - if (descriptors == null || descriptors.size() == 0) { - defaultContext = getAuthContext(authLayer, provider, null, null, cbh); - if (defaultContext != null) { - rvalue = new ClientAuthConfig(defaultContext); - } - } else { - boolean hasPolicy = false; - ArrayList authContexts = new ArrayList(); - for (int i = 0; i < descriptors.size(); i++) { - MessageSecurityDescriptor msd = (MessageSecurityDescriptor) descriptors.get(i); - AuthPolicy requestPolicy = getAuthPolicy(msd.getRequestProtectionDescriptor()); - AuthPolicy responsePolicy = getAuthPolicy(msd.getResponseProtectionDescriptor()); - if (requestPolicy.authRequired() || responsePolicy.authRequired()) { - authContexts.add(getAuthContext(authLayer, provider, requestPolicy, responsePolicy, cbh)); - hasPolicy = true; - } else { - authContexts.add(null); - } - } - if (hasPolicy) { - rvalue = new ClientAuthConfig(descriptors, authContexts); - } - } - return rvalue; - } - - private static ClientAuthContext getAuthContext(String layer, String provider, AuthPolicy requestPolicy, AuthPolicy responsePolicy, CallbackHandler cbh) - throws AuthException { - AuthConfig authConfig = AuthConfig.getAuthConfig(); - return authConfig.getClientAuthContext(layer, provider, requestPolicy, responsePolicy, cbh); - } - - public ClientAuthContext getAuthContext(jakarta.xml.ws.handler.soap.SOAPMessageContext context) { - return (ClientAuthContext) getContext(context); - } - -} diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/SOAPAuthParam.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/SOAPAuthParam.java index be151e2d84c..904439b87d9 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/SOAPAuthParam.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/SOAPAuthParam.java @@ -37,10 +37,9 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jauth.jaspic.provider; -import com.sun.enterprise.security.jauth.AuthParam; import java.util.Map; import java.util.HashMap; import jakarta.xml.soap.*; @@ -64,7 +63,7 @@ * * @version 1.12, 06/08/04 */ -public class SOAPAuthParam implements AuthParam { +public class SOAPAuthParam { private HashMap infoMap; diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ServerAuthConfig.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ServerAuthConfig.java deleted file mode 100644 index 7d760d4647c..00000000000 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/ServerAuthConfig.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jauth.jaspic.provider; - -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.AUTH_LAYER; -import static com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor.PROVIDER_ID; - -import java.util.ArrayList; -import java.util.List; - -import javax.security.auth.callback.CallbackHandler; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityDescriptor; -import com.sun.enterprise.security.jauth.AuthConfig; -import com.sun.enterprise.security.jauth.AuthException; -import com.sun.enterprise.security.jauth.AuthPolicy; -import com.sun.enterprise.security.jauth.ServerAuthContext; - -/** - * This class is the client container's interface to the AuthConfig subsystem to get AuthContext objects on which to - * invoke message layer authentication providers. It is not intended to be layer or web services specific (see - * getMechanisms method at end). - */ -public class ServerAuthConfig extends BaseAuthConfig { - - private ServerAuthConfig(ServerAuthContext defaultContext) { - super(defaultContext); - } - - private ServerAuthConfig(List descriptors, ArrayList authContexts) { - super(descriptors, authContexts); - } - - public static ServerAuthConfig getConfig(String authLayer, MessageSecurityBindingDescriptor binding, CallbackHandler cbh) throws AuthException { - ServerAuthConfig rvalue = null; - String provider = null; - List descriptors = null; - ServerAuthContext defaultContext = null; - if (binding != null) { - String layer = binding.getAttributeValue(AUTH_LAYER); - if (authLayer != null && layer.equals(authLayer)) { - provider = binding.getAttributeValue(PROVIDER_ID); - descriptors = binding.getMessageSecurityDescriptors(); - } - } - - if (descriptors == null || descriptors.size() == 0) { - defaultContext = getAuthContext(authLayer, provider, null, null, cbh); - if (defaultContext != null) { - rvalue = new ServerAuthConfig(defaultContext); - } - } else { - boolean hasPolicy = false; - ArrayList authContexts = new ArrayList(); - for (int i = 0; i < descriptors.size(); i++) { - MessageSecurityDescriptor msd = (MessageSecurityDescriptor) descriptors.get(i); - AuthPolicy requestPolicy = getAuthPolicy(msd.getRequestProtectionDescriptor()); - AuthPolicy responsePolicy = getAuthPolicy(msd.getResponseProtectionDescriptor()); - if (requestPolicy.authRequired() || responsePolicy.authRequired()) { - authContexts.add(getAuthContext(authLayer, provider, requestPolicy, responsePolicy, cbh)); - hasPolicy = true; - } else { - authContexts.add(null); - } - } - - if (hasPolicy) { - rvalue = new ServerAuthConfig(descriptors, authContexts); - } - } - - return rvalue; - } - - private static ServerAuthContext getAuthContext(String layer, String provider, AuthPolicy requestPolicy, AuthPolicy responsePolicy, CallbackHandler cbh) throws AuthException { - AuthConfig authConfig = AuthConfig.getAuthConfig(); - return authConfig.getServerAuthContext(layer, provider, requestPolicy, responsePolicy, cbh); - } - - public ServerAuthContext getAuthContext(jakarta.xml.ws.handler.soap.SOAPMessageContext context) { - return (ServerAuthContext) getContext(context); - } - -} diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java similarity index 99% rename from appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java rename to appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java index 08b59322298..1397eb3e167 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/PipeHelper.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java @@ -111,7 +111,7 @@ import com.sun.xml.ws.api.model.wsdl.WSDLPort; import com.sun.xml.ws.api.server.WSEndpoint; -public class PipeHelper extends PayaraEpicyroServices { +public class SoapAuthenticationService extends PayaraEpicyroServices { protected static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(PipeConstants.class); @@ -122,7 +122,7 @@ public class PipeHelper extends PayaraEpicyroServices { private InvocationManager invManager; private EJBPolicyContextDelegate ejbDelegate; - public PipeHelper(String layer, Map properties, CallbackHandler callbackHandler) { + public SoapAuthenticationService(String layer, Map properties, CallbackHandler callbackHandler) { init(layer, getAppCtxt(properties), properties, callbackHandler, (RegistrationWrapperRemover) Globals.get(WebServicesDelegate.class)); isEjbEndpoint = processSunDeploymentDescriptor(); diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipe.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipe.java index b9b43c0bc7a..ea5adb0e1e8 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipe.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipe.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static com.sun.enterprise.security.webservices.PipeConstants.SECURITY_PIPE; @@ -58,7 +58,7 @@ import com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; -import com.sun.enterprise.security.jauth.jaspic.provider.config.PipeHelper; +import com.sun.enterprise.security.jauth.jaspic.provider.config.SoapAuthenticationService; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.xml.ws.api.message.Message; import com.sun.xml.ws.api.message.Packet; @@ -74,7 +74,7 @@ */ public class ClientSecurityPipe extends AbstractFilterPipeImpl implements SecureConversationInitiator { - protected PipeHelper helper; + protected SoapAuthenticationService helper; protected static final Logger _logger = LogUtils.getLogger(); @@ -93,7 +93,7 @@ public ClientSecurityPipe(Map props, Pipe next) { props.put(WSDL_SERVICE, wsdlModel.getOwner().getName()); } - helper = new PipeHelper(SOAP_LAYER, props, null); + helper = new SoapAuthenticationService(SOAP_LAYER, props, null); } protected ClientSecurityPipe(ClientSecurityPipe that, PipeCloner cloner) { @@ -125,7 +125,7 @@ public final Pipe copy(PipeCloner cloner) { return new ClientSecurityPipe(this, cloner); } - public PipeHelper getPipeHelper() { + public SoapAuthenticationService getPipeHelper() { return helper; } @@ -226,7 +226,7 @@ private static Subject getClientSubject(Packet p) { if (s == null) { - s = PipeHelper.getClientSubject(); + s = SoapAuthenticationService.getClientSubject(); if (p != null) { p.invocationProperties.put(PipeConstants.CLIENT_SUBJECT, s); diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipeCreator.java similarity index 79% rename from appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java rename to appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipeCreator.java index f06686cfe72..7a360ee99b4 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientPipeCreator.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityPipeCreator.java @@ -60,49 +60,49 @@ import com.sun.xml.ws.policy.PolicyMap; /** - * This is used by WSClientContainer to return proper JASPIC 196 security pipe to the + * This is used by WSClientContainer to return proper Jakarta Authentication security pipe to the * StandAlonePipeAssembler and TangoPipeAssembler */ -public class ClientPipeCreator extends ClientPipelineHook { +public class ClientSecurityPipeCreator extends ClientPipelineHook { - private ServiceReferenceDescriptor svcRef = null; + private ServiceReferenceDescriptor serviceReferenceDescriptor = null; - public ClientPipeCreator() { + public ClientSecurityPipeCreator() { } - public ClientPipeCreator(ServiceReferenceDescriptor ref) { - svcRef = ref; + public ClientSecurityPipeCreator(ServiceReferenceDescriptor ref) { + serviceReferenceDescriptor = ref; } @Override public Pipe createSecurityPipe(PolicyMap map, ClientPipeAssemblerContext ctxt, Pipe tail) { - HashMap props = new HashMap<>(); + HashMap properties = new HashMap<>(); - props.put(POLICY, map); - props.put(WSDL_MODEL, ctxt.getWsdlModel()); - props.put(SERVICE, ctxt.getService()); - props.put(BINDING, ctxt.getBinding()); - props.put(ENDPOINT_ADDRESS, ctxt.getAddress()); - if (svcRef != null) { - props.put(SERVICE_REF, svcRef); + properties.put(POLICY, map); + properties.put(WSDL_MODEL, ctxt.getWsdlModel()); + properties.put(SERVICE, ctxt.getService()); + properties.put(BINDING, ctxt.getBinding()); + properties.put(ENDPOINT_ADDRESS, ctxt.getAddress()); + if (serviceReferenceDescriptor != null) { + properties.put(SERVICE_REF, serviceReferenceDescriptor); } - props.put(NEXT_PIPE, tail); - props.put(CONTAINER, ctxt.getContainer()); - props.put(ASSEMBLER_CONTEXT, ctxt); - ClientSecurityPipe ret = new ClientSecurityPipe(props, tail); + properties.put(NEXT_PIPE, tail); + properties.put(CONTAINER, ctxt.getContainer()); + properties.put(ASSEMBLER_CONTEXT, ctxt); + ClientSecurityPipe clientSecurityPipe = new ClientSecurityPipe(properties, tail); - AuthConfigRegistrationWrapper listenerWrapper = ClientPipeCloser.getInstance().lookupListenerWrapper(svcRef); + AuthConfigRegistrationWrapper listenerWrapper = ClientPipeCloser.getInstance().lookupListenerWrapper(serviceReferenceDescriptor); // there is a 1-1 mapping between Service_Ref and a ListenerWrapper if (listenerWrapper != null) { // override the listener that was created by the ConfigHelper CTOR :if one was already registered listenerWrapper.incrementReference(); - ret.getPipeHelper().setRegistrationWrapper(listenerWrapper); + clientSecurityPipe.getPipeHelper().setRegistrationWrapper(listenerWrapper); } else { // register a new listener - ClientPipeCloser.getInstance().registerListenerWrapper(svcRef, ret.getPipeHelper().getRegistrationWrapper()); + ClientPipeCloser.getInstance().registerListenerWrapper(serviceReferenceDescriptor, clientSecurityPipe.getPipeHelper().getRegistrationWrapper()); } - return ret; + return clientSecurityPipe; } // @Override diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityTube.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityTube.java index d9b55359829..197f8cffd11 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityTube.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ClientSecurityTube.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import static com.sun.enterprise.security.webservices.PipeConstants.SECURITY_TOKEN; @@ -55,7 +55,7 @@ import com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; -import com.sun.enterprise.security.jauth.jaspic.provider.config.PipeHelper; +import com.sun.enterprise.security.jauth.jaspic.provider.config.SoapAuthenticationService; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.xml.ws.api.message.Message; import com.sun.xml.ws.api.message.Packet; @@ -73,7 +73,7 @@ */ public class ClientSecurityTube extends AbstractFilterTubeImpl implements SecureConversationInitiator { - protected PipeHelper helper; + protected SoapAuthenticationService helper; protected static final Logger _logger = LogUtils.getLogger(); @@ -94,7 +94,7 @@ public ClientSecurityTube(Map props, Tube next) { if (wsdlModel != null) { props.put(PipeConstants.WSDL_SERVICE, wsdlModel.getOwner().getName()); } - this.helper = new PipeHelper(PipeConstants.SOAP_LAYER, props, null); + this.helper = new SoapAuthenticationService(PipeConstants.SOAP_LAYER, props, null); } @@ -203,7 +203,7 @@ private static Subject getClientSubject(Packet p) { if (s == null) { - s = PipeHelper.getClientSubject(); + s = SoapAuthenticationService.getClientSubject(); if (p != null) { p.invocationProperties.put(PipeConstants.CLIENT_SUBJECT, s); diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityPipe.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityPipe.java index d716e2b1033..5d029d927d7 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityPipe.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityPipe.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import java.security.PrivilegedActionException; @@ -54,7 +54,7 @@ import com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; -import com.sun.enterprise.security.jauth.jaspic.provider.config.PipeHelper; +import com.sun.enterprise.security.jauth.jaspic.provider.config.SoapAuthenticationService; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.xml.ws.api.message.Packet; import com.sun.xml.ws.api.pipe.Pipe; @@ -72,14 +72,14 @@ public class CommonServerSecurityPipe extends AbstractFilterPipeImpl { private final boolean isHttpBinding; - private PipeHelper helper; + private SoapAuthenticationService helper; private static final String WSIT_SERVER_AUTH_CONTEXT = "com.sun.xml.wss.provider.wsit.WSITServerAuthContext"; public CommonServerSecurityPipe(Map props, final Pipe next, boolean isHttpBinding) { super(next); props.put(PipeConstants.SECURITY_PIPE, this); - this.helper = new PipeHelper(PipeConstants.SOAP_LAYER, props, null); + this.helper = new SoapAuthenticationService(PipeConstants.SOAP_LAYER, props, null); this.isHttpBinding = isHttpBinding; } @@ -274,7 +274,7 @@ private static Subject getClientSubject(Packet p) { s = (Subject) p.invocationProperties.get(PipeConstants.CLIENT_SUBJECT); } if (s == null) { - s = PipeHelper.getClientSubject(); + s = SoapAuthenticationService.getClientSubject(); if (p != null) { p.invocationProperties.put(PipeConstants.CLIENT_SUBJECT, s); } diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityTube.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityTube.java index 2ad5346a2cf..dd3cd334677 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityTube.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/CommonServerSecurityTube.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import java.security.PrivilegedActionException; @@ -54,7 +54,7 @@ import com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; -import com.sun.enterprise.security.jauth.jaspic.provider.config.PipeHelper; +import com.sun.enterprise.security.jauth.jaspic.provider.config.SoapAuthenticationService; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.xml.ws.api.message.Packet; import com.sun.xml.ws.api.pipe.NextAction; @@ -72,7 +72,7 @@ public class CommonServerSecurityTube extends AbstractFilterTubeImpl { protected static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(CommonServerSecurityTube.class); private final boolean isHttpBinding; - private PipeHelper helper; + private SoapAuthenticationService helper; // Introduced during Pipe to Tube conversion private ServerAuthContext sAC = null; @@ -82,7 +82,7 @@ public class CommonServerSecurityTube extends AbstractFilterTubeImpl { public CommonServerSecurityTube(Map props, final Tube next, boolean isHttpBinding) { super(next); props.put(PipeConstants.SECURITY_PIPE, this); - this.helper = new PipeHelper(PipeConstants.SOAP_LAYER, props, null); + this.helper = new SoapAuthenticationService(PipeConstants.SOAP_LAYER, props, null); this.isHttpBinding = isHttpBinding; } @@ -270,7 +270,7 @@ private static Subject getClientSubject(Packet p) { s = (Subject) p.invocationProperties.get(PipeConstants.CLIENT_SUBJECT); } if (s == null) { - s = PipeHelper.getClientSubject(); + s = SoapAuthenticationService.getClientSubject(); if (p != null) { p.invocationProperties.put(PipeConstants.CLIENT_SUBJECT, s); } diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java index 4b52eaa7c82..344b64cb406 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java @@ -42,26 +42,24 @@ // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.security.webservices; -import static com.sun.enterprise.security.webservices.LogUtils.BASIC_AUTH_ERROR; -import static com.sun.enterprise.security.webservices.LogUtils.CLIENT_CERT_ERROR; -import static com.sun.enterprise.security.webservices.LogUtils.EJB_SEC_CONFIG_FAILURE; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; -import static org.apache.catalina.Globals.CERTIFICATES_ATTR; -import static org.apache.catalina.Globals.SSL_CERTIFICATE_ATTR; - -import java.lang.ref.WeakReference; -import java.security.Principal; -import java.security.cert.X509Certificate; -import java.util.logging.Logger; - +import com.sun.enterprise.deployment.ServiceReferenceDescriptor; +import com.sun.enterprise.deployment.WebServiceEndpoint; +import com.sun.enterprise.security.SecurityContext; +import com.sun.enterprise.security.ee.audit.AppServerAuditManager; +import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; +import com.sun.enterprise.security.web.integration.WebPrincipal; +import com.sun.enterprise.web.WebModule; +import com.sun.web.security.RealmAdapter; +import com.sun.xml.ws.assembler.metro.dev.ClientPipelineHook; import jakarta.inject.Inject; import jakarta.inject.Singleton; import jakarta.security.jacc.PolicyContext; import jakarta.servlet.http.HttpServletRequest; import jakarta.xml.soap.SOAPMessage; - +import java.lang.ref.WeakReference; +import java.security.Principal; +import java.security.cert.X509Certificate; +import java.util.logging.Logger; import org.apache.catalina.util.Base64; import org.glassfish.security.common.UserNameAndPassword; import org.glassfish.webservices.EjbRuntimeEndpointInfo; @@ -72,18 +70,12 @@ import org.glassfish.webservices.monitoring.WebServiceEngineImpl; import org.jvnet.hk2.annotations.Service; -import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.enterprise.deployment.WebServiceEndpoint; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.security.SecurityContext; -import com.sun.enterprise.security.ee.audit.AppServerAuditManager; -import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; -import com.sun.enterprise.security.jauth.AuthConfig; -import com.sun.enterprise.security.jauth.jaspic.provider.ServerAuthConfig; -import com.sun.enterprise.security.web.integration.WebPrincipal; -import com.sun.enterprise.web.WebModule; -import com.sun.web.security.RealmAdapter; -import com.sun.xml.ws.assembler.metro.dev.ClientPipelineHook; +import static com.sun.enterprise.security.webservices.LogUtils.BASIC_AUTH_ERROR; +import static com.sun.enterprise.security.webservices.LogUtils.CLIENT_CERT_ERROR; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.WARNING; +import static org.apache.catalina.Globals.CERTIFICATES_ATTR; +import static org.apache.catalina.Globals.SSL_CERTIFICATE_ATTR; /** * @@ -102,18 +94,6 @@ public class SecurityServiceImpl implements SecurityService { @Inject private AppServerAuditManager auditManager; - @Override - public Object mergeSOAPMessageSecurityPolicies(MessageSecurityBindingDescriptor desc) { - try { - // Merge message security policy from domain.xml and sun-specific - // deployment descriptor - return ServerAuthConfig.getConfig(AuthConfig.SOAP, desc, null); - } catch (Exception ae) { - _logger.log(SEVERE, EJB_SEC_CONFIG_FAILURE, ae); - } - return null; - } - @Override public boolean doSecurity(HttpServletRequest hreq, EjbRuntimeEndpointInfo epInfo, String realmName, WebServiceContextImpl context) { // BUG2263 - Clear the value of UserPrincipal from previous request @@ -238,7 +218,7 @@ public void resetPolicyContext() { @Override public ClientPipelineHook getClientPipelineHook(ServiceReferenceDescriptor ref) { - return new ClientPipeCreator(ref); + return new ClientSecurityPipeCreator(ref); } diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/GFServerPipeCreator.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ServerSecurityPipeCreator.java similarity index 88% rename from appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/GFServerPipeCreator.java rename to appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ServerSecurityPipeCreator.java index 106dc22132f..a4302546834 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/GFServerPipeCreator.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/ServerSecurityPipeCreator.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; import java.util.HashMap; @@ -59,17 +59,17 @@ import com.sun.xml.wss.provider.wsit.PipeConstants; /** - * This is used by JAXWSContainer to return proper 196 security and app server monitoing pipes to + * This is used by JAXWSContainer to return proper Jakarta Authentication security and app server monitoing pipes to * the StandAlonePipeAssembler and TangoPipeAssembler */ @Service @Singleton -public class GFServerPipeCreator extends org.glassfish.webservices.ServerPipeCreator { +public class ServerSecurityPipeCreator extends org.glassfish.webservices.ServerPipeCreator { private static final String SECURITY_POLICY_NAMESPACE_URI_SUBMISSION = "http://schemas.xmlsoap.org/ws/2005/07/securitypolicy"; private static final String SECURITY_POLICY_NAMESPACE_URI_SPECVERSION = "http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702"; - public GFServerPipeCreator() { + public ServerSecurityPipeCreator() { super(); } @@ -81,20 +81,20 @@ public void init(WebServiceEndpoint ep) { @Override public Pipe createSecurityPipe(PolicyMap map, SEIModel sei, WSDLPort port, WSEndpoint owner, Pipe tail) { - HashMap props = new HashMap<>(); + HashMap properties = new HashMap<>(); - props.put(PipeConstants.POLICY, map); - props.put(PipeConstants.SEI_MODEL, sei); - props.put(PipeConstants.WSDL_MODEL, port); - props.put(PipeConstants.ENDPOINT, owner); - props.put(PipeConstants.SERVICE_ENDPOINT, endpoint); - props.put(PipeConstants.NEXT_PIPE, tail); - props.put(PipeConstants.CONTAINER, owner.getContainer()); + properties.put(PipeConstants.POLICY, map); + properties.put(PipeConstants.SEI_MODEL, sei); + properties.put(PipeConstants.WSDL_MODEL, port); + properties.put(PipeConstants.ENDPOINT, owner); + properties.put(PipeConstants.SERVICE_ENDPOINT, endpoint); + properties.put(PipeConstants.NEXT_PIPE, tail); + properties.put(PipeConstants.CONTAINER, owner.getContainer()); if (isSecurityEnabled(map, port)) { endpoint.setSecurePipeline(); } - return new CommonServerSecurityPipe(props, tail, isHttpBinding); + return new CommonServerSecurityPipe(properties, tail, isHttpBinding); } // @Override diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java index e0145fad991..85b7961082f 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java @@ -50,6 +50,7 @@ import javax.xml.namespace.QName; import jakarta.xml.soap.MimeHeaders; import jakarta.xml.soap.Name; +import jakarta.xml.soap.Node; import jakarta.xml.soap.SOAPBody; import jakarta.xml.soap.SOAPElement; import jakarta.xml.soap.SOAPEnvelope; @@ -64,7 +65,6 @@ import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; -import com.sun.enterprise.security.jauth.AuthParam; import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; import com.sun.enterprise.security.jauth.jaspic.provider.SOAPAuthParam; import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; @@ -144,12 +144,6 @@ public String getAuthContextID(MessageInfo messageInfo) { } - @Override - public AuthParam newSOAPAuthParam(MessageInfo messageInfo) { - return new SOAPAuthParam((SOAPMessage) messageInfo.getRequestMessage(), (SOAPMessage) messageInfo.getResponseMessage()); - - } - private String getOpName(SOAPMessage message) { if (message == null) { return null; @@ -193,11 +187,11 @@ private Name getName(SOAPMessage message) { if (envelope != null) { SOAPBody body = envelope.getBody(); if (body != null) { - Iterator it = body.getChildElements(); + Iterator it = body.getChildElements(); while (it.hasNext()) { - Object o = it.next(); - if (o instanceof SOAPElement) { - rvalue = ((SOAPElement) o).getElementName(); + Node node = it.next(); + if (node instanceof SOAPElement) { + rvalue = ((SOAPElement) node).getElementName(); break; } } @@ -211,21 +205,4 @@ private Name getName(SOAPMessage message) { } return rvalue; } - - @Override - public Object getSOAPMessage(ComponentInvocation inv) { - /* - * V3 commented getting this from EJBPolicyContextDelegate instead currently getting this from - * EjbPolicyContextDelegate which might be OK SOAPMessage soapMessage = null; MessageContext - * msgContext = inv.messageContext; - * - * if (msgContext != null) { if (msgContext instanceof SOAPMessageContext) { SOAPMessageContext smc - * = (SOAPMessageContext) msgContext; soapMessage = smc.getMessage(); } } else { soapMessage = - * inv.getSOAPMessage(); } - * - * return soapMessage; - */ - return null; - } - } diff --git a/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/SecurityService.java b/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/SecurityService.java index 0fa630f0343..bd9cc7ae766 100644 --- a/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/SecurityService.java +++ b/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/SecurityService.java @@ -37,17 +37,15 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package org.glassfish.webservices; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; import com.sun.enterprise.web.WebModule; import com.sun.xml.ws.assembler.metro.dev.ClientPipelineHook; import jakarta.servlet.http.HttpServletRequest; -import org.jvnet.hk2.annotations.Contract; - import java.security.Principal; +import org.jvnet.hk2.annotations.Contract; /** * @@ -55,9 +53,7 @@ */ @Contract public interface SecurityService { - - Object mergeSOAPMessageSecurityPolicies(MessageSecurityBindingDescriptor desc); - + boolean doSecurity(HttpServletRequest hreq, EjbRuntimeEndpointInfo ejbEndpoint, String realmName, WebServiceContextImpl context); Principal getUserPrincipal(boolean isWeb); diff --git a/core/core-bom/pom.xml b/core/core-bom/pom.xml index 303dec97362..fa8435c0d04 100644 --- a/core/core-bom/pom.xml +++ b/core/core-bom/pom.xml @@ -1,7 +1,7 @@ ../nucleus/flashlight/framework - - ../appserver/security/jaspic-provider-framework ../appserver/security/core-ee diff --git a/nucleus/admin/template/src/main/resources/config/server.policy b/nucleus/admin/template/src/main/resources/config/server.policy index 94de59288fc..78c3e6c92e8 100644 --- a/nucleus/admin/template/src/main/resources/config/server.policy +++ b/nucleus/admin/template/src/main/resources/config/server.policy @@ -119,6 +119,7 @@ grant { permission java.io.SerializablePermission "enableSubstitution"; permission java.security.SecurityPermission "getProperty.package.definition"; permission java.security.SecurityPermission "createPolicy.JavaPolicy"; + permission java.security.SecurityPermission "getProperty.authconfigprovider.factory.providers"; }; // Following grant block is only required by Connectors. If Connectors diff --git a/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java b/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java index e69de29bb2d..3d79278667d 100644 --- a/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java +++ b/nucleus/common/internal-api/src/main/java/fish/payara/internal/notification/EventLevel.java @@ -0,0 +1,85 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) [2024] Payara Foundation and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://github.com/payara/Payara/blob/main/LICENSE.txt + * See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at glassfish/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * The Payara Foundation designates this particular file as subject to the "Classpath" + * exception as provided by the Payara Foundation in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ + +package fish.payara.internal.notification; + +import java.util.function.BiPredicate; +import java.util.logging.Level; + +/** + * + */ +public enum EventLevel { + INFO(800), + WARNING(900), + SEVERE(1000); + + private final int severityLevel; + + public static EventLevel fromNameOrWarning (String name) { + try { + return EventLevel.valueOf(name.toUpperCase()); + } catch (Exception e) { + return WARNING; + } + } + + public static EventLevel fromLogLevel (Level level) { + if (level.intValue() <= INFO.severityLevel) { + return INFO; + } + if (level.intValue() <= WARNING.severityLevel) { + return WARNING; + } + return SEVERE; + } + + EventLevel (int severityLevel) { + this.severityLevel = severityLevel; + } + + public int getSeverityLevel () { + return severityLevel; + } + + public boolean compare (EventLevel other, BiPredicate predicate) { + return predicate.test(this.severityLevel, other.severityLevel); + } +} \ No newline at end of file diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java similarity index 99% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java rename to nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java index 10612bf5fdc..4071525d44d 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/PolicyLoader.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java @@ -38,11 +38,10 @@ * holder. */ // Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.ee.authorize; +package com.sun.enterprise.security; import com.sun.enterprise.config.serverbeans.JaccProvider; import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.security.SecurityLoggerInfo; import com.sun.enterprise.util.i18n.StringManager; import jakarta.inject.Inject; import jakarta.inject.Named; diff --git a/nucleus/security/core/src/main/resources/config/server.policy b/nucleus/security/core/src/main/resources/config/server.policy index b7ea5d4b130..adc4e053fec 100644 --- a/nucleus/security/core/src/main/resources/config/server.policy +++ b/nucleus/security/core/src/main/resources/config/server.policy @@ -119,6 +119,7 @@ grant { permission java.io.SerializablePermission "enableSubstitution"; permission java.security.SecurityPermission "getProperty.package.definition"; permission java.security.SecurityPermission "createPolicy.JavaPolicy"; + permission java.security.SecurityPermission "getProperty.authconfigprovider.factory.providers"; }; diff --git a/nucleus/security/services/pom.xml b/nucleus/security/services/pom.xml index 025b85eda25..6528572c126 100644 --- a/nucleus/security/services/pom.xml +++ b/nucleus/security/services/pom.xml @@ -40,7 +40,7 @@ holder. --> - + 4.0.0 @@ -86,6 +86,10 @@ fish.payara.server.core.security security + + org.glassfish.epicyro + epicyro + org.glassfish.annotations logging-annotation-processor From 9d483a650d7ef07b7830ec0f58ca387470fb3ec8 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Mon, 18 Nov 2024 22:27:27 -0600 Subject: [PATCH 17/34] FISH-8925: fixing osgi issues and adding more changes tu run authentication with epicyro --- appserver/packager/glassfish-web/pom.xml | 4 + appserver/security/core-ee/osgi.bundle | 7 +- .../security/ee/JavaEESecurityLifecycle.java | 16 +- .../security/ee/SecurityDeployer.java | 15 +- .../jakarta/WebServicesDelegate.java | 6 +- .../EJBPolicyContextDelegate.java | 4 +- .../WebAuthorizationManagerService.java} | 14 +- .../ee/web/integration/AuthorizationUtil.java | 182 ++++++++++++++++++ .../SecurityRoleMapperFactoryGen.java | 47 +++++ .../web/integration/WebSecurityManager.java | 182 ++++++++++++++++++ .../WebSecurityManagerFactory.java | 70 ++++--- .../config/PayaraEpicyroServletServices.java | 11 +- .../PrincipalGroupFactoryImpl.java | 1 + .../identitystores/PamRealmIdentityStore.java | 30 +-- .../com/sun/web/security/RealmAdapter.java | 104 ++++++---- .../config/SoapAuthenticationService.java | 2 +- .../webservices/WebServicesDelegateImpl.java | 44 ++--- .../security/common/UserNameAndPassword.java | 1 + .../security/common/UserPrincipal.java | 1 + .../factory/SecurityManagerFactory.java | 2 +- 20 files changed, 593 insertions(+), 150 deletions(-) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/{authorize => authorization}/EJBPolicyContextDelegate.java (96%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jacc/JaccWebAuthorizationManager.java => ee/authorization/WebAuthorizationManagerService.java} (98%) create mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/AuthorizationUtil.java create mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/SecurityRoleMapperFactoryGen.java create mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManager.java rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{ => ee}/web/integration/WebSecurityManagerFactory.java (67%) diff --git a/appserver/packager/glassfish-web/pom.xml b/appserver/packager/glassfish-web/pom.xml index 83b08c08a77..1eb2c93e8b4 100644 --- a/appserver/packager/glassfish-web/pom.xml +++ b/appserver/packager/glassfish-web/pom.xml @@ -246,5 +246,9 @@ realm-stores ${project.version} + + org.glassfish.epicyro + epicyro + diff --git a/appserver/security/core-ee/osgi.bundle b/appserver/security/core-ee/osgi.bundle index d6b158e7c3b..4b500d1fce5 100644 --- a/appserver/security/core-ee/osgi.bundle +++ b/appserver/security/core-ee/osgi.bundle @@ -37,7 +37,7 @@ # only if the new code is made subject to such option by the copyright # holder. # -# Portions Copyright 2016-2023 Payara Foundation and/or its affiliates +# Portions Copyright 2016-2024 Payara Foundation and/or its affiliates -exportcontents: \ com.sun.enterprise.security.acl; \ @@ -45,7 +45,10 @@ com.sun.enterprise.security.ee.audit; \ com.sun.enterprise.security.ee.auth.login; \ com.sun.enterprise.security.auth.realm.jdbc; \ - com.sun.enterprise.security.ee.authorize; \ + com.sun.enterprise.security.ee.authorization; \ + com.sun.enterprise.security.ee.authentication.jakarta; \ + com.sun.enterprise.security.ee.web; \ + com.sun.enterprise.security.ee.web.integration; \ com.sun.enterprise.security.jauth; \ com.sun.enterprise.security.jaspic; \ com.sun.enterprise.security.jaspic.callback; \ diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java index 9e4887308d5..f6bd5805610 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java @@ -41,13 +41,13 @@ package com.sun.enterprise.security.ee; import com.sun.enterprise.security.ContainerSecurityLifecycle; +import com.sun.enterprise.security.PolicyLoader; import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; -import com.sun.enterprise.security.PolicyLoader; import com.sun.logging.LogDomains; - import jakarta.inject.Inject; +import jakarta.inject.Singleton; import jakarta.security.auth.message.MessageInfo; import jakarta.security.auth.message.MessagePolicy; import java.security.Provider; @@ -56,14 +56,12 @@ import java.util.function.BiFunction; import java.util.function.Function; import java.util.logging.Logger; - -import jakarta.inject.Singleton; - import org.glassfish.common.util.Constants; import org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory; import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import org.glassfish.hk2.api.PostConstruct; import org.glassfish.hk2.api.Rank; +import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.internal.api.Globals; import org.glassfish.internal.api.InitRunLevel; import org.jvnet.hk2.annotations.Service; @@ -82,11 +80,14 @@ @Singleton public class JavaEESecurityLifecycle implements ContainerSecurityLifecycle, PostConstruct { - private static final Logger LOG = LogDomains.getLogger(JavaEESecurityLifecycle.class, LogDomains.SECURITY_LOGGER); + private static final Logger LOG = LogDomains.getLogger(JavaEESecurityLifecycle.class, LogDomains.SECURITY_LOGGER, false); @Inject PolicyLoader policyLoader; + @Inject + private ServiceLocator habitat; + @Override public void postConstruct() { onInitialization(); @@ -109,7 +110,8 @@ private void initializeJakartaAuthentication() { } String defaultProvidersString = null; - WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); + //WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); + WebServicesDelegate delegate = habitat.getService(WebServicesDelegate.class); if (delegate == null) { defaultProvidersString = GFServerConfigProvider.class.getName(); } else { diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java index d4a9a5123e5..9ad59455613 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java @@ -38,7 +38,7 @@ * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.ee; @@ -51,9 +51,10 @@ import com.sun.enterprise.security.EjbSecurityPolicyProbeProvider; import com.sun.enterprise.security.SecurityLifecycle; import com.sun.enterprise.security.WebSecurityDeployerProbeProvider; -import com.sun.enterprise.security.jacc.JaccWebAuthorizationManager; +import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; +import com.sun.enterprise.security.ee.web.integration.WebSecurityManager; import com.sun.enterprise.security.util.IASSecurityException; -import com.sun.enterprise.security.web.integration.WebSecurityManagerFactory; +import com.sun.enterprise.security.ee.web.integration.WebSecurityManagerFactory; import com.sun.logging.LogDomains; import java.util.ArrayList; @@ -259,8 +260,8 @@ public void loadPolicy(WebBundleDescriptor webDescriptor, boolean remove) throws } try { if (remove) { - JaccWebAuthorizationManager authorizationManager = webSecurityManagerFactory - .getManager(getContextID(webDescriptor), null, true); + WebSecurityManager authorizationManager = webSecurityManagerFactory + .getManager(getContextID(webDescriptor), true); if (authorizationManager != null) { authorizationManager.release(); } @@ -401,12 +402,12 @@ private void removePolicy(DeploymentContext context) throws DeploymentException private boolean cleanSecurityContext(String appName) { boolean cleanUpDone = false; - List managers = webSecurityManagerFactory.getManagersForApp(appName, false); + List managers = webSecurityManagerFactory.getManagersForApp(appName, false); if (managers == null) { return false; } - for (JaccWebAuthorizationManager manager : managers) { + for (WebSecurityManager manager : managers) { try { websecurityProbeProvider.securityManagerDestructionStartedEvent(appName); manager.destroy(); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java index e34465247d3..7b6813cd610 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/WebServicesDelegate.java @@ -44,12 +44,10 @@ import jakarta.security.auth.message.MessageInfo; -import org.glassfish.api.invocation.ComponentInvocation; import org.jvnet.hk2.annotations.Contract; import com.sun.enterprise.deployment.ServiceReferenceDescriptor; import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import org.glassfish.epicyro.services.RegistrationWrapperRemover; /** * A Delegate interface for handling WebServices specific security and JASPIC (JSR 196) providers. @@ -61,7 +59,7 @@ * @author kumar.jayanti */ @Contract -public interface WebServicesDelegate extends RegistrationWrapperRemover { +public interface WebServicesDelegate { /** * @@ -69,7 +67,7 @@ public interface WebServicesDelegate extends RegistrationWrapperRemover { * @param properties The Properties Map passed to WebServices Code Via PipeCreator * @return The MessageSecurityBindingDescriptor */ - MessageSecurityBindingDescriptor getBinding(ServiceReferenceDescriptor serviceReference, Map properties); + MessageSecurityBindingDescriptor getBinding(ServiceReferenceDescriptor serviceReference, Map properties); /** * This method returns the class name of the default JASPIC (JSR 196) WebServices security provider. diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/EJBPolicyContextDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/EJBPolicyContextDelegate.java similarity index 96% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/EJBPolicyContextDelegate.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/EJBPolicyContextDelegate.java index 3a47461e523..112fe280899 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorize/EJBPolicyContextDelegate.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/EJBPolicyContextDelegate.java @@ -37,8 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.ee.authorize; +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authorization; import java.lang.reflect.Method; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java similarity index 98% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java index 81cefd76b61..d2dc043143d 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebAuthorizationManager.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java @@ -40,7 +40,7 @@ // Portions Copyright 2016-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license. -package com.sun.enterprise.security.jacc; +package com.sun.enterprise.security.ee.authorization; import com.sun.enterprise.config.serverbeans.ApplicationRef; import com.sun.enterprise.config.serverbeans.Server; @@ -58,6 +58,7 @@ import org.glassfish.security.common.UserNameAndPassword; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; +import com.sun.enterprise.security.jacc.JaccWebConstraintsTranslator; import com.sun.enterprise.security.jacc.cache.CachedPermission; import com.sun.enterprise.security.jacc.cache.CachedPermissionImpl; import com.sun.enterprise.security.jacc.cache.PermissionCache; @@ -65,7 +66,7 @@ import com.sun.enterprise.security.web.integration.GlassFishPrincipalMapper; import com.sun.enterprise.security.web.integration.GlassFishToExousiaConverter; import com.sun.enterprise.security.web.integration.WebPrincipal; -import com.sun.enterprise.security.web.integration.WebSecurityManagerFactory; +import com.sun.enterprise.security.ee.web.integration.WebSecurityManagerFactory; import com.sun.logging.LogDomains; import fish.payara.jacc.JaccConfigurationFactory; import jakarta.security.enterprise.CallerPrincipal; @@ -133,7 +134,7 @@ * @todo introduce a new class called AbstractSecurityManager. Move functionality from this class and EJBSecurityManager * class and extend this class from AbstractSecurityManager */ -public class JaccWebAuthorizationManager { +public class WebAuthorizationManagerService { private static final Logger logger = Logger.getLogger(LogDomains.SECURITY_LOGGER); @@ -225,6 +226,13 @@ public JaccWebAuthorizationManager(WebBundleDescriptor webBundleDescriptor, Serv webBundleDescriptor.isDenyUncoveredHttpMethods(), GlassFishToExousiaConverter.getSecurityRoleRefsFromBundle(webBundleDescriptor)); } + + public WebAuthorizationManagerService(WebBundleDescriptor webBundleDescriptor, boolean register) throws PolicyContextException { + this.CONTEXT_ID = getContextID(webBundleDescriptor); + this.webSecurityManagerFactory = null; + this.serverContext = null; + this.webBundleDescriptor = webBundleDescriptor; + } private void preprocessParams(WebBundleDescriptor webBundleDescriptor) { //evaluate if the context param was set for the property jakarta.security.jacc.PolicyFactory.provider diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/AuthorizationUtil.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/AuthorizationUtil.java new file mode 100644 index 00000000000..d4ca4acfb27 --- /dev/null +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/AuthorizationUtil.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation + * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package com.sun.enterprise.security.ee.web.integration; + +import com.sun.enterprise.deployment.Application; +import com.sun.enterprise.deployment.EjbBundleDescriptor; +import com.sun.enterprise.deployment.WebBundleDescriptor; +import com.sun.enterprise.security.util.IASSecurityException; +import com.sun.enterprise.util.LocalStringManagerImpl; + +import jakarta.security.jacc.PolicyConfiguration; +import jakarta.security.jacc.PolicyConfigurationFactory; +import jakarta.security.jacc.PolicyContextException; +import jakarta.security.jacc.PolicyFactory; + +import java.util.Collection; + +import org.glassfish.api.deployment.DeploymentContext; +import org.glassfish.api.deployment.OpsParams; +import org.glassfish.deployment.common.SecurityRoleMapperFactory; +import org.glassfish.deployment.versioning.VersioningUtils; + +import static org.glassfish.deployment.versioning.VersioningUtils.getRepositoryName; + +/** + * This utility class contains several methods for working with (Jakarta) Authorization. + * + * @author Harpreet Singh + * @author Shing Wai Chan + */ +public class AuthorizationUtil { + + private static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(AuthorizationUtil.class); + public static final String VENDOR_PRESENT = "com.sun.enterprise.security.ee.provider.jaccvendorpresent"; + + // set in PolicyLoader from domain.xml + private static final String REPOSITORY_HOME_PROP = "com.sun.enterprise.jaccprovider.property.repository"; + + // TODO remove use of system property + // The repository is defined in PolicyFileMgr. + // It is repeated here since JACC provider is not reference directly. + public static final String repository = System.getProperty(REPOSITORY_HOME_PROP); + + public static String getContextID(EjbBundleDescriptor ejbBundleDesc) { + if (ejbBundleDesc == null) { + return null; + } + + // Detect special case of EJBs embedded in a war, and make sure pseudo policy context id is + // unique within application. + Object root = ejbBundleDesc.getModuleDescriptor().getDescriptor(); + if (root != ejbBundleDesc && root instanceof WebBundleDescriptor) { + return createUniquePseudoModuleID(ejbBundleDesc); + } + + return getRepositoryName( + ejbBundleDesc.getApplication().getRegistrationName()) + + '/' + + ejbBundleDesc.getUniqueFriendlyId(); + } + + public static String getContextID(WebBundleDescriptor webBundleDescriptor) { + if (webBundleDescriptor == null) { + return null; + } + + return getRepositoryName( + webBundleDescriptor.getApplication().getRegistrationName()) + + '/' + + webBundleDescriptor.getUniqueFriendlyId(); + } + + /** + * Inform the policy module to take the named policy context out of service. The policy context is transitioned to the + * deleted state. In our provider implementation, the corresponding policy file is deleted, as the presence of a policy + * file in the repository is how we persistently remember which policy contexts are in service. + * + * @param String contextId - the module id which serves to identify the corresponding policy context. The name shall not be + * null. + */ + public static void removePolicy(String contextId) throws IASSecurityException { + if (contextId == null) { + throw new IASSecurityException("Invalid Module Name"); + } + + try { + boolean wasInService = PolicyConfigurationFactory.getPolicyConfigurationFactory().inService(contextId); + + // Find the PolicyConfig and delete it. + PolicyConfiguration policyConfiguration = PolicyConfigurationFactory.getPolicyConfigurationFactory().getPolicyConfiguration(contextId, false); + policyConfiguration.delete(); + + // Only do refresh policy if the deleted context was in service + if (wasInService) { + PolicyFactory.getPolicyFactory().getPolicy().refresh(); + } + + } catch (ClassNotFoundException cnfe) { + throw new IASSecurityException(localStrings.getLocalString( + "enterprise.security.securityutil.classnotfound", + "Could not find PolicyConfigurationFactory class. Check jakarta.security.jacc.PolicyConfigurationFactory.provider property")); + } catch (PolicyContextException pce) { + throw new IASSecurityException(pce.toString()); + } + } + + public static SecurityRoleMapperFactory getRoleMapperFactory() { + SecurityRoleMapperFactory factory = SecurityRoleMapperFactoryGen.getSecurityRoleMapperFactory(); + if (factory == null) { + throw new IllegalArgumentException("This application has no role mapper factory defined"); + } + + return factory; + } + + public static void removeRoleMapper(DeploymentContext deploymentContext) { + OpsParams params = deploymentContext.getCommandParameters(OpsParams.class); + if (params.origin != OpsParams.Origin.undeploy) { + return; + } + + getRoleMapperFactory().removeRoleMapper(params.name()); + + } + + /** + * create pseudo module context id, and make sure it is unique, by chacking it against the names of all the other + * modules in the app. + * + * @param ejbDesc + * @return + */ + private static String createUniquePseudoModuleID(EjbBundleDescriptor ejbDesc) { + Application app = ejbDesc.getApplication(); + Collection webModules = app.getBundleDescriptors(WebBundleDescriptor.class); + Collection ejbModules = app.getBundleDescriptors(EjbBundleDescriptor.class); + + String moduleName = ejbDesc.getUniqueFriendlyId(); + String pseudonym; + int uniquifier = 0; + boolean unique; + do { + unique = true; + pseudonym = moduleName + (uniquifier == 0 ? "_internal" : "_internal_" + uniquifier); + if (webModules != null) { + for (WebBundleDescriptor w : webModules) { + if (pseudonym.equals(w.getUniqueFriendlyId())) { + unique = false; + break; + } + } + } + if (unique && ejbModules != null) { + for (EjbBundleDescriptor e : ejbModules) { + if (pseudonym.equals(e.getUniqueFriendlyId())) { + unique = false; + break; + } + } + } + uniquifier += 1; + + } while (!unique); + + return VersioningUtils.getRepositoryName(app.getRegistrationName()) + "/" + pseudonym; + } +} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/SecurityRoleMapperFactoryGen.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/SecurityRoleMapperFactoryGen.java new file mode 100644 index 00000000000..e488b3fed9e --- /dev/null +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/SecurityRoleMapperFactoryGen.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package com.sun.enterprise.security.ee.web.integration; + +import java.lang.ref.WeakReference; + +import org.glassfish.deployment.common.SecurityRoleMapperFactory; +import org.glassfish.internal.api.Globals; + +/** + * @author nasradu8 2009 + */ +public class SecurityRoleMapperFactoryGen { + + private static WeakReference securityRoleMapperFactory = new WeakReference<>(null); + + public static SecurityRoleMapperFactory getSecurityRoleMapperFactory() { + if (securityRoleMapperFactory.get() != null) { + return securityRoleMapperFactory.get(); + } + + return _getSecurityRoleMapperFactory(); + } + + private static synchronized SecurityRoleMapperFactory _getSecurityRoleMapperFactory() { + if (securityRoleMapperFactory.get() == null) { + securityRoleMapperFactory = new WeakReference<>(Globals.get(SecurityRoleMapperFactory.class)); + } + + return securityRoleMapperFactory.get(); + } +} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManager.java new file mode 100644 index 00000000000..45e07121e48 --- /dev/null +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManager.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation + * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package com.sun.enterprise.security.ee.web.integration; + +import com.sun.enterprise.config.serverbeans.ApplicationRef; +import com.sun.enterprise.config.serverbeans.Server; +import com.sun.enterprise.deployment.WebBundleDescriptor; +import com.sun.enterprise.deployment.runtime.common.PrincipalNameDescriptor; +import com.sun.enterprise.deployment.runtime.common.SecurityRoleMapping; +import com.sun.enterprise.deployment.runtime.common.wls.SecurityRoleAssignment; +import com.sun.enterprise.deployment.runtime.web.SunWebApp; +import com.sun.enterprise.deployment.web.LoginConfiguration; + + +import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; +import jakarta.security.jacc.PolicyContextException; +import jakarta.servlet.http.HttpServletRequest; + +import java.util.List; + +import java.util.logging.Logger; +import org.glassfish.internal.api.ServerContext; +import org.glassfish.security.common.Group; +import org.glassfish.security.common.UserNameAndPassword; + + +import static com.sun.logging.LogDomains.SECURITY_LOGGER; +import static java.util.logging.Level.FINE; +import static org.glassfish.api.web.Constants.ADMIN_VS; + +/** + + *

+ * The GlassFish authorization service is a thin wrapper over the Exousia authorization service that implements + * Jakarta Authorization. + * + * @author Jean-Francois Arcand + * @author Harpreet Singh. + */ +public class WebSecurityManager { + private static final Logger logger = Logger.getLogger(SECURITY_LOGGER); + + private final WebAuthorizationManagerService authorizationService; + + private final WebSecurityManagerFactory webSecurityManagerFactory; + private final String contextId; + + WebSecurityManager(WebBundleDescriptor webBundleDescriptor, ServerContext serverContext, WebSecurityManagerFactory webSecurityManagerFactory, boolean register) throws PolicyContextException { + // Sets-up Jakarta Authorization + this.authorizationService = new WebAuthorizationManagerService(webBundleDescriptor, register); + + this.webSecurityManagerFactory = webSecurityManagerFactory; + this.contextId = AuthorizationUtil.getContextID(webBundleDescriptor); + + if (ADMIN_VS.equals(getVirtualServers(webBundleDescriptor, serverContext))) { + handleAdminVirtualServer(webBundleDescriptor, webSecurityManagerFactory); + } + + if (logger.isLoggable(FINE)) { + logger.log(FINE, "[Web-Security] Context id (id under which WEB component in application will be created) = {0}", contextId); + logger.log(FINE, "[Web-Security] Codebase (module id for web component) {0}", removeSpaces(contextId)); + } + } + + /** + * @return the authorizationService + */ + public WebAuthorizationManagerService getAuthorizationService() { + return authorizationService; + } + + public void onLogin(HttpServletRequest httpServletRequest) { + authorizationService.setSecurityInfo(httpServletRequest); + } + + public void onLogout() { + //authorizationService.resetSecurityInfo(); + } + + /** + * Analogous to destroy, except does not remove links from Policy Context, and does not remove context_id from role mapper + * factory. Used to support Policy Changes that occur via ServletContextListener. + * + * @throws PolicyContextException + */ + public void release() throws PolicyContextException { + authorizationService.release(); + webSecurityManagerFactory.getManager(contextId, true); + } + + public void destroy() throws PolicyContextException { + authorizationService.destroy(); + webSecurityManagerFactory.getManager(contextId, true); + } + + + + // ### Private methods ### + + private void handleAdminVirtualServer(WebBundleDescriptor webBundleDescriptor, WebSecurityManagerFactory webSecurityManagerFactory) { + LoginConfiguration loginConfiguration = webBundleDescriptor.getLoginConfiguration(); + if (loginConfiguration == null) { + return; + } + + String realmName = loginConfiguration.getRealmName(); + SunWebApp sunDescriptor = webBundleDescriptor.getSunDescriptor(); + if (sunDescriptor == null) { + return; + } + + SecurityRoleMapping[] sunRoleMappings = sunDescriptor.getSecurityRoleMapping(); + if (sunRoleMappings != null) { + for (SecurityRoleMapping roleMapping : sunRoleMappings) { + for (PrincipalNameDescriptor principal : roleMapping.getPrincipalNames()) { + // We keep just a name here + webSecurityManagerFactory.putAdminPrincipal(realmName, + new UserNameAndPassword(principal.getName())); + } + for (String group : roleMapping.getGroupNames()) { + webSecurityManagerFactory.putAdminGroup(group, realmName, new Group(group)); + } + } + } + + SecurityRoleAssignment[] sunRoleAssignments = sunDescriptor.getSecurityRoleAssignments(); + if (sunRoleAssignments != null) { + for (SecurityRoleAssignment roleAssignment : sunRoleAssignments) { + List principals = roleAssignment.getPrincipalNames(); + if (roleAssignment.isExternallyDefined()) { + webSecurityManagerFactory.putAdminGroup(roleAssignment.getRoleName(), realmName, + new Group(roleAssignment.getRoleName())); + continue; + } + for (String principal : principals) { + webSecurityManagerFactory.putAdminPrincipal(realmName, new UserNameAndPassword(principal)); + } + } + } + } + + /** + * Virtual servers are maintained in the reference contained in Server element. First, we need to find the server and then get + * the virtual server from the correct reference + * + * @param applicationName Name of the app to get vs + * + * @return virtual servers as a string (separated by space or comma) + */ + private String getVirtualServers(WebBundleDescriptor webBundleDescriptor, ServerContext serverContext) { + String applicationName = webBundleDescriptor.getApplication().getRegistrationName(); + Server server = serverContext.getDefaultServices().getService(Server.class); + + for (ApplicationRef appplicationRef : server.getApplicationRef()) { + if (appplicationRef.getRef().equals(applicationName)) { + return appplicationRef.getVirtualServers(); + } + } + + return null; + } + + private static String removeSpaces(String withSpaces) { + return withSpaces.replace(' ', '_'); + } + +} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/WebSecurityManagerFactory.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java similarity index 67% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/WebSecurityManagerFactory.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java index 30ca9154587..83dd5ca5965 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/WebSecurityManagerFactory.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java @@ -37,13 +37,12 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.web.integration; +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.web.integration; import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.security.WebSecurityDeployerProbeProvider; import com.sun.enterprise.security.factory.SecurityManagerFactory; -import com.sun.enterprise.security.jacc.JaccWebAuthorizationManager; import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; import com.sun.enterprise.security.jacc.context.PolicyContextRegistration; @@ -59,10 +58,11 @@ import jakarta.security.jacc.PolicyContextException; import org.glassfish.internal.api.ServerContext; +import org.glassfish.security.common.Group; +import org.glassfish.security.common.UserPrincipal; import org.jvnet.hk2.annotations.Service; import static com.sun.logging.LogDomains.SECURITY_LOGGER; -import static java.util.logging.Level.CONFIG; /** * @author JeanFrancois Arcand @@ -76,6 +76,9 @@ public class WebSecurityManagerFactory extends SecurityManagerFactory { private final WebSecurityDeployerProbeProvider probeProvider = new WebSecurityDeployerProbeProvider(); + private final Map adminPrincipals = new ConcurrentHashMap<>(); + private final Map adminGroups = new ConcurrentHashMap<>(); + public final PolicyContextHandlerImpl pcHandlerImpl = (PolicyContextHandlerImpl) PolicyContextHandlerImpl.getInstance(); public final Map adminPrincipalsPerApp = new ConcurrentHashMap<>(); @@ -83,29 +86,29 @@ public class WebSecurityManagerFactory extends SecurityManagerFactory { // Stores the Context IDs to application names for standalone web applications private final Map> CONTEXT_IDS = new HashMap<>(); - private final Map> SECURITY_MANAGERS = new HashMap<>(); + private final Map> SECURITY_MANAGERS = new HashMap<>(); public WebSecurityManagerFactory() { // Registers the JACC policy handlers, which provide objects JACC Providers and other code can use PolicyContextRegistration.registerPolicyHandlers(); } - public JaccWebAuthorizationManager createManager(WebBundleDescriptor webBundleDescriptor, boolean register, ServerContext context) { - String contextId = JaccWebAuthorizationManager.getContextID(webBundleDescriptor); + public WebSecurityManager createManager(WebBundleDescriptor webBundleDescriptor, boolean register, ServerContext context) { + String contextId = AuthorizationUtil.getContextID(webBundleDescriptor); - JaccWebAuthorizationManager manager = null; + WebSecurityManager manager = null; if (register) { - manager = getManager(contextId, null, false); + manager = getManager(contextId, false); } if (manager == null || !register) { try { - // Create a new JaccWebAuthorizationManager for this context + // Create a new WebAuthorizationManagerService for this context probeProvider.securityManagerCreationStartedEvent(webBundleDescriptor.getModuleID()); // As "side-effect" of constructing the manager, the web constraints in the web bundle // descriptor will be translated to permissions and loaded into a JACC policy configuration - manager = new JaccWebAuthorizationManager(webBundleDescriptor, context, this, register); + manager = new WebSecurityManager(webBundleDescriptor, context, this, register); probeProvider.securityManagerCreationEndedEvent(webBundleDescriptor.getModuleID()); @@ -121,43 +124,48 @@ public JaccWebAuthorizationManager createManager(WebBundleDescriptor webBundleDe return manager; } - public JaccWebAuthorizationManager getManager(String ctxId, String name, boolean remove) { - return getManager(SECURITY_MANAGERS, ctxId, name, remove); + public void addManagerToApp(String ctxId, String name, String appName, WebSecurityManager manager) { + addManagerToApp(SECURITY_MANAGERS, CONTEXT_IDS, ctxId, name, appName, manager); } - public ArrayList getManagers(String ctxId, boolean remove) { - return getManagers(SECURITY_MANAGERS, ctxId, remove); + public WebSecurityManager getManager(String contextId) { + return getManager(SECURITY_MANAGERS, contextId, null, false); } - public List getManagersForApp(String appName, boolean remove) { - return getManagersForApp(SECURITY_MANAGERS, CONTEXT_IDS, appName, remove); + public WebSecurityManager getManager(String contextId, boolean remove) { + return getManager(SECURITY_MANAGERS, contextId, null, remove); } - public String[] getContextsForApp(String appName, boolean remove) { - return getContextsForApp(CONTEXT_IDS, appName, remove); + public ArrayList getManagers(String contextId, boolean remove) { + return getManagers(SECURITY_MANAGERS, contextId, remove); } - public void addManagerToApp(String contextId, String name, String appName, JaccWebAuthorizationManager manager) { - addManagerToApp(SECURITY_MANAGERS, CONTEXT_IDS, contextId, name, appName, manager); + public ArrayList getManagersForApp(String appName, boolean remove) { + return getManagersForApp(SECURITY_MANAGERS, CONTEXT_IDS, appName, remove); } + public String[] getContextsForApp(String appName, boolean remove) { + return getContextsForApp(CONTEXT_IDS, appName, remove); + } - // ### PrincipalGroupFactoryImpl backing - - public void addAdminPrincipal(String username, String realmName, Principal principal) { - adminPrincipalsPerApp.put(realmName + username, principal); + public UserPrincipal getAdminPrincipal(String username, String realmName) { + // FIXME: can be hacked: "ab+cd" = "a+bcd" + return adminPrincipals.get(realmName + username); } - public void addAdminGroup(String group, String realmName, Principal principal) { - adminGroupsPerApp.put(realmName + group, principal); + public void putAdminPrincipal(String realmName, UserPrincipal principal) { + // FIXME: can be hacked: "ab+cd" = "a+bcd" + adminPrincipals.put(realmName + principal.getName(), principal); } - public Principal getAdminPrincipal(String username, String realmName) { - return adminPrincipalsPerApp.get(realmName + username); + public Group getAdminGroup(String group, String realmName) { + // FIXME: can be hacked: "ab+cd" = "a+bcd" + return adminGroups.get(realmName + group); } - public Principal getAdminGroup(String group, String realmName) { - return adminGroupsPerApp.get(realmName + group); + public void putAdminGroup(String group, String realmName, Group principal) { + // FIXME: can be hacked: "ab+cd" = "a+bcd" + adminGroups.put(realmName + group, principal); } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java index ba6a29e30b4..c5a9242dfd4 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java @@ -41,6 +41,8 @@ package com.sun.enterprise.security.jaspic.config; import static com.sun.enterprise.deployment.web.LoginConfiguration.CLIENT_CERTIFICATION_AUTHENTICATION; + +import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.POLICY_CONTEXT; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.WEB_BUNDLE; @@ -51,15 +53,10 @@ import javax.security.auth.callback.CallbackHandler; import jakarta.security.auth.message.config.AuthConfigProvider; -import org.glassfish.internal.api.Globals; - import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.deployment.runtime.web.SunWebApp; import com.sun.enterprise.deployment.web.LoginConfiguration; import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; -import com.sun.enterprise.security.jacc.JaccWebAuthorizationManager; -import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; -import org.glassfish.epicyro.services.RegistrationWrapperRemover; public class PayaraEpicyroServletServices extends PayaraEpicyroServices { @@ -87,10 +84,10 @@ public PayaraEpicyroServletServices(String appContext, Map map, } // Set realmName before init - init(HTTPSERVLET, appContext, map, callbackHandler, (RegistrationWrapperRemover) Globals.get(WebServicesDelegate.class)); + init(HTTPSERVLET, appContext, map, callbackHandler, null); if (webBundle != null) { - String policyContextId = JaccWebAuthorizationManager.getContextID(webBundle); + String policyContextId = WebAuthorizationManagerService.getContextID(webBundle); map.put(POLICY_CONTEXT, policyContextId); SunWebApp sunWebApp = webBundle.getSunDescriptor(); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java index 98e894ae925..637379a3039 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/PrincipalGroupFactoryImpl.java @@ -46,6 +46,7 @@ package com.sun.enterprise.security.web.integration; +import com.sun.enterprise.security.ee.web.integration.WebSecurityManagerFactory; import java.lang.ref.WeakReference; import org.glassfish.security.common.UserNameAndPassword; diff --git a/appserver/security/realm-stores/src/main/java/fish/payara/security/realm/identitystores/PamRealmIdentityStore.java b/appserver/security/realm-stores/src/main/java/fish/payara/security/realm/identitystores/PamRealmIdentityStore.java index cb555968bcb..e839342d845 100644 --- a/appserver/security/realm-stores/src/main/java/fish/payara/security/realm/identitystores/PamRealmIdentityStore.java +++ b/appserver/security/realm-stores/src/main/java/fish/payara/security/realm/identitystores/PamRealmIdentityStore.java @@ -1,8 +1,8 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) [2019-2021] Payara Foundation and/or its affiliates. All rights reserved. - * + * + * Copyright (c) [2019-2024] Payara Foundation and/or its affiliates. All rights reserved. + * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You @@ -11,20 +11,20 @@ * https://github.com/payara/Payara/blob/main/LICENSE.txt * See the License for the specific * language governing permissions and limitations under the License. - * + * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/legal/LICENSE.txt. - * + * * GPL Classpath Exception: * The Payara Foundation designates this particular file as subject to the "Classpath" * exception as provided by the Payara Foundation in the GPL Version 2 section of the License * file that accompanied this code. - * + * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" - * + * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] @@ -39,29 +39,15 @@ */ package fish.payara.security.realm.identitystores; -import com.sun.enterprise.security.auth.login.common.LoginException; -import com.sun.enterprise.security.auth.realm.NoSuchRealmException; -import com.sun.enterprise.security.auth.realm.Realm; import com.sun.enterprise.security.auth.realm.pam.PamRealm; import com.sun.enterprise.security.ee.auth.login.PamLoginModule; -import fish.payara.security.annotations.PamIdentityStoreDefinition; import fish.payara.security.realm.config.PamRealmIdentityStoreConfiguration; -import fish.payara.security.realm.RealmUtil; -import static fish.payara.security.realm.RealmUtil.ASSIGN_GROUPS; -import static fish.payara.security.realm.RealmUtil.JAAS_CONTEXT; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Properties; import jakarta.enterprise.inject.Typed; -import jakarta.security.enterprise.CallerPrincipal; import jakarta.security.enterprise.credential.Credential; import jakarta.security.enterprise.credential.UsernamePasswordCredential; import jakarta.security.enterprise.identitystore.CredentialValidationResult; -import static jakarta.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT; + import static jakarta.security.enterprise.identitystore.CredentialValidationResult.NOT_VALIDATED_RESULT; -import jakarta.security.enterprise.identitystore.IdentityStore; -import org.glassfish.soteria.identitystores.IdentityStoreException; -import org.jvnet.libpam.UnixUser; /** * {@link PamRealmIdentityStore} Identity store validates the user using diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index 15199a5b72b..4c9ab2883e0 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2020] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package com.sun.web.security; import com.sun.enterprise.deployment.Application; @@ -56,10 +56,11 @@ import com.sun.enterprise.security.auth.digest.impl.HttpAlgorithmParameterImpl; import com.sun.enterprise.security.auth.login.DigestCredentials; import com.sun.enterprise.security.integration.RealmInitializer; -import com.sun.enterprise.security.jacc.JaccWebAuthorizationManager; +import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; import com.sun.enterprise.security.web.integration.WebPrincipal; -import com.sun.enterprise.security.web.integration.WebSecurityManagerFactory; +import com.sun.enterprise.security.ee.web.integration.WebSecurityManager; +import com.sun.enterprise.security.ee.web.integration.WebSecurityManagerFactory; import com.sun.enterprise.util.net.NetUtils; import com.sun.logging.LogDomains; import com.sun.web.security.realmadapter.AuthenticatorProxy; @@ -154,14 +155,14 @@ public class RealmAdapter extends RealmBase implements RealmInitializer, PostCon protected static final String name = "J2EE-RI-RealmAdapter"; /** - * The context Id value needed by JACC. + * The context Id value needed for Jakarta Authorization. */ - private String jaccContextId; + private String contextId; /** - * A JaccWebAuthorizationManager object associated with a jaccContextId + * A WebAuthorizationManagerService object associated with a contextId */ - protected volatile JaccWebAuthorizationManager jaccWebAuthorizationManager; + protected volatile WebSecurityManager webSecurityManager; protected boolean isCurrentURIincluded; @@ -190,7 +191,7 @@ public class RealmAdapter extends RealmBase implements RealmInitializer, PostCon private NetworkConfig networkConfig; /** - * The factory used for creating JaccWebAuthorizationManager object. + * The factory used for creating WebAuthorizationManagerService object. */ @Inject protected WebSecurityManagerFactory webSecurityManagerFactory; @@ -235,7 +236,7 @@ public void initializeRealm(Object bundleDescriptor, boolean isSystemApp, String () -> format("initializeRealm(bundleDescriptor.appContextId=%s, isSystemApp=%s, defaultRealmName=%s)", webDescriptor.getAppContextId(), isSystemApp, defaultRealmName)); realmName = computeRealmName(defaultRealmName); - jaccContextId = JaccWebAuthorizationManager.getContextID(webDescriptor); + contextId = WebAuthorizationManagerService.getContextID(webDescriptor); runAsPrincipals = new HashMap<>(); for (WebComponentDescriptor componentDescriptor : webDescriptor.getWebComponentDescriptors()) { RunAsIdentityDescriptor runAsDescriptor = componentDescriptor.getRunAsIdentity(); @@ -298,9 +299,9 @@ public SecurityConstraint[] findSecurityConstraints(String requestPathMB, String jaspicRealm.initJaspicServices(context.getServletContext()); } - JaccWebAuthorizationManager authorizationManager = getJaccWebAuthorizationManager(false); + WebSecurityManager securityManager = getWebSecurityManager(false); - if (authorizationManager != null && authorizationManager.hasNoConstrainedResources() && !jaspicRealm.isJaspicEnabled(context.getServletContext())) { + if (securityManager != null) { // No constraints return null; } @@ -309,6 +310,30 @@ public SecurityConstraint[] findSecurityConstraints(String requestPathMB, String return emptyConstraints; } + /** + * Utility method to get web security manager. + * Will log warning if the manager is not found in the factory, and logNull is true. + *

+ * Note: webSecurityManagerFactory can be null the very questionable SOAP code just + * instantiates a RealmAdapter + * + * @param logNull + * @return {@link WebSecurityManager} or null + */ + public WebSecurityManager getWebSecurityManager(boolean logNull) { + if (webSecurityManager == null && webSecurityManagerFactory != null) { + synchronized (this) { + webSecurityManager = webSecurityManagerFactory.getManager(contextId); + } + + if (webSecurityManager == null && logNull) { + LOG.log(WARNING, "realmAdapter.noWebSecMgr", contextId); + } + } + + return webSecurityManager; + } + /** * Enforce any user data constraint required by the security constraint guarding this request URI. * @@ -361,14 +386,14 @@ public boolean hasUserDataPermission(HttpRequest request, HttpResponse response, return true; } - JaccWebAuthorizationManager authorizationManager = getJaccWebAuthorizationManager(true); - if (authorizationManager == null) { + WebSecurityManager securityManager = getWebSecurityManager(true); + if (securityManager == null) { return false; } int isGranted = 0; try { - isGranted = authorizationManager.hasUserDataPermission(httpServletRequest, uri, method); + isGranted = 0; } catch (IllegalArgumentException e) { // End the request after getting IllegalArgumentException while checking user data permission sendBadRequest(response, e); @@ -446,10 +471,10 @@ public int preAuthenticateCheck(HttpRequest request, HttpResponse response, Secu disableProxyCaching(request, response, disableProxyCaching, securePagesWithPragma); if (ssoEnabled) { HttpServletRequest httpServletRequest = (HttpServletRequest) request.getRequest(); - if (!getJaccWebAuthorizationManager(true).isPermitAll(httpServletRequest)) { + //if (!getJaccWebAuthorizationManager(true).isPermitAll(httpServletRequest)) { // Create a session for protected SSO association httpServletRequest.getSession(true); - } + //} } } return AUTHENTICATE_NOT_NEEDED; @@ -482,10 +507,10 @@ public int preAuthenticateCheck(HttpRequest request, HttpResponse response, Secu @Override public boolean invokeAuthenticateDelegate(HttpRequest request, HttpResponse response, Context context, Authenticator authenticator, boolean calledFromAuthenticate) throws IOException { - if (jaspicRealm.isJaspicEnabled()) { + /*if (jaspicRealm.isJaspicEnabled()) { // JASPIC (JSR 196) is enabled for this application - return jaspicRealm.validateRequest(request, response, context, authenticator, calledFromAuthenticate, e -> !getJaccWebAuthorizationManager(true).isPermitAll(e)); - } + return jaspicRealm.validateRequest(request, response, context, authenticator, calledFromAuthenticate, e -> !getWebSecurityManager(true).isPermitAll(e)); + }*/ // JASPIC (JSR 196) is not enabled. Use the passed-in Catalina authenticator. return ((AuthenticatorBase) authenticator).authenticate(request, response, context.getLoginConfig()); @@ -514,7 +539,7 @@ public void setVirtualServer(Object container) { @Override public void updateWebSecurityManager() { - if (jaccWebAuthorizationManager == null) { + /*if (jaccWebAuthorizationManager == null) { jaccWebAuthorizationManager = getJaccWebAuthorizationManager(true); } @@ -527,8 +552,8 @@ public void updateWebSecurityManager() { } jaccWebAuthorizationManager = webSecurityManagerFactory.createManager(webDescriptor, true, serverContext); - LOG.fine(() -> "JaccWebAuthorizationManager for " + jaccContextId + " has been updated"); - } + LOG.fine(() -> "WebAuthorizationManagerService for " + contextId + " has been updated"); + }*/ } /** @@ -657,12 +682,12 @@ public boolean invokePostAuthenticateDelegate(HttpRequest request, HttpResponse */ @Override public boolean hasRole(HttpRequest request, HttpResponse response, Principal principal, String role) { - JaccWebAuthorizationManager authorizationManager = getJaccWebAuthorizationManager(true); + WebSecurityManager authorizationManager = getWebSecurityManager(true); if (authorizationManager == null) { return false; } String servletName = getCanonicalName(request); - boolean isGranted = authorizationManager.hasRoleRefPermission(servletName, role, principal); + boolean isGranted = true;//authorizationManager.hasRoleRefPermission(servletName, role, principal); LOG.fine(() -> "Checking if servlet " + servletName + " with principal " + principal + " has role " + role + " isGranted: " + isGranted); return isGranted; @@ -724,17 +749,17 @@ public boolean authenticate(WebPrincipal principal) { * This will log a warning if the manager is not found in the factory, and logNull is true. * */ - public JaccWebAuthorizationManager getJaccWebAuthorizationManager(boolean logNull) { - if (jaccWebAuthorizationManager == null) { + public WebSecurityManager getWebAuthorizationManager(boolean logNull) { + if (webSecurityManager == null) { synchronized (this) { - jaccWebAuthorizationManager = webSecurityManagerFactory.getManager(jaccContextId, null, false); + webSecurityManager = webSecurityManagerFactory.getManager(contextId, false); } - if (jaccWebAuthorizationManager == null && logNull) { - LOG.log(WARNING, "realmAdapter.noWebSecMgr", jaccContextId); + if (webSecurityManager == null && logNull) { + LOG.log(WARNING, "realmAdapter.noWebSecMgr", contextId); } } - return jaccWebAuthorizationManager; + return webSecurityManager; } /** @@ -760,12 +785,12 @@ public Principal createFailOveredPrincipal(String username) { } public boolean hasRole(String servletName, Principal principal, String role) { - JaccWebAuthorizationManager authorizationManager = getJaccWebAuthorizationManager(true); - if (authorizationManager == null) { + WebSecurityManager webSecurityManager = getWebAuthorizationManager(true); + if (webSecurityManager == null) { return false; } - return authorizationManager.hasRoleRefPermission(servletName, role, principal); + return true; } /** @@ -1058,12 +1083,12 @@ private boolean invokeWebSecurityManager(HttpRequest request, HttpResponse respo LOG.fine(() -> "[Web-Security] [ hasResourcePermission ] Principal: " + httpServletRequest.getUserPrincipal() + " ContextPath: " + httpServletRequest.getContextPath()); - JaccWebAuthorizationManager authorizationManager = getJaccWebAuthorizationManager(true); + WebSecurityManager authorizationManager = getWebSecurityManager(true);//getJaccWebAuthorizationManager(true); if (authorizationManager == null) { return false; } - return authorizationManager.hasResourcePermission(httpServletRequest); + return true;//authorizationManager.hasResourcePermission(httpServletRequest); } private boolean redirect(HttpRequest request, HttpResponse response) throws IOException { @@ -1324,6 +1349,15 @@ private boolean hasRequestPrincipal(HttpRequest request) { return ((HttpServletRequest) request).getUserPrincipal() != null; } + private boolean isJakartaAuthenticationEnabled() throws IOException { + try { + //return authenticationService != null && authenticationService.getServerAuthConfig() != null; + return true; + } catch (Exception ex) { + throw new IOException(ex); + } + } + @FunctionalInterface public interface IOSupplier { diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java index 1397eb3e167..383ee2da179 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java @@ -93,7 +93,7 @@ import com.sun.enterprise.security.common.AppservAccessController; import com.sun.enterprise.security.common.ClientSecurityContext; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; -import com.sun.enterprise.security.ee.authorize.EJBPolicyContextDelegate; +import com.sun.enterprise.security.ee.authorization.EJBPolicyContextDelegate; import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; import com.sun.enterprise.security.jaspic.config.HandlerContext; import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServices; diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java index 85b7961082f..e7aff2dfe4c 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java @@ -40,14 +40,17 @@ // Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.webservices; -import java.util.Iterator; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - +import com.sun.enterprise.deployment.ServiceRefPortInfo; +import com.sun.enterprise.deployment.ServiceReferenceDescriptor; +import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; +import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; +import com.sun.xml.ws.api.message.Message; +import com.sun.xml.ws.api.message.Packet; +import com.sun.xml.ws.api.model.wsdl.WSDLBoundOperation; +import com.sun.xml.ws.api.model.wsdl.WSDLPort; import jakarta.inject.Singleton; import jakarta.security.auth.message.MessageInfo; -import javax.xml.namespace.QName; import jakarta.xml.soap.MimeHeaders; import jakarta.xml.soap.Name; import jakarta.xml.soap.Node; @@ -57,22 +60,13 @@ import jakarta.xml.soap.SOAPException; import jakarta.xml.soap.SOAPMessage; import jakarta.xml.soap.SOAPPart; - -import org.glassfish.api.invocation.ComponentInvocation; +import java.util.Iterator; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.xml.namespace.QName; import org.jvnet.hk2.annotations.Service; -import com.sun.enterprise.deployment.ServiceRefPortInfo; -import com.sun.enterprise.deployment.ServiceReferenceDescriptor; -import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; -import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; -import com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo; -import com.sun.enterprise.security.jauth.jaspic.provider.SOAPAuthParam; -import org.glassfish.epicyro.services.AuthConfigRegistrationWrapper; -import com.sun.xml.ws.api.message.Message; -import com.sun.xml.ws.api.message.Packet; -import com.sun.xml.ws.api.model.wsdl.WSDLBoundOperation; -import com.sun.xml.ws.api.model.wsdl.WSDLPort; - /** * * @author kumar.jayanti @@ -86,7 +80,7 @@ public class WebServicesDelegateImpl implements WebServicesDelegate { private static final String DEFAULT_WEBSERVICES_PROVIDER = "com.sun.xml.wss.provider.wsit.WSITAuthConfigProvider"; @Override - public MessageSecurityBindingDescriptor getBinding(ServiceReferenceDescriptor svcRef, Map properties) { + public MessageSecurityBindingDescriptor getBinding(ServiceReferenceDescriptor svcRef, Map properties) { MessageSecurityBindingDescriptor binding = null; WSDLPort p = (WSDLPort) properties.get("WSDL_MODEL"); QName portName = null; @@ -101,13 +95,7 @@ public MessageSecurityBindingDescriptor getBinding(ServiceReferenceDescriptor sv } return binding; } - - @Override - public void removeListener(AuthConfigRegistrationWrapper listener) { - // TODO:V3 convert the pipes to Tubes. - ClientPipeCloser.getInstance().removeListenerWrapper(listener); - } - + @Override public String getDefaultWebServicesProvider() { return DEFAULT_WEBSERVICES_PROVIDER; diff --git a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserNameAndPassword.java b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserNameAndPassword.java index 18c0235652e..f96494d6af8 100644 --- a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserNameAndPassword.java +++ b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserNameAndPassword.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation * Copyright (c) 2022 Eclipse Foundation and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the diff --git a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserPrincipal.java b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserPrincipal.java index 41f5bc61061..0e0fb70fa1b 100644 --- a/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserPrincipal.java +++ b/nucleus/common/common-util/src/main/java/org/glassfish/security/common/UserPrincipal.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation * Copyright (c) 2022 Eclipse Foundation and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/factory/SecurityManagerFactory.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/factory/SecurityManagerFactory.java index 87220c9cde9..de425d788c6 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/factory/SecurityManagerFactory.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/factory/SecurityManagerFactory.java @@ -128,7 +128,7 @@ public ArrayList getManagers(Map> iD2sMmap, String * aiD2sMmap. * @return a non-empty ArrayList containing the selected managers, or null. */ - public List getManagersForApp(Map> iD2sMmap, Map> app2iDmap, String appName, boolean remove) { + public ArrayList getManagersForApp(Map> iD2sMmap, Map> app2iDmap, String appName, boolean remove) { ArrayList managerList = null; String[] ctxIds = getContextsForApp(app2iDmap, appName, remove); From ff2e31a5258c006c342ef979864c7498483203d6 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Mon, 25 Nov 2024 21:29:30 -0600 Subject: [PATCH 18/34] FISH-8925: trying to fix error to render pages --- .../connectors/ConnectorRuntime.java | 4 +- appserver/security/core-ee/osgi.bundle | 1 + .../security/ee/JavaEESecurityLifecycle.java | 28 +- .../security/ee/SecurityDeployer.java | 8 +- .../BaseContainerCallbackHandler.java | 27 +- .../ClientContainerCallbackHandler.java | 4 +- .../callback/ContainerCallbackHandler.java | 4 +- .../ServerContainerCallbackHandler.java | 39 +- .../jakarta}/callback/ServerLoginCBHUtil.java | 4 +- .../WebAuthorizationManagerService.java | 2 +- .../WebSecurityManagerFactory.java | 33 +- .../config/PayaraEpicyroServletServices.java | 2 + .../security/jaspic/package-info.java | 3 +- .../com/sun/web/security/RealmAdapter.java | 751 +++++++++++++++--- .../security/realmadapter/JaspicRealm.java | 624 --------------- .../webservices/WebServicesDelegateImpl.java | 57 +- .../catalina/connector/RequestFacade.java | 20 + .../java/com/sun/enterprise/util/Utility.java | 22 +- .../enterprise/security/SecurityContext.java | 12 +- .../auth/login/LoginContextDriver.java | 152 +++- 20 files changed, 981 insertions(+), 816 deletions(-) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic => ee/authentication/jakarta}/callback/BaseContainerCallbackHandler.java (96%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic => ee/authentication/jakarta}/callback/ClientContainerCallbackHandler.java (98%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic => ee/authentication/jakarta}/callback/ContainerCallbackHandler.java (96%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic => ee/authentication/jakarta}/callback/ServerContainerCallbackHandler.java (73%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic => ee/authentication/jakarta}/callback/ServerLoginCBHUtil.java (95%) delete mode 100644 appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java diff --git a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/ConnectorRuntime.java b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/ConnectorRuntime.java index 4903182d4a6..ad24a1560d2 100755 --- a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/ConnectorRuntime.java +++ b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/ConnectorRuntime.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.connectors; @@ -61,7 +61,7 @@ import com.sun.enterprise.resource.pool.monitor.ConnectionPoolProbeProviderUtil; import com.sun.enterprise.resource.pool.monitor.PoolMonitoringLevelListener; import com.sun.enterprise.security.SecurityServicesUtil; -import com.sun.enterprise.security.jaspic.callback.ContainerCallbackHandler; +import com.sun.enterprise.security.ee.authentication.jakarta.callback.ContainerCallbackHandler; import com.sun.enterprise.transaction.api.JavaEETransactionManager; import com.sun.enterprise.util.Utility; import com.sun.logging.LogDomains; diff --git a/appserver/security/core-ee/osgi.bundle b/appserver/security/core-ee/osgi.bundle index 4b500d1fce5..35dbe68e0c6 100644 --- a/appserver/security/core-ee/osgi.bundle +++ b/appserver/security/core-ee/osgi.bundle @@ -47,6 +47,7 @@ com.sun.enterprise.security.auth.realm.jdbc; \ com.sun.enterprise.security.ee.authorization; \ com.sun.enterprise.security.ee.authentication.jakarta; \ + com.sun.enterprise.security.ee.authentication.jakarta.callback; \ com.sun.enterprise.security.ee.web; \ com.sun.enterprise.security.ee.web.integration; \ com.sun.enterprise.security.jauth; \ diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java index f6bd5805610..8218e65592b 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java @@ -68,6 +68,7 @@ import static jakarta.security.auth.message.config.AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY; import static org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory.DEFAULT_FACTORY_DEFAULT_PROVIDERS; +import static java.util.logging.Level.WARNING; /** @@ -85,22 +86,34 @@ public class JavaEESecurityLifecycle implements ContainerSecurityLifecycle, Post @Inject PolicyLoader policyLoader; - @Inject - private ServiceLocator habitat; - @Override public void postConstruct() { onInitialization(); + initializeJakartaAuthentication(); + initializeJakartaAuthorization(); } @Override public void onInitialization() { - initializeJakartaAuthentication(); - initializeJakartaAuthorization(); + LOG.finest(() -> "Initializing " + getClass()); + + // TODO: Need some way to not override the security manager if the EmbeddedServer was + // run with a different non-default security manager. + // + // Right now there seems no way to find out if the security manager is the VM's default security manager. + final SecurityManager systemSecurityManager = System.getSecurityManager(); + if (systemSecurityManager != null && !(J2EESecurityManager.class.equals(systemSecurityManager.getClass()))) { + J2EESecurityManager eeSecurityManager = new J2EESecurityManager(); + try { + System.setSecurityManager(eeSecurityManager); + LOG.config(() -> "System security manager has been set to " + eeSecurityManager); + } catch (SecurityException ex) { + LOG.log(WARNING, "security.secmgr.could.not.override", ex); + } + } } private void initializeJakartaAuthentication() { - // Define default factory if it is not already defined. // The factory will be constructed on first getFactory call. @@ -110,8 +123,7 @@ private void initializeJakartaAuthentication() { } String defaultProvidersString = null; - //WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); - WebServicesDelegate delegate = habitat.getService(WebServicesDelegate.class); + WebServicesDelegate delegate = Globals.get(WebServicesDelegate.class); if (delegate == null) { defaultProvidersString = GFServerConfigProvider.class.getName(); } else { diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java index 9ad59455613..ccdf2f64323 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java @@ -260,8 +260,8 @@ public void loadPolicy(WebBundleDescriptor webDescriptor, boolean remove) throws } try { if (remove) { - WebSecurityManager authorizationManager = webSecurityManagerFactory - .getManager(getContextID(webDescriptor), true); + WebAuthorizationManagerService authorizationManager = webSecurityManagerFactory + .getManager(getContextID(webDescriptor), null,true); if (authorizationManager != null) { authorizationManager.release(); } @@ -402,12 +402,12 @@ private void removePolicy(DeploymentContext context) throws DeploymentException private boolean cleanSecurityContext(String appName) { boolean cleanUpDone = false; - List managers = webSecurityManagerFactory.getManagersForApp(appName, false); + List managers = webSecurityManagerFactory.getManagersForApp(appName, false); if (managers == null) { return false; } - for (WebSecurityManager manager : managers) { + for (WebAuthorizationManagerService manager : managers) { try { websecurityProbeProvider.securityManagerDestructionStartedEvent(appName); manager.destroy(); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/BaseContainerCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/BaseContainerCallbackHandler.java similarity index 96% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/BaseContainerCallbackHandler.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/BaseContainerCallbackHandler.java index df643ab1208..9f8905cfa3d 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/BaseContainerCallbackHandler.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/BaseContainerCallbackHandler.java @@ -45,7 +45,7 @@ * Created on April 21, 2004, 11:56 AM */ -package com.sun.enterprise.security.jaspic.callback; +package com.sun.enterprise.security.ee.authentication.jakarta.callback; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityServicesUtil; @@ -69,6 +69,8 @@ import jakarta.security.auth.message.callback.PrivateKeyCallback; import jakarta.security.auth.message.callback.SecretKeyCallback; import jakarta.security.auth.message.callback.TrustStoreCallback; +import org.glassfish.epicyro.config.helper.Caller; +import org.glassfish.epicyro.services.InMemoryStore; import org.glassfish.internal.api.Globals; import org.glassfish.security.common.Group; import org.glassfish.security.common.MasterPassword; @@ -429,8 +431,8 @@ private void processGroupPrincipal(GroupPrincipalCallback groupCallback) { } } - private void processPasswordValidation(PasswordValidationCallback pwdCallback) { - if (SecurityServicesUtil.getInstance().isACC()) { + protected void processPasswordValidation(PasswordValidationCallback pwdCallback) { + /*if (SecurityServicesUtil.getInstance().isACC()) { _logger.log(Level.FINE, "JASPIC: In PasswordValidationCallback Processor for appclient - will do nothing"); pwdCallback.setResult(true); return; @@ -462,7 +464,26 @@ private void processPasswordValidation(PasswordValidationCallback pwdCallback) { // login failed _logger.log(Level.INFO, "jaspic.loginfail", username); pwdCallback.setResult(false); + }*/ + // Default to a very basic in memory identity store. + // Clients may want to override this for more advanced features. + Caller caller = InMemoryStore.validate(pwdCallback.getUsername(), getPassword(pwdCallback)); + if (caller != null) { + processCallerPrincipal(new CallerPrincipalCallback(pwdCallback.getSubject(), caller.getCallerPrincipal())); + if (!caller.getGroups().isEmpty()) { + processGroupPrincipal(new GroupPrincipalCallback(pwdCallback.getSubject(), caller.getGroupsAsArray())); + } + pwdCallback.setResult(true); + } + } + + private String getPassword(PasswordValidationCallback pwdCallback) { + char[] password = pwdCallback.getPassword(); + if (password == null) { + return null; } + + return new String(password); } private void processPrivateKey(PrivateKeyCallback privKeyCallback) { diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ClientContainerCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ClientContainerCallbackHandler.java similarity index 98% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ClientContainerCallbackHandler.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ClientContainerCallbackHandler.java index f579f7dddd0..c06ae885df7 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ClientContainerCallbackHandler.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ClientContainerCallbackHandler.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] /* * ClientContainerCallbackHandler.java @@ -45,7 +45,7 @@ * Created on September 14, 2004, 12:20 PM */ -package com.sun.enterprise.security.jaspic.callback; +package com.sun.enterprise.security.ee.authentication.jakarta.callback; import com.sun.enterprise.security.SecurityServicesUtil; import java.io.IOException; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ContainerCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ContainerCallbackHandler.java similarity index 96% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ContainerCallbackHandler.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ContainerCallbackHandler.java index aa8dd70b70c..75fcafaaee8 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ContainerCallbackHandler.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ContainerCallbackHandler.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] /* * ContainerCallbackHandler @@ -45,7 +45,7 @@ * Created on April 21, 2004, 11:56 AM */ -package com.sun.enterprise.security.jaspic.callback; +package com.sun.enterprise.security.ee.authentication.jakarta.callback; import com.sun.enterprise.security.SecurityServicesUtil; import com.sun.enterprise.security.jaspic.config.CallbackHandlerConfig; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ServerContainerCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerContainerCallbackHandler.java similarity index 73% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ServerContainerCallbackHandler.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerContainerCallbackHandler.java index f9746d886b2..001d90b6a6f 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ServerContainerCallbackHandler.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerContainerCallbackHandler.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] /* * ServerContainerCallbackHandler.java @@ -45,7 +45,7 @@ * Created on September 14, 2004, 12:56 PM */ -package com.sun.enterprise.security.jaspic.callback; +package com.sun.enterprise.security.ee.authentication.jakarta.callback; import java.io.IOException; @@ -58,6 +58,8 @@ import jakarta.security.auth.message.callback.PrivateKeyCallback; import jakarta.security.auth.message.callback.SecretKeyCallback; import jakarta.security.auth.message.callback.TrustStoreCallback; +import com.sun.enterprise.security.auth.login.LoginContextDriver; +import com.sun.enterprise.security.auth.login.common.LoginException; /** * Callback Handler for ServerContainer @@ -65,11 +67,17 @@ * @author Harpreet Singh * @author Shing Wai Chan */ -final class ServerContainerCallbackHandler extends BaseContainerCallbackHandler { +final public class ServerContainerCallbackHandler extends BaseContainerCallbackHandler { + + private String realmName; ServerContainerCallbackHandler() { } + public ServerContainerCallbackHandler(String realmName) { + this.realmName = realmName; + } + protected void handleSupportedCallbacks(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { processCallback(callback); @@ -85,4 +93,29 @@ protected boolean isSupportedCallback(Callback callback) { || callback instanceof PrivateKeyCallback || callback instanceof TrustStoreCallback; } + + @Override + protected void processPasswordValidation(PasswordValidationCallback pwdCallback) { + String username = pwdCallback.getUsername(); + char[] password = pwdCallback.getPassword(); + + try { + LoginContextDriver.jmacLogin(pwdCallback.getSubject(), username, password, realmName); + ditchPassword(password); + + pwdCallback.setResult(true); + } catch (LoginException le) { + // Login failed + pwdCallback.setResult(false); + } + } + + private void ditchPassword(char[] passwd) { + // Explicitly ditch the password + if (passwd != null) { + for (int i = 0; i < passwd.length; i++) { + passwd[i] = ' '; + } + } + } } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ServerLoginCBHUtil.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerLoginCBHUtil.java similarity index 95% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ServerLoginCBHUtil.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerLoginCBHUtil.java index b78b109f67b..2f144cb935e 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/callback/ServerLoginCBHUtil.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerLoginCBHUtil.java @@ -37,8 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.callback; +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authentication.jakarta.callback; import static com.sun.enterprise.security.common.AppservAccessController.privileged; import static java.util.Arrays.stream; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java index d2dc043143d..69c0711736d 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java @@ -188,7 +188,7 @@ public class WebAuthorizationManagerService { private final ThreadLocal currentRequest = new ThreadLocal<>(); private AuthorizationService authorizationService; - public JaccWebAuthorizationManager(WebBundleDescriptor webBundleDescriptor, ServerContext serverContext, WebSecurityManagerFactory webSecurityManagerFactory, boolean register) throws PolicyContextException { + public WebAuthorizationManagerService(WebBundleDescriptor webBundleDescriptor, ServerContext serverContext, WebSecurityManagerFactory webSecurityManagerFactory, boolean register) throws PolicyContextException { this.register = register; this.webBundleDescriptor = webBundleDescriptor; this.CONTEXT_ID = getContextID(webBundleDescriptor); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java index 83dd5ca5965..99225be7920 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java @@ -45,6 +45,7 @@ import com.sun.enterprise.security.factory.SecurityManagerFactory; import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; import com.sun.enterprise.security.jacc.context.PolicyContextRegistration; +import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; import java.security.Principal; import java.util.ArrayList; @@ -86,17 +87,17 @@ public class WebSecurityManagerFactory extends SecurityManagerFactory { // Stores the Context IDs to application names for standalone web applications private final Map> CONTEXT_IDS = new HashMap<>(); - private final Map> SECURITY_MANAGERS = new HashMap<>(); + private final Map> SECURITY_MANAGERS = new HashMap<>(); public WebSecurityManagerFactory() { // Registers the JACC policy handlers, which provide objects JACC Providers and other code can use PolicyContextRegistration.registerPolicyHandlers(); } - public WebSecurityManager createManager(WebBundleDescriptor webBundleDescriptor, boolean register, ServerContext context) { + public WebAuthorizationManagerService createManager(WebBundleDescriptor webBundleDescriptor, boolean register, ServerContext context) { String contextId = AuthorizationUtil.getContextID(webBundleDescriptor); - WebSecurityManager manager = null; + WebAuthorizationManagerService manager = null; if (register) { manager = getManager(contextId, false); } @@ -108,7 +109,7 @@ public WebSecurityManager createManager(WebBundleDescriptor webBundleDescriptor, // As "side-effect" of constructing the manager, the web constraints in the web bundle // descriptor will be translated to permissions and loaded into a JACC policy configuration - manager = new WebSecurityManager(webBundleDescriptor, context, this, register); + manager = new WebAuthorizationManagerService(webBundleDescriptor, context, this, register); probeProvider.securityManagerCreationEndedEvent(webBundleDescriptor.getModuleID()); @@ -124,23 +125,27 @@ public WebSecurityManager createManager(WebBundleDescriptor webBundleDescriptor, return manager; } - public void addManagerToApp(String ctxId, String name, String appName, WebSecurityManager manager) { + public void addManagerToApp(String ctxId, String name, String appName, WebAuthorizationManagerService manager) { addManagerToApp(SECURITY_MANAGERS, CONTEXT_IDS, ctxId, name, appName, manager); } - public WebSecurityManager getManager(String contextId) { + public WebAuthorizationManagerService getManager(String ctxId, String name, boolean remove) { + return getManager(SECURITY_MANAGERS, ctxId, name, remove); + } + + public WebAuthorizationManagerService getManager(String contextId) { return getManager(SECURITY_MANAGERS, contextId, null, false); } - public WebSecurityManager getManager(String contextId, boolean remove) { + public WebAuthorizationManagerService getManager(String contextId, boolean remove) { return getManager(SECURITY_MANAGERS, contextId, null, remove); } - public ArrayList getManagers(String contextId, boolean remove) { + public ArrayList getManagers(String contextId, boolean remove) { return getManagers(SECURITY_MANAGERS, contextId, remove); } - - public ArrayList getManagersForApp(String appName, boolean remove) { + + public ArrayList getManagersForApp(String appName, boolean remove) { return getManagersForApp(SECURITY_MANAGERS, CONTEXT_IDS, appName, remove); } @@ -168,4 +173,12 @@ public void putAdminGroup(String group, String realmName, Group principal) { adminGroups.put(realmName + group, principal); } + public void addAdminPrincipal(String username, String realmName, Principal principal) { + adminPrincipalsPerApp.put(realmName + username, principal); + } + + public void addAdminGroup(String group, String realmName, Principal principal) { + adminGroupsPerApp.put(realmName + group, principal); + } + } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java index c5a9242dfd4..cfc6b397dde 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java @@ -42,6 +42,7 @@ import static com.sun.enterprise.deployment.web.LoginConfiguration.CLIENT_CERTIFICATION_AUTHENTICATION; +import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.POLICY_CONTEXT; @@ -57,6 +58,7 @@ import com.sun.enterprise.deployment.runtime.web.SunWebApp; import com.sun.enterprise.deployment.web.LoginConfiguration; import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; +import org.glassfish.internal.api.Globals; public class PayaraEpicyroServletServices extends PayaraEpicyroServices { diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java index f980089d138..474634b9976 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java @@ -1,7 +1,7 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * - * Copyright (c) [2019] Payara Foundation and/or its affiliates. + * Copyright (c) [2019-2024] Payara Foundation and/or its affiliates. * All rights reserved. * * The contents of this file are subject to the terms of either the GNU @@ -62,7 +62,6 @@ *

* The pluggable authentication mechanisms are managed by the * {@link jakarta.security.auth.message.config.AuthConfigFactory}. The Payara specific implementation of this is - * {@link com.sun.enterprise.security.jaspic.config.GFAuthConfigFactory}, which is installed by * com.sun.enterprise.security.ee.JavaEESecurityLifecycle. * */ diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index 4c9ab2883e0..d714f2a37b6 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -55,29 +55,50 @@ import com.sun.enterprise.security.auth.digest.impl.DigestParameterGenerator; import com.sun.enterprise.security.auth.digest.impl.HttpAlgorithmParameterImpl; import com.sun.enterprise.security.auth.login.DigestCredentials; +import com.sun.enterprise.security.auth.login.DistinguishedPrincipalCredential; +import com.sun.enterprise.security.auth.login.LoginContextDriver; +import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; +import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; +import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; +import com.sun.enterprise.security.ee.authentication.jakarta.callback.ServerContainerCallbackHandler; import com.sun.enterprise.security.integration.RealmInitializer; import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; import com.sun.enterprise.security.web.integration.WebPrincipal; -import com.sun.enterprise.security.ee.web.integration.WebSecurityManager; import com.sun.enterprise.security.ee.web.integration.WebSecurityManagerFactory; import com.sun.enterprise.util.net.NetUtils; import com.sun.logging.LogDomains; import com.sun.web.security.realmadapter.AuthenticatorProxy; -import com.sun.web.security.realmadapter.JaspicRealm; import fish.payara.nucleus.requesttracing.RequestTracingService; +import jakarta.security.auth.message.AuthStatus; +import jakarta.security.auth.message.MessageInfo; +import jakarta.security.auth.message.config.ServerAuthContext; +import java.io.UncheckedIOException; +import java.util.Map; +import java.util.Set; +import javax.security.auth.x500.X500Principal; import org.apache.catalina.*; import org.apache.catalina.authenticator.AuthenticatorBase; +import org.apache.catalina.authenticator.Constants; +import org.apache.catalina.connector.RequestFacade; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.realm.RealmBase; import org.glassfish.api.invocation.ComponentInvocation; +import org.glassfish.epicyro.config.helper.Caller; +import org.glassfish.epicyro.config.helper.CallerPrincipal; +import org.glassfish.epicyro.config.helper.HttpServletConstants; +import org.glassfish.epicyro.config.servlet.HttpMessageInfo; +import org.glassfish.epicyro.services.BaseAuthenticationService; +import org.glassfish.epicyro.services.DefaultAuthenticationService; import org.glassfish.grizzly.config.dom.NetworkConfig; import org.glassfish.grizzly.config.dom.NetworkListener; import org.glassfish.grizzly.config.dom.NetworkListeners; import org.glassfish.hk2.api.PerLookup; import org.glassfish.hk2.api.PostConstruct; import org.glassfish.internal.api.ServerContext; +import org.glassfish.security.common.Group; +import org.glassfish.security.common.UserNameAndPassword; import org.jvnet.hk2.annotations.Service; import jakarta.inject.Inject; @@ -114,17 +135,27 @@ import static com.sun.enterprise.security.SecurityContext.setUnauthenticatedContext; import static com.sun.enterprise.security.auth.digest.api.Constants.A1; import static com.sun.enterprise.security.auth.digest.impl.DigestParameterGenerator.HTTP_DIGEST; +import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.REGISTER_WITH_AUTHENTICATOR; +import static com.sun.enterprise.util.Utility.isAllNull; import static com.sun.logging.LogDomains.WEB_LOGGER; +import static com.sun.web.security.realmadapter.AuthenticatorProxy.PROXY_AUTH_TYPE; import static java.lang.String.format; import static java.net.URLEncoder.encode; import static java.security.AccessController.doPrivileged; import static java.util.Arrays.asList; import static java.util.logging.Level.*; import static jakarta.servlet.http.HttpServletResponse.*; -import static org.apache.catalina.realm.Constants.FORM_ACTION; +import static org.apache.catalina.ContainerEvent.*; +import static org.apache.catalina.Globals.WRAPPED_REQUEST; +import static org.apache.catalina.Globals.WRAPPED_RESPONSE; import static org.apache.catalina.realm.Constants.FORM_METHOD; import static org.glassfish.api.admin.ServerEnvironment.DEFAULT_INSTANCE_NAME; +import static com.sun.enterprise.security.ee.web.integration.AuthorizationUtil.getContextID; +import static org.glassfish.epicyro.config.helper.HttpServletConstants.POLICY_CONTEXT; +import static org.glassfish.epicyro.config.helper.HttpServletConstants.REGISTER_SESSION; +import static com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy.WEB_BUNDLE; + /** * This is the realm adapter used to authenticate users and authorize access to web resources. The authenticate method * is called by Tomcat to authenticate users. The hasRole method is called by Tomcat during the authorization process. @@ -143,6 +174,9 @@ public class RealmAdapter extends RealmBase implements RealmInitializer, PostCon private static final Logger LOG = LogDomains.getLogger(RealmAdapter.class, WEB_LOGGER); private static final ResourceBundle resourceBundle = LOG.getResourceBundle(); + public static final String SERVER_AUTH_CONTEXT = "__jakarta.security.auth.message.ServerAuthContext"; + private static final String MESSAGE_INFO = "__jakarta.security.auth.message.MessageInfo"; + private WebBundleDescriptor webDescriptor; private HashMap runAsPrincipals; @@ -159,10 +193,12 @@ public class RealmAdapter extends RealmBase implements RealmInitializer, PostCon */ private String contextId; + private Container virtualServer; + /** * A WebAuthorizationManagerService object associated with a contextId */ - protected volatile WebSecurityManager webSecurityManager; + protected volatile WebAuthorizationManagerService webAuthorizationManagerService; protected boolean isCurrentURIincluded; @@ -177,6 +213,8 @@ public class RealmAdapter extends RealmBase implements RealmInitializer, PostCon private String moduleID; + private BaseAuthenticationService authenticationService; + @Inject private ServerContext serverContext; @@ -201,7 +239,6 @@ public class RealmAdapter extends RealmBase implements RealmInitializer, PostCon private NetworkListeners nwListeners; - private JaspicRealm jaspicRealm; private CNonceValidator cNonceValidator; /** @@ -211,6 +248,8 @@ public class RealmAdapter extends RealmBase implements RealmInitializer, PostCon */ private static ThreadLocal reentrancyStatus = ThreadLocal.withInitial(() -> new byte[] { 0 }); + private static final String PROXY_AUTH_TYPE = "PLUGGABLE_PROVIDER"; + public RealmAdapter() { // used during Injection in WebContainer (glue code) } @@ -254,10 +293,19 @@ public void initializeRealm(Object bundleDescriptor, boolean isSystemApp, String } moduleID = webDescriptor.getModuleID(); - jaspicRealm = new JaspicRealm(realmName, isSystemApp, webDescriptor, requestTracing); cNonceValidator = new CNonceValidator(webDescriptor, appCNonceCacheMapProvider, cNonceCacheFactoryProvider); } + /** + * Sets the virtual server on which the web module (with which this RealmAdapter is associated with) has been deployed. + * + * @param container The virtual server + */ + @Override + public void setVirtualServer(Object container) { + this.virtualServer = (Container) container; + } + /** * Return true if JASPIC is available. * @@ -265,9 +313,73 @@ public void initializeRealm(Object bundleDescriptor, boolean isSystemApp, String */ @Override public boolean isSecurityExtensionEnabled(ServletContext context) { - return jaspicRealm.isJaspicEnabled(context); + if (authenticationService == null) { + initAuthenticationService(context); + } + + try { + return (authenticationService.getServerAuthConfig() != null); + } catch (Exception ex) { + throw new RuntimeException(ex); + } } + public synchronized void initAuthenticationService(final ServletContext servletContext) { + if (this.authenticationService != null) { + return; + } + + try { + this.authenticationService = createAuthenticationService(servletContext); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private BaseAuthenticationService createAuthenticationService(final ServletContext servletContext) throws IOException { + Map properties = new HashMap<>(); + + String policyContextId = getContextID(webDescriptor); + if (policyContextId != null) { + properties.put(POLICY_CONTEXT, policyContextId); + } + + // "authModuleId" (HttpServletSecurityProvider) is a GlassFish proprietary mechanism where a + // Jakarta Authentication module gets assigned an ID in the proprietary config of GlassFish (domain.xml). + // This ID is then used in glassfish-web.xml to indicate that a war wants to use that authentication module. + String authModuleId = + AuthMessagePolicy.getProviderID( + AuthMessagePolicy.getSunWebApp(Map.of( + WEB_BUNDLE, webDescriptor))); + + if (authModuleId != null) { + properties.put("authModuleId", authModuleId); + } + + String appContextId = getAppContextID(servletContext); + + return new DefaultAuthenticationService( + appContextId, + properties, + new ConfigDomainParser(), + new ServerContainerCallbackHandler(realmName)); + } + + /** + * This must be invoked after virtualServer is set. + */ + private String getAppContextID(final ServletContext servletContext) { + if (!servletContext.getVirtualServerName().equals(this.virtualServer.getName())) { + LOG.log(WARNING, "Virtual server name from ServletContext: {0} differs from name from virtual.getName(): {1}", + new Object[] { servletContext.getVirtualServerName(), virtualServer.getName() }); + } + if (!servletContext.getContextPath().equals(webDescriptor.getContextRoot())) { + LOG.log(WARNING, "Context path from ServletContext: {0} differs from path from bundle: {1}", + new Object[] { servletContext.getContextPath(), webDescriptor.getContextRoot() }); + } + return servletContext.getVirtualServerName() + " " + servletContext.getContextPath(); + } + /** * One of the initial operations being done to apply security to a request, is to find out if there are security constraints * for a request. @@ -295,18 +407,16 @@ public SecurityConstraint[] findSecurityConstraints(HttpRequest request, Context */ @Override public SecurityConstraint[] findSecurityConstraints(String requestPathMB, String httpMethod, Context context) { - if (!jaspicRealm.isInitialised()) { - jaspicRealm.initJaspicServices(context.getServletContext()); + if (authenticationService == null) { + initAuthenticationService(context.getServletContext()); } - WebSecurityManager securityManager = getWebSecurityManager(false); - - if (securityManager != null) { - // No constraints + WebAuthorizationManagerService webAuthorizationManagerService = getWebSecurityManager(false); + if (webAuthorizationManagerService != null && webAuthorizationManagerService.hasNoConstrainedResources() + && !isSecurityExtensionEnabled(context.getServletContext())) { return null; } - // Constraints return emptyConstraints; } @@ -318,20 +428,20 @@ public SecurityConstraint[] findSecurityConstraints(String requestPathMB, String * instantiates a RealmAdapter * * @param logNull - * @return {@link WebSecurityManager} or null + * @return {@link webAuthorizationManagerService} or null */ - public WebSecurityManager getWebSecurityManager(boolean logNull) { - if (webSecurityManager == null && webSecurityManagerFactory != null) { + public WebAuthorizationManagerService getWebSecurityManager(boolean logNull) { + if (webAuthorizationManagerService == null && webSecurityManagerFactory != null) { synchronized (this) { - webSecurityManager = webSecurityManagerFactory.getManager(contextId); + webAuthorizationManagerService = webSecurityManagerFactory.getManager(contextId); } - if (webSecurityManager == null && logNull) { + if (webAuthorizationManagerService == null && logNull) { LOG.log(WARNING, "realmAdapter.noWebSecMgr", contextId); } } - return webSecurityManager; + return webAuthorizationManagerService; } /** @@ -386,14 +496,14 @@ public boolean hasUserDataPermission(HttpRequest request, HttpResponse response, return true; } - WebSecurityManager securityManager = getWebSecurityManager(true); + WebAuthorizationManagerService securityManager = getWebSecurityManager(true); if (securityManager == null) { return false; } int isGranted = 0; try { - isGranted = 0; + isGranted = securityManager.hasUserDataPermission(httpServletRequest, uri, method); } catch (IllegalArgumentException e) { // End the request after getting IllegalArgumentException while checking user data permission sendBadRequest(response, e); @@ -444,7 +554,8 @@ public boolean hasUserDataPermission(HttpRequest request, HttpResponse response, * @exception IOException if an input/output error occurs */ @Override - public int preAuthenticateCheck(HttpRequest request, HttpResponse response, SecurityConstraint[] constraints, boolean disableProxyCaching, boolean securePagesWithPragma, boolean ssoEnabled) throws IOException { + public int preAuthenticateCheck(HttpRequest request, HttpResponse response, SecurityConstraint[] constraints, + boolean disableProxyCaching, boolean securePagesWithPragma, boolean ssoEnabled) throws IOException { boolean isGranted = false; try { @@ -453,7 +564,7 @@ public int preAuthenticateCheck(HttpRequest request, HttpResponse response, Secu } // JASPIC enabled; always give the SAM the opportunity to authenticate - if (jaspicRealm.isJaspicEnabled()) { + if (isJakartaAuthenticationEnabled()) { return AUTHENTICATE_NEEDED; } @@ -471,10 +582,10 @@ public int preAuthenticateCheck(HttpRequest request, HttpResponse response, Secu disableProxyCaching(request, response, disableProxyCaching, securePagesWithPragma); if (ssoEnabled) { HttpServletRequest httpServletRequest = (HttpServletRequest) request.getRequest(); - //if (!getJaccWebAuthorizationManager(true).isPermitAll(httpServletRequest)) { + if (!getWebSecurityManager(true).isPermitAll(httpServletRequest)) { // Create a session for protected SSO association httpServletRequest.getSession(true); - //} + } } } return AUTHENTICATE_NOT_NEEDED; @@ -490,30 +601,319 @@ public int preAuthenticateCheck(HttpRequest request, HttpResponse response, Secu return AUTHENTICATE_NEEDED; } - /** - * Authenticates the user making this request, based on the specified authentication mechanism. - * - * Return true if any specified requirements have been satisfied, or false - * if we have created a response challenge already. - * - * @param request Request we are processing - * @param response Response we are creating - * @param context The Context to which client of this class is attached. - * @param authenticator the current authenticator. - * @param calledFromAuthenticate if the calls to this method comes from a call to HttpServletRequest.authenticate - * @return - * @exception IOException if an input/output error occurs - */ @Override public boolean invokeAuthenticateDelegate(HttpRequest request, HttpResponse response, Context context, Authenticator authenticator, boolean calledFromAuthenticate) throws IOException { + LoginConfig config = context.getLoginConfig(); - /*if (jaspicRealm.isJaspicEnabled()) { - // JASPIC (JSR 196) is enabled for this application - return jaspicRealm.validateRequest(request, response, context, authenticator, calledFromAuthenticate, e -> !getWebSecurityManager(true).isPermitAll(e)); - }*/ + if (isJakartaAuthenticationEnabled()) { + // Jakarta Authentication is enabled for this application + try { + context.fireContainerEvent(BEFORE_AUTHENTICATION, null); + RequestFacade requestFacade = (RequestFacade) request.getRequest(); + SecurityContext.getCurrent().setSessionPrincipal(requestFacade.getRequestPrincipal()); + return validateRequest(request, response, config, authenticator, calledFromAuthenticate); + } finally { + SecurityContext.getCurrent().setSessionPrincipal(null); + context.fireContainerEvent(AFTER_AUTHENTICATION, null); + } + } - // JASPIC (JSR 196) is not enabled. Use the passed-in Catalina authenticator. - return ((AuthenticatorBase) authenticator).authenticate(request, response, context.getLoginConfig()); + // Jakarta Authentication is not enabled. Use the current authenticator. + return ((AuthenticatorBase) authenticator).authenticate(request, response, config); + } + + private boolean validateRequest(HttpRequest request, HttpResponse response, LoginConfig config, Authenticator authenticator, boolean calledFromAuthenticate) throws IOException { + + HttpServletRequest servletRequest = (HttpServletRequest) request.getRequest(); + HttpServletResponse servletResponse = (HttpServletResponse) response.getResponse(); + + Subject subject = new Subject(); + MessageInfo messageInfo = new HttpMessageInfo(servletRequest, servletResponse); + + boolean isRequestValidated = false; + boolean isMandatory = true; + ServerAuthContext authContext = null; + + + try { + isMandatory = this.webAuthorizationManagerService.isPermitAll(servletRequest); + // Produce caller challenge if call originates from HttpServletRequest#authenticate + if (isMandatory || calledFromAuthenticate) { + messageInfo.getMap().put(HttpServletConstants.IS_MANDATORY, Boolean.TRUE.toString()); + } + + // Obtain the JASIC ServerAuthContext, which represents the authentication mechanism that interacts with the caller + authContext = authenticationService.getServerAuthContext(messageInfo, null); + + if (authContext == null) { + throw new AuthException("null ServerAuthContext"); + } + AuthStatus authStatus = authContext.validateRequest(messageInfo, subject, null); // null serviceSubject + isRequestValidated = AuthStatus.SUCCESS.equals(authStatus); + + if (isRequestValidated) { // cache it only if validateRequest = true + messageInfo.getMap().put(SERVER_AUTH_CONTEXT, authContext); + servletRequest.setAttribute(MESSAGE_INFO, messageInfo); + } + + } catch (AuthException | RuntimeException e) { + LOG.log(WARNING, "JASPIC: http msg authentication fail", e); + servletResponse.setStatus(SC_INTERNAL_SERVER_ERROR); + } + + if (isRequestValidated) { + Caller caller = getCaller(subject); + + // Must have a caller to establish non-default security context + if (caller != null) { + + // Convert Epicyro representation of the Caller Principal / Groups to the existing + // GlassFish one. A future version of this code may use the Epicyro one everywhere directly. + subject = new Subject(); + + // See if there's a Subject stored in the session that contain all relevant principals and + // credentials for reuse, and the caller has indicated to take these. + Subject sessionSubject = reuseSessionSubject(caller); + if (sessionSubject != null) { + // Copy principals, public credentials and private credentials from the Subject that lives in + // the session to the receiving Subject. + copySubject(subject, sessionSubject); + } else { + Principal glassFishCallerPrincipal = getGlassFishCallerPrincipal(caller); + + toSubject(subject, glassFishCallerPrincipal); + DistinguishedPrincipalCredential distinguishedPrincipal = new DistinguishedPrincipalCredential(glassFishCallerPrincipal); + + // Credentials don't serialize, so for now, also add to the subject principals + // For next version, see if we can only use principals + toSubject(subject, distinguishedPrincipal); + toSubjectCredential(subject, distinguishedPrincipal); + + for (String group : caller.getGroups()) { + toSubject(subject, new Group(group)); + } + + if (!glassFishCallerPrincipal.equals(SecurityContext.getDefaultCallerPrincipal())) { + + // Give native GlassFish (realms, mostly) opportunity to add groups + LoginContextDriver.jmacLogin(subject, glassFishCallerPrincipal, realmName); + + SecurityContext ctx = new SecurityContext(subject); + SecurityContext.setCurrent(ctx); + + // XXX assuming no null principal here + Principal principal = ctx.getCallerPrincipal(); + WebPrincipal webPrincipal = new WebPrincipal(principal, ctx); + try { + String authType = (String) messageInfo.getMap().get(HttpServletConstants.AUTH_TYPE); + if (authType == null && config != null && config.getAuthMethod() != null) { + authType = config.getAuthMethod(); + } + + if (shouldRegister(messageInfo.getMap())) { + // Sets webPrincipal for the session and request + new AuthenticatorProxy(authenticator, webPrincipal, authType) + .authenticate(request, response, config); + } else { + // Sets webPrincipal for the request only + request.setAuthType(authType == null ? PROXY_AUTH_TYPE : authType); + request.setUserPrincipal(webPrincipal); + } + } catch (LifecycleException le) { + LOG.log(SEVERE, "Unable to register session", le); + + } + + } else { + // GLASSFISH-20930.Set null for the case when SAM does not + // indicate that it needs the session + if (((HttpServletRequest) messageInfo.getRequestMessage()).getUserPrincipal() != null) { + request.setUserPrincipal(null); + request.setAuthType(null); + } + + if (isMandatory) { + isRequestValidated = false; + } + } + } + } + + if (isRequestValidated) { + HttpServletRequest newRequest = (HttpServletRequest) messageInfo.getRequestMessage(); + if (newRequest != servletRequest) { + request.setNote(WRAPPED_REQUEST, new HttpRequestWrapper(request, newRequest)); + } + + HttpServletResponse newResponse = (HttpServletResponse) messageInfo.getResponseMessage(); + if (newResponse != servletResponse) { + request.setNote(WRAPPED_RESPONSE, new HttpResponseWrapper(response, newResponse)); + } + } + + } + + return isRequestValidated; + } + + private boolean shouldRegister(Map map) { + /* + * Detect both the proprietary property and the standard one. + */ + return map.containsKey(REGISTER_WITH_AUTHENTICATOR) || mapEntryToBoolean(REGISTER_SESSION, map); + } + + private boolean mapEntryToBoolean(final String propName, final Map map) { + if (map.containsKey(propName)) { + Object value = map.get(propName); + if (value != null && value instanceof String) { + return Boolean.parseBoolean((String) value); + } + } + + return false; + } + + public static void toSubjectCredential(Subject subject, Object credential) { + subject.getPublicCredentials().add(credential); + } + + public static void toSubject(Subject subject, Principal principal) { + subject.getPrincipals().add(principal); + } + + private Principal getGlassFishCallerPrincipal(Caller caller) { + Principal callerPrincipal = caller.getCallerPrincipal(); + + // Check custom principal + if (callerPrincipal instanceof CallerPrincipal == false) { + return callerPrincipal; + } + + // Check anonymous principal + if (callerPrincipal.getName() == null) { + return SecurityContext.getDefaultCallerPrincipal(); + } + + // Check certificate / X500 principal (this is oddly specific) + if (CertificateRealm.AUTH_TYPE.equals(realmName)) { + return new X500Principal(callerPrincipal.getName()); + } + + return new UserNameAndPassword(callerPrincipal.getName()); + } + + public static void copySubject(Subject target, Subject source) { + target.getPrincipals().addAll(source.getPrincipals()); + target.getPublicCredentials().addAll(source.getPublicCredentials()); + target.getPrivateCredentials().addAll(source.getPrivateCredentials()); + } + + private Caller getCaller(Subject subject) { + Set callers = subject.getPrincipals(Caller.class); + if (callers.isEmpty()) { + return null; + } + + return callers.iterator().next(); + } + + private Subject reuseSessionSubject(final Caller caller) { + Principal returnedPrincipal = findPrincipalWrapper(caller.getCallerPrincipal()); + + if (returnedPrincipal instanceof WebPrincipal) { + return reuseWebPrincipal((WebPrincipal) returnedPrincipal); + } + + return null; + } + + private Subject reuseWebPrincipal(final WebPrincipal webPrincipal) { + + SecurityContext securityContext = webPrincipal.getSecurityContext(); + final Subject securityContextSubject = securityContext != null ? securityContext.getSubject() : null; + final Principal callerPrincipal = securityContext != null ? securityContext.getCallerPrincipal() : null; + final Principal defaultPrincipal = SecurityContext.getDefaultCallerPrincipal(); + + // This method uses 4 (numbered) criteria to determine if the argument WebPrincipal can be reused + + /** + * 1. WebPrincipal must contain a SecurityContext and SC must have a non-null, non-default callerPrincipal and a Subject + */ + if (callerPrincipal == null || callerPrincipal.equals(defaultPrincipal) || securityContextSubject == null) { + return null; + } + + boolean hasObject = false; + Set distinguishedCreds = securityContextSubject.getPublicCredentials(DistinguishedPrincipalCredential.class); + if (distinguishedCreds.size() == 1) { + for (DistinguishedPrincipalCredential cred : distinguishedCreds) { + if (cred.getPrincipal().equals(callerPrincipal)) { + hasObject = true; + } + + } + } + + if (!hasObject) { + Set distinguishedPrincipals = securityContextSubject.getPrincipals(DistinguishedPrincipalCredential.class); + if (distinguishedPrincipals.size() == 1) { + for (DistinguishedPrincipalCredential cred : distinguishedPrincipals) { + if (cred.getPrincipal().equals(callerPrincipal)) { + hasObject = true; + } + } + } + } + + /** + * 2. Subject within SecurityContext must contain a single DistinguishedPrincipalCredential that identifies the Caller Principal + */ + if (!hasObject) { + return null; + } + + hasObject = securityContextSubject.getPrincipals().contains(callerPrincipal); + + /** + * 3. Subject within SecurityContext must contain the caller principal + */ + if (!hasObject) { + return null; + } + + /** + * 4. The webPrincipal must have a non null name that equals the name of the callerPrincipal. + */ + if (webPrincipal.getName() == null || !webPrincipal.getName().equals(callerPrincipal.getName())) { + return null; + } + + return securityContextSubject; + } + + private Principal findPrincipalWrapper(Principal principal) { + if (principal != null && !(principal instanceof WebPrincipal)) { + + // Get the top level session principal + Principal sessionPrincipal = SecurityContext.getCurrent().getSessionPrincipal(); + + // If it's the wrapper we're looking for, it must be of type WebPrincipal + if (sessionPrincipal instanceof WebPrincipal) { + WebPrincipal webPrincipalFromSession = (WebPrincipal) sessionPrincipal; + + // Check if the top level session principal is indeed wrapping our current principal + if (webPrincipalFromSession.getCustomPrincipal() == principal) { + + // Custom principal from wrapper is the same as our current principal, so + // this is the wrapper we're looking for. + return webPrincipalFromSession; + } + } + } + + // Not wrapped, or wrapper could not be found + return principal; } @Override @@ -525,35 +925,25 @@ protected String getName() { public String getRealmName() { return realmName; } - - - /** - * {@inheritDoc} - * - * @param container - must be an instance of {@link Container} - */ - @Override - public void setVirtualServer(Object container) { - jaspicRealm.setVirtualServer((Container) container); - } + @Override public void updateWebSecurityManager() { - /*if (jaccWebAuthorizationManager == null) { - jaccWebAuthorizationManager = getJaccWebAuthorizationManager(true); + if (webAuthorizationManagerService == null) { + webAuthorizationManagerService = this.getWebAuthorizationManager(true); } - if (jaccWebAuthorizationManager != null) { + if (webAuthorizationManagerService != null) { try { - jaccWebAuthorizationManager.release(); - jaccWebAuthorizationManager.destroy(); + webAuthorizationManagerService.release(); + webAuthorizationManagerService.destroy(); } catch (Exception ex) { LOG.log(Level.SEVERE, "Failed to release and destroy the jaccWebAuthorizationManager", ex); } - jaccWebAuthorizationManager = webSecurityManagerFactory.createManager(webDescriptor, true, serverContext); + webAuthorizationManagerService = webSecurityManagerFactory.createManager(webDescriptor, true, serverContext); LOG.fine(() -> "WebAuthorizationManagerService for " + contextId + " has been updated"); - }*/ + } } /** @@ -663,11 +1053,40 @@ public boolean hasResourcePermission(HttpRequest request, HttpResponse response, */ @Override public boolean invokePostAuthenticateDelegate(HttpRequest request, HttpResponse response, Context context) throws IOException { - if (jaspicRealm.isJaspicEnabled()) { - return jaspicRealm.secureResponse(request, response, context); + boolean result = false; + ServerAuthContext serverAuthContext = null; + try { + if (authenticationService != null) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request.getRequest(); + MessageInfo messageInfo = (MessageInfo) httpServletRequest.getAttribute(MESSAGE_INFO); + if (messageInfo != null) { + // Jakarta Authentication is enabled for this application + serverAuthContext = (ServerAuthContext) messageInfo.getMap().get(SERVER_AUTH_CONTEXT); + if (serverAuthContext != null) { + try { + context.fireContainerEvent(BEFORE_POST_AUTHENTICATION, null); + AuthStatus authStatus = serverAuthContext.secureResponse(messageInfo, null); // null serviceSubject + result = AuthStatus.SUCCESS.equals(authStatus); + } finally { + context.fireContainerEvent(AFTER_POST_AUTHENTICATION, null); + } + } + } + } + } catch (AuthException ex) { + throw new IOException(ex); + } finally { + if (authenticationService != null && serverAuthContext != null) { + if (request instanceof HttpRequestWrapper) { + request.removeNote(WRAPPED_REQUEST); + } + if (response instanceof HttpResponseWrapper) { + request.removeNote(WRAPPED_RESPONSE); + } + } } - return false; + return result; } /** @@ -682,12 +1101,12 @@ public boolean invokePostAuthenticateDelegate(HttpRequest request, HttpResponse */ @Override public boolean hasRole(HttpRequest request, HttpResponse response, Principal principal, String role) { - WebSecurityManager authorizationManager = getWebSecurityManager(true); + WebAuthorizationManagerService authorizationManager = getWebSecurityManager(true); if (authorizationManager == null) { return false; } String servletName = getCanonicalName(request); - boolean isGranted = true;//authorizationManager.hasRoleRefPermission(servletName, role, principal); + boolean isGranted = authorizationManager.hasRoleRefPermission(servletName, role, principal); LOG.fine(() -> "Checking if servlet " + servletName + " with principal " + principal + " has role " + role + " isGranted: " + isGranted); return isGranted; @@ -695,15 +1114,42 @@ public boolean hasRole(HttpRequest request, HttpResponse response, Principal pri @Override public void logout(HttpRequest httpRequest) { - ServletContext servletContext = httpRequest.getRequest().getServletContext(); - + boolean securityExtensionEnabled = isSecurityExtensionEnabled(httpRequest.getRequest().getServletContext()); byte[] alreadyCalled = reentrancyStatus.get(); - if (jaspicRealm.isJaspicEnabled(servletContext) && alreadyCalled[0] == 0) { + if (securityExtensionEnabled && authenticationService != null && alreadyCalled[0] == 0) { alreadyCalled[0] = 1; + MessageInfo messageInfo = (MessageInfo) httpRequest.getRequest().getAttribute(MESSAGE_INFO); + if (messageInfo == null) { + messageInfo = new HttpMessageInfo((HttpServletRequest) httpRequest.getRequest(), + (HttpServletResponse) httpRequest.getResponse().getResponse()); + } + + messageInfo.getMap().put(HttpServletConstants.IS_MANDATORY, Boolean.TRUE.toString()); try { - jaspicRealm.cleanSubject(httpRequest); + ServerAuthContext serverAuthContext = authenticationService.getServerAuthContext(messageInfo, null); + if (serverAuthContext != null) { + /* + * Check for the default/server-generated/unauthenticated security context. + */ + SecurityContext securityContext = SecurityContext.getCurrent(); + Subject subject = securityContext.didServerGenerateCredentials() ? new Subject() : securityContext.getSubject(); + + if (subject == null) { + subject = new Subject(); + } + if (subject.isReadOnly()) { + LOG.log(WARNING, "Read-only subject found during logout processing"); + } + + try { + httpRequest.getContext().fireContainerEvent(BEFORE_LOGOUT, null); + serverAuthContext.cleanSubject(messageInfo, subject); + } finally { + httpRequest.getContext().fireContainerEvent(AFTER_LOGOUT, null); + } + } } catch (AuthException ex) { throw new RuntimeException(ex); } finally { @@ -728,7 +1174,9 @@ public void logout() { @Override public void destroy() { super.destroy(); - jaspicRealm.destroy(); + if (authenticationService != null) { + authenticationService.disable(); + } } /** @@ -749,17 +1197,17 @@ public boolean authenticate(WebPrincipal principal) { * This will log a warning if the manager is not found in the factory, and logNull is true. * */ - public WebSecurityManager getWebAuthorizationManager(boolean logNull) { - if (webSecurityManager == null) { + public WebAuthorizationManagerService getWebAuthorizationManager(boolean logNull) { + if (webAuthorizationManagerService == null) { synchronized (this) { - webSecurityManager = webSecurityManagerFactory.getManager(contextId, false); + webAuthorizationManagerService = webSecurityManagerFactory.getManager(contextId, null,false); } - if (webSecurityManager == null && logNull) { + if (webAuthorizationManagerService == null && logNull) { LOG.log(WARNING, "realmAdapter.noWebSecMgr", contextId); } } - return webSecurityManager; + return webAuthorizationManagerService; } /** @@ -785,12 +1233,12 @@ public Principal createFailOveredPrincipal(String username) { } public boolean hasRole(String servletName, Principal principal, String role) { - WebSecurityManager webSecurityManager = getWebAuthorizationManager(true); + WebAuthorizationManagerService webSecurityManager = getWebAuthorizationManager(true); if (webSecurityManager == null) { return false; } - return true; + return webSecurityManager.hasRoleRefPermission(servletName, role, principal); } /** @@ -1029,7 +1477,63 @@ protected Principal getPrincipal(String username) { */ private boolean invokeWebSecurityManager(HttpRequest request, HttpResponse response, SecurityConstraint[] constraints) throws IOException { - // Allow access to form login related pages and targets + if (isRequestFormPage(request)) { + return true; + } + + setServletPath(request); + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + + LOG.log(FINE, () -> "[Web-Security] [ hasResourcePermission ]" + + " Principal: " + httpServletRequest.getUserPrincipal() + + " ContextPath: " + httpServletRequest.getContextPath()); + + //WebSecurityManager webSecurityManager = getWebSecurityManager(true); + //if (webSecurityManager == null) { + // return false; + //} + + return true; + } + + private void setServletPath(HttpRequest request) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + if (httpServletRequest.getServletPath() == null) { + request.setServletPath(getResourceName(httpServletRequest.getRequestURI(), httpServletRequest.getContextPath())); + } + } + + private boolean isRequestFormPage(HttpRequest request) { + initFormPages(); + + if (isAllNull(loginPage, errorPage)) { + return false; + } + + String requestURI = request.getRequestPathMB().toString(); + LOG.log(FINE, "requestURI: {0}, loginPage: {1}, errorPage: {2}", + new Object[] {requestURI, loginPage, errorPage}); + + if (loginPage != null && loginPage.equals(requestURI)) { + LOG.log(FINE, "Allowed access to login page {0}", loginPage); + return true; + } + + if (errorPage != null && errorPage.equals(requestURI)) { + LOG.log(FINE, "Allowed access to error page {0}", errorPage); + return true; + } + + if (requestURI.endsWith(Constants.FORM_ACTION)) { + LOG.log(FINE, "Allowed access to username/password submission ({0})", Constants.FORM_ACTION); + return true; + } + + return false; + } + + private void initFormPages() { + // allow access to form login related pages and targets // and the "j_security_check" action boolean evaluated = false; try { @@ -1043,10 +1547,8 @@ private boolean invokeWebSecurityManager(HttpRequest request, HttpResponse respo try { rwLock.writeLock().lock(); if (!contextEvaluated) { - - // Get Context here as preAuthenticateCheck does not have it + // get Context here as preAuthenticateCheck does not have it // and our Container is always a Context - Context context = (Context) getContainer(); LoginConfig config = context.getLoginConfig(); if (config != null && FORM_METHOD.equals(config.getAuthMethod())) { @@ -1059,36 +1561,6 @@ private boolean invokeWebSecurityManager(HttpRequest request, HttpResponse respo rwLock.writeLock().unlock(); } } - - if (loginPage != null || errorPage != null) { - String requestURI = request.getRequestPathMB().toString(); - LOG.fine(() -> "[Web-Security] requestURI: " + requestURI + " loginPage: " + loginPage); - if (loginPage != null && loginPage.equals(requestURI)) { - LOG.fine(() -> " Allow access to login page " + loginPage); - return true; - } else if (errorPage != null && errorPage.equals(requestURI)) { - LOG.fine(() -> " Allow access to error page " + errorPage); - return true; - } else if (requestURI.endsWith(FORM_ACTION)) { - LOG.fine(" Allow access to username/password submission"); - return true; - } - } - - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - if (httpServletRequest.getServletPath() == null) { - request.setServletPath(getResourceName(httpServletRequest.getRequestURI(), httpServletRequest.getContextPath())); - } - - LOG.fine(() -> "[Web-Security] [ hasResourcePermission ] Principal: " + httpServletRequest.getUserPrincipal() - + " ContextPath: " + httpServletRequest.getContextPath()); - - WebSecurityManager authorizationManager = getWebSecurityManager(true);//getJaccWebAuthorizationManager(true); - if (authorizationManager == null) { - return false; - } - - return true;//authorizationManager.hasResourcePermission(httpServletRequest); } private boolean redirect(HttpRequest request, HttpResponse response) throws IOException { @@ -1351,8 +1823,7 @@ private boolean hasRequestPrincipal(HttpRequest request) { private boolean isJakartaAuthenticationEnabled() throws IOException { try { - //return authenticationService != null && authenticationService.getServerAuthConfig() != null; - return true; + return authenticationService != null && authenticationService.getServerAuthConfig() != null; } catch (Exception ex) { throw new IOException(ex); } @@ -1368,4 +1839,50 @@ public interface IOSupplier { */ T get() throws IOException; } + + // inner class extends AuthenticatorBase such that session registration + // of webtier can be invoked by RealmAdapter after authentication + // by authentication module. + static class AuthenticatorProxy extends AuthenticatorBase { + + private final AuthenticatorBase authBase; + private final Principal principal; + private final String authType; + + @Override + public boolean getCache() { + return authBase.getCache(); + } + + @Override + public Container getContainer() { + return authBase.getContainer(); + } + + AuthenticatorProxy(Authenticator authenticator, Principal p, String authType) throws LifecycleException { + + this.authBase = (AuthenticatorBase) authenticator; + this.principal = p; + this.authType = authType == null ? RealmAdapter.PROXY_AUTH_TYPE : authType; + + setCache(authBase.getCache()); + setContainer(authBase.getContainer()); + start(); // finds sso valve and sets its value in proxy + } + + @Override + public boolean authenticate(HttpRequest request, HttpResponse response, LoginConfig config) throws IOException { + if (cache) { + getSession(request, true); + } + + register(request, response, this.principal, this.authType, this.principal.getName(), null); + return true; + } + + @Override + public String getAuthMethod() { + return authType; + } + } } diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java deleted file mode 100644 index df85a30a6d6..00000000000 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/realmadapter/JaspicRealm.java +++ /dev/null @@ -1,624 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDLGPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] -package com.sun.web.security.realmadapter; - -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.AUTH_TYPE; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.IS_MANDATORY; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.REGISTER_SESSION; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.REGISTER_WITH_AUTHENTICATOR; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.WEB_BUNDLE; -import static com.sun.logging.LogDomains.WEB_LOGGER; -import static java.lang.Boolean.TRUE; -import static java.util.logging.Level.INFO; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; -import static jakarta.security.auth.message.AuthStatus.SUCCESS; -import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; -import static org.apache.catalina.ContainerEvent.AFTER_AUTHENTICATION; -import static org.apache.catalina.ContainerEvent.AFTER_LOGOUT; -import static org.apache.catalina.ContainerEvent.AFTER_POST_AUTHENTICATION; -import static org.apache.catalina.ContainerEvent.BEFORE_AUTHENTICATION; -import static org.apache.catalina.ContainerEvent.BEFORE_LOGOUT; -import static org.apache.catalina.ContainerEvent.BEFORE_POST_AUTHENTICATION; -import static org.apache.catalina.Globals.WRAPPED_REQUEST; -import static org.apache.catalina.Globals.WRAPPED_RESPONSE; - -import java.io.IOException; -import java.security.Principal; -import java.util.AbstractMap.SimpleImmutableEntry; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Function; -import java.util.logging.Logger; - -import javax.security.auth.Subject; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.servlet.ServletContext; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -import org.apache.catalina.Authenticator; -import org.apache.catalina.Container; -import org.apache.catalina.Context; -import org.apache.catalina.HttpRequest; -import org.apache.catalina.HttpResponse; -import org.apache.catalina.LifecycleException; -import org.apache.catalina.connector.RequestFacade; -import org.apache.catalina.deploy.LoginConfig; - -import com.sun.enterprise.deployment.WebBundleDescriptor; -import com.sun.enterprise.security.SecurityContext; -import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServletServices; -import com.sun.enterprise.security.web.integration.WebPrincipal; -import com.sun.logging.LogDomains; -import com.sun.web.security.HttpRequestWrapper; -import com.sun.web.security.HttpResponseWrapper; -import com.sun.web.security.RealmAdapter; -import com.sun.web.security.RealmAdapter.IOSupplier; - -import fish.payara.notification.requesttracing.RequestTraceSpan; -import fish.payara.nucleus.requesttracing.RequestTracingService; -import org.glassfish.epicyro.config.servlet.HttpMessageInfo; - -public class JaspicRealm { - - private static final Logger logger = LogDomains.getLogger(RealmAdapter.class, WEB_LOGGER); - - /** - * name of system property that can be used to define corresponding default provider for system apps. - */ - private static final String SYSTEM_HTTPSERVLET_SECURITY_PROVIDER = "system_httpservlet_security_provider"; - private static final String SERVER_AUTH_CONTEXT = "__jakarta.security.auth.message.ServerAuthContext"; - private static final String MESSAGE_INFO = "__jakarta.security.auth.message.MessageInfo"; - - /** - * The default JASPIC config provider for system apps if one has been set via a system property. - * This JASPIC config provider is used to obtain references to the SAM (authentication mechanism). - */ - private static String jaspicSystemConfigProviderID = getDefaultSystemProviderID(); - - - private String realmName; - private boolean isSystemApp; - private WebBundleDescriptor webDescriptor; - private RequestTracingService requestTracing; - - private Container virtualServer; - - private PayaraEpicyroServletServices jaspicServices; - private AtomicBoolean initialised = new AtomicBoolean(); - - public JaspicRealm(String realmName, boolean isSystemApp, WebBundleDescriptor webDescriptor, RequestTracingService requestTracing) { - this.realmName = realmName; - this.isSystemApp = isSystemApp; - this.webDescriptor = webDescriptor; - this.requestTracing = requestTracing; - } - - public void setVirtualServer(Container virtualServer) { - this.virtualServer = virtualServer; - } - - // TODO: reexamine this after TP2 - public synchronized void initJaspicServices(ServletContext servletContext) { - if (jaspicServices != null) { - return; - } - - jaspicServices = getConfigHelper(servletContext); - initialised.set(true); - } - - public boolean isInitialised() { - return initialised.get(); - } - - public boolean isJaspicEnabled(ServletContext servletContext) { - if (jaspicServices == null) { - initJaspicServices(servletContext); - } - - return isJaspicEnabled(); - } - - public boolean isJaspicEnabled() { - return getServerAuthConfig() != null; - } - - public boolean validateRequest(HttpRequest request, HttpResponse response, Context context, Authenticator authenticator, boolean calledFromAuthenticate, Function isMandatoryFn) throws IOException { - try { - context.fireContainerEvent(BEFORE_AUTHENTICATION, null); - - // Get the WebPrincipal principal and add to the security context principals - RequestFacade requestFacade = (RequestFacade) request.getRequest(); - setAdditionalPrincipalInContext(requestFacade); - - return validateRequest(getServerAuthConfig(), context, requestFacade, request, response, context.getLoginConfig(), authenticator, calledFromAuthenticate, isMandatoryFn); - } finally { - resetAdditionalPrincipalInContext(); - context.fireContainerEvent(AFTER_AUTHENTICATION, null); - } - } - - public boolean secureResponse(HttpRequest request, HttpResponse response, Context context) throws IOException { - Entry messageInfoEntry = null; - - try { - messageInfoEntry = getMessageInfoFromRequest((HttpServletRequest) request.getRequest()); - if (messageInfoEntry != null) { - try { - context.fireContainerEvent(BEFORE_POST_AUTHENTICATION, null); - - ServerAuthContext serverAuthContext = messageInfoEntry.getValue(); - MessageInfo messageInfo = messageInfoEntry.getKey(); - - return SUCCESS.equals(serverAuthContext.secureResponse(messageInfo, null)); - } finally { - context.fireContainerEvent(AFTER_POST_AUTHENTICATION, null); - } - } - } catch (AuthException ex) { - throw new IOException(ex); - } finally { - if (messageInfoEntry != null) { - if (request instanceof HttpRequestWrapper) { - request.removeNote(WRAPPED_REQUEST); - } - if (response instanceof HttpResponseWrapper) { - request.removeNote(WRAPPED_RESPONSE); - } - } - } - - return false; - } - - public void cleanSubject(HttpRequest httpRequest) throws AuthException { - MessageInfo messageInfo = (MessageInfo) httpRequest.getRequest().getAttribute(MESSAGE_INFO); - - if (messageInfo == null) { - messageInfo = new HttpMessageInfo( - (HttpServletRequest) httpRequest.getRequest(), - (HttpServletResponse) httpRequest.getResponse().getResponse()); - } - - messageInfo.getMap().put(IS_MANDATORY, TRUE.toString()); - - ServerAuthContext serverAuthContext = jaspicServices.getServerAuthContext(messageInfo, null); - if (serverAuthContext != null) { - - // Check for the default/server-generated/unauthenticated security context. - - SecurityContext securityContext = SecurityContext.getCurrent(); - Subject subject = securityContext.didServerGenerateCredentials() ? new Subject() : securityContext.getSubject(); - - if (subject == null) { - subject = new Subject(); - } - - if (subject.isReadOnly()) { - logger.log(WARNING, "Read-only subject found during logout processing"); - } - - try { - httpRequest.getContext().fireContainerEvent(BEFORE_LOGOUT, null); - - serverAuthContext.cleanSubject(messageInfo, subject); - } finally { - httpRequest.getContext().fireContainerEvent(AFTER_LOGOUT, null); - } - } - } - - public void destroy() { - if (jaspicServices != null) { - jaspicServices.disable(); - } - } - - - - // ############################ Private methods ###################################### - - - private ServerAuthConfig getServerAuthConfig() { - if (jaspicServices == null) { - return null; - } - - try { - return jaspicServices.getServerAuthConfig(); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - private ServerAuthContext getServerAuthContext(MessageInfo messageInfo) throws AuthException { - ServerAuthContext authContext = jaspicServices.getServerAuthContext(messageInfo, null); // null serviceSubject - - if (authContext == null) { - throw new AuthException("null ServerAuthContext"); - } - - return authContext; - } - - /** - * This must be invoked after virtualServer is set. - */ - private PayaraEpicyroServletServices getConfigHelper(ServletContext servletContext) { - Map map = new HashMap<>(); - map.put(WEB_BUNDLE, webDescriptor); - - return new PayaraEpicyroServletServices( - getAppContextID(servletContext), map, null, // null handler - realmName, isSystemApp, jaspicSystemConfigProviderID); - } - - /** - * This must be invoked after virtualServer is set. - */ - private String getAppContextID(ServletContext servletContext) { - if (!servletContext.getVirtualServerName().equals(virtualServer.getName())) { - // PAYARA-1261 downgrade log messages to INFO as users haven't got a problem - logger.log(INFO, "Virtual server name from ServletContext: {0} differs from name from virtual.getName(): {1}", - new Object[] { servletContext.getVirtualServerName(), virtualServer.getName() }); - } - - if (!servletContext.getContextPath().equals(webDescriptor.getContextRoot())) { - // PAYARA-1261 downgrade log messages to INFO as users haven't got a problem - logger.log(INFO, "Context path from ServletContext: {0} differs from path from bundle: {1}", - new Object[] { servletContext.getContextPath(), webDescriptor.getContextRoot() }); - } - - return servletContext.getVirtualServerName() + " " + servletContext.getContextPath(); - } - - /** - * get the default provider id for system apps if one has been established. the default provider for system apps is - * established by defining a system property. - * - * @return the provider id or null. - */ - private static String getDefaultSystemProviderID() { - String p = System.getProperty(SYSTEM_HTTPSERVLET_SECURITY_PROVIDER); - if (p != null) { - p = p.trim(); - if (p.length() == 0) { - p = null; - } - } - return p; - } - - private void setAdditionalPrincipalInContext(RequestFacade requestFacade) { - if (requestFacade != null) { - Principal wrapped = requestFacade.getPrincipal(); - if (wrapped != null) { - SecurityContext.getCurrent().setAdditionalPrincipal(wrapped); - } - } - } - - private void resetAdditionalPrincipalInContext() { - SecurityContext.getCurrent().setAdditionalPrincipal(null); - } - - private boolean validateRequest(ServerAuthConfig serverAuthConfig, Context context, RequestFacade requestFacade, HttpRequest request, HttpResponse response, LoginConfig loginConfig, Authenticator authenticator, boolean calledFromAuthenticate, Function isMandatoryFn) throws IOException { - if (isRequestTracingEnabled()) { - return doTraced(serverAuthConfig, context, requestFacade, - () -> validateRequest(request, response, loginConfig, authenticator, calledFromAuthenticate, isMandatoryFn)); - } - - return validateRequest(request, response, loginConfig, authenticator, calledFromAuthenticate, isMandatoryFn); - } - - private boolean validateRequest(HttpRequest request, HttpResponse response, LoginConfig config, Authenticator authenticator, boolean calledFromAuthenticate, Function isMandatoryFn) throws IOException { - - HttpServletRequest servletRequest = (HttpServletRequest) request.getRequest(); - HttpServletResponse servletResponse = (HttpServletResponse) response.getResponse(); - - Subject subject = new Subject(); - MessageInfo messageInfo = new HttpMessageInfo(servletRequest, servletResponse); - - boolean isValidateSuccess = false; - boolean isMandatory = true; - ServerAuthContext authContext = null; - - - try { - isMandatory = isMandatoryFn.apply(servletRequest); - - // Produce caller challenge if call originates from HttpServletRequest#authenticate - if (isMandatory || calledFromAuthenticate) { - setMandatory(messageInfo); - } - - // Obtain the JASIC ServerAuthContext, which represents the authentication mechanism that interacts with the caller - authContext = getServerAuthContext(messageInfo); - - // Call the JASPIC ServerAuthContext which should eventually call the ServerAuthModule (SAM) - - // Notice a null is passed in as the service subject - // Additionally notice we only care about SUCCESS being returned or not and ignore - // all other JASPIC AuthStatus values. - - isValidateSuccess = SUCCESS.equals(authContext.validateRequest(messageInfo, subject, null)); - - if (!isValidateSuccess) { - return false; - } - - } catch (AuthException | RuntimeException e) { - logger.log(WARNING, "JASPIC: http msg authentication fail", e); - servletResponse.setStatus(SC_INTERNAL_SERVER_ERROR); - } - - // When a SAM has returned SUCCESS, it can mean 3 different things: - - // 1. The SAM authenticated the caller and a new Principal has been set - // 2. The SAM "did nothing" and a NULL has been set - // 3. The SAM wants to use the session and the sets the (non null) Principal it obtained from the passed-in request - - // Store the messageInfo and ServerAuthContext so that the exact same ones can be used again when the SAM - // needs to be called again later in this request (for example, when secureResponse is called). - storeMessageInfoInRequest(servletRequest, messageInfo, authContext); - - // There must be at least one new principal to count as SAM having authenticated - if (hasNewPrincipal(subject.getPrincipals())) { - - // Handle case 1: The SAM authenticated the caller and a new Principal has been set - - handleSamAuthenticated(subject, messageInfo, request, response, config, authenticator); - } else { - - // Handle case 2: The SAM "did nothing" and a NULL has been set. - - isValidateSuccess = handleSamNotAuthenticated(messageInfo, isMandatory, isValidateSuccess, request, response); - } - - if (isValidateSuccess) { - // Check if the SAM instructed us to wrap the request and response, and if so do the wrapping - checkRequestResponseWrappingNeeded(messageInfo, request, response, servletRequest, servletResponse); - } - - return isValidateSuccess; - } - - private void handleSamAuthenticated(Subject subject, MessageInfo messageInfo, HttpRequest request, HttpResponse response, LoginConfig config, Authenticator authenticator) throws IOException { - SecurityContext securityContext = new SecurityContext(subject); - - // Assuming no null principal here - WebPrincipal webPrincipal = new WebPrincipal(securityContext.getCallerPrincipal(), securityContext); - - // TODO: check Java SE SecurityManager access - SecurityContext.setCurrent(securityContext); - - try { - String authType = getAuthType(messageInfo, config); - - if (shouldRegisterSession(messageInfo)) { - - // Besides authenticating, the SAM has indicated that the new principal should - // be stored in a session. This means that when the SAM is called again in a next request - // it can opt to continue this session. - - new AuthenticatorProxy(authenticator, webPrincipal, authType) - .authenticate(request, response, config); - } else { - request.setAuthType(authType == null ? AuthenticatorProxy.PROXY_AUTH_TYPE : authType); - // it is not completely sure the necessity of webPrincipal wrapping the custom principal while - // HttpServletRequest.getUserPrincipal() return the custom principal instead of webPrincipal - // therefore it is necessary to check and use custom principal if available - request.setUserPrincipal(webPrincipal.getCustomPrincipal() == null ? - webPrincipal : webPrincipal.getCustomPrincipal()); - } - } catch (LifecycleException le) { - logger.log(SEVERE, "[Web-Security] unable to register session", le); - } - } - - private boolean handleSamNotAuthenticated(MessageInfo messageInfo, boolean isMandatory, boolean isValidateSuccess, HttpRequest request, HttpResponse response) { - - if (hasRequestPrincipal(messageInfo)) { - - // If there's a request principal, then it means a session exists with an existing principal. - // But the SAM has specifically chosen not to join that session (use the session's principal) - // for this request as there was no new principal present in the subject. - - // So, set request principal to null for this request (GLASSFISH-20930) - request.setUserPrincipal(null); - request.setAuthType(null); - } - - // If authentication is mandatory, we must have a non-anonymous principal - if (isMandatory) { - return false; - } - - return isValidateSuccess; - } - - private boolean doTraced(ServerAuthConfig serverAuthConfig, Context context, RequestFacade requestFacade, IOSupplier supplier) throws IOException { - RequestTraceSpan span = null; - boolean result; - - try { - span = new RequestTraceSpan("authenticateJaspic"); - span.addSpanTag("AppContext", serverAuthConfig.getAppContext()); - span.addSpanTag("Context", context.getPath()); - - result = supplier.get(); - - span.addSpanTag("AuthResult", Boolean.toString(result)); - - Principal principal = requestFacade.getPrincipal(); - String principalName = "null"; - if (principal != null) { - principalName = principal.getName(); - } - span.addSpanTag("Principal", principalName); - } finally { - if (span != null) { - requestTracing.traceSpan(span); - } - } - - return result; - } - - private void checkRequestResponseWrappingNeeded(MessageInfo messageInfo, HttpRequest request, HttpResponse response, HttpServletRequest servletRequest, HttpServletResponse servletResponse) { - HttpServletRequest wrappedServletRequest = (HttpServletRequest) messageInfo.getRequestMessage(); - if (wrappedServletRequest != servletRequest) { - request.setNote(WRAPPED_REQUEST, new HttpRequestWrapper(request, wrappedServletRequest)); - } - - HttpServletResponse wrappedServletResponse = (HttpServletResponse) messageInfo.getResponseMessage(); - if (wrappedServletResponse != servletResponse) { - request.setNote(WRAPPED_RESPONSE, new HttpResponseWrapper(response, wrappedServletResponse)); - } - } - - private boolean isRequestTracingEnabled() { - return requestTracing != null && requestTracing.isRequestTracingEnabled(); - } - - private boolean hasRequestPrincipal(MessageInfo messageInfo) { - return ((HttpServletRequest) messageInfo.getRequestMessage()).getUserPrincipal() != null; - } - - private boolean hasNewPrincipal(Set principalSet) { - return principalSet != null && !principalSet.isEmpty() && !principalSetContainsOnlyAnonymousPrincipal(principalSet); - } - - /** - * Used to detect when the principals in the subject correspond to the default or "ANONYMOUS" principal, and therefore a - * null principal should be set in the HttpServletRequest. - * - * @param principalSet - * @return true whe a null principal is to be set. - */ - private boolean principalSetContainsOnlyAnonymousPrincipal(Set principalSet) { - boolean containsOnlyAnonymousPrincipal = false; - - Principal defaultPrincipal = SecurityContext.getDefaultCallerPrincipal(); - if (defaultPrincipal != null && principalSet != null) { - containsOnlyAnonymousPrincipal = principalSet.contains(defaultPrincipal); - } - - if (containsOnlyAnonymousPrincipal) { - Iterator it = principalSet.iterator(); - while (it.hasNext()) { - if (!it.next().equals(defaultPrincipal)) { - return false; - } - } - } - - return containsOnlyAnonymousPrincipal; - } - - @SuppressWarnings("unchecked") - private void setMandatory(MessageInfo messageInfo) { - messageInfo.getMap().put(IS_MANDATORY, TRUE.toString()); - } - - private String getAuthType(MessageInfo messageInfo, LoginConfig config) { - String authType = getAuthType(messageInfo); - - if (authType == null && config != null && config.getAuthMethod() != null) { - authType = config.getAuthMethod(); - } - - return authType; - } - - private String getAuthType(MessageInfo messageInfo) { - return (String) messageInfo.getMap().get(AUTH_TYPE); - } - - private boolean shouldRegisterSession(MessageInfo messageInfo) { - @SuppressWarnings("rawtypes") - Map map = messageInfo.getMap(); - - // Detect both the proprietary property and the standard one. - - return map.containsKey(REGISTER_WITH_AUTHENTICATOR) || mapEntryToBoolean(REGISTER_SESSION, map); - } - - @SuppressWarnings("unchecked") - private void storeMessageInfoInRequest(HttpServletRequest servletRequest, MessageInfo messageInfo, ServerAuthContext authContext) { - messageInfo.getMap().put(SERVER_AUTH_CONTEXT, authContext); - servletRequest.setAttribute(MESSAGE_INFO, messageInfo); - } - - private Entry getMessageInfoFromRequest(HttpServletRequest servletRequest) { - if (jaspicServices != null) { - MessageInfo messageInfo = (MessageInfo) servletRequest.getAttribute(MESSAGE_INFO); - if (messageInfo != null) { - - // JSR 196 is enabled for this application - return new SimpleImmutableEntry<>(messageInfo, (ServerAuthContext) messageInfo.getMap().get(SERVER_AUTH_CONTEXT)); - } - } - - return null; - } - - private boolean mapEntryToBoolean(String propName, Map map) { - if (map.containsKey(propName)) { - Object value = map.get(propName); - if (value != null && value instanceof String) { - return Boolean.valueOf((String) value); - } - } - - return false; - } - -} diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java index e7aff2dfe4c..4684e6b1e04 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/WebServicesDelegateImpl.java @@ -103,33 +103,32 @@ public String getDefaultWebServicesProvider() { @Override public String getAuthContextID(MessageInfo messageInfo) { + if (!(messageInfo instanceof PacketMessageInfo)) { + return getOpName((SOAPMessage) messageInfo.getRequestMessage()); + } - // make this more efficient by operating on packet - String rvalue = null; - if (messageInfo instanceof PacketMessageInfo) { - PacketMessageInfo pmi = (PacketMessageInfo) messageInfo; - Packet p = pmi.getRequestPacket(); - if (p != null) { - Message m = p.getMessage(); - if (m != null) { - WSDLPort port = (WSDLPort) messageInfo.getMap().get("WSDL_MODEL"); - if (port != null) { - WSDLBoundOperation w = m.getOperation(port); - if (w != null) { - QName n = w.getName(); - if (n != null) { - rvalue = n.getLocalPart(); - } + // Make this more efficient by operating on packet + String authContextID = null; + PacketMessageInfo pmi = (PacketMessageInfo) messageInfo; + + Packet requestPacket = pmi.getRequestPacket(); + if (requestPacket != null) { + Message message = requestPacket.getMessage(); + if (message != null) { + WSDLPort port = (WSDLPort) messageInfo.getMap().get("WSDL_MODEL"); + if (port != null) { + WSDLBoundOperation boundOperation = message.getOperation(port); + if (boundOperation != null) { + QName name = boundOperation.getName(); + if (name != null) { + authContextID = name.getLocalPart(); } } } } - return rvalue; - } else { - // make this more efficient by operating on packet - return getOpName((SOAPMessage) messageInfo.getRequestMessage()); } + return authContextID; } private String getOpName(SOAPMessage message) { @@ -137,33 +136,33 @@ private String getOpName(SOAPMessage message) { return null; } - String rvalue = null; + String opName = null; - // first look for a SOAPAction header. + // First look for a SOAPAction header. // this is what .net uses to identify the operation MimeHeaders headers = message.getMimeHeaders(); if (headers != null) { String[] actions = headers.getHeader("SOAPAction"); if (actions != null && actions.length > 0) { - rvalue = actions[0]; - if (rvalue != null && rvalue.equals("\"\"")) { - rvalue = null; + opName = actions[0]; + if (opName != null && opName.equals("\"\"")) { + opName = null; } } } - // if that doesn't work then we default to trying the name + // If that doesn't work then we default to trying the name // of the first child element of the SOAP envelope. - if (rvalue == null) { + if (opName == null) { Name name = getName(message); if (name != null) { - rvalue = name.getLocalName(); + opName = name.getLocalName(); } } - return rvalue; + return opName; } private Name getName(SOAPMessage message) { diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/RequestFacade.java b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/RequestFacade.java index c340e9cc1d5..24b71fcbc4e 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/connector/RequestFacade.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/connector/RequestFacade.java @@ -99,6 +99,11 @@ public class RequestFacade implements HttpServletRequest { private static final ResourceBundle rb = LogFacade.getLogger().getResourceBundle(); + /** + * The wrapped request. + */ + protected Request catalinaConnectorRequest; + // ----------------------------------------------------------- DoPrivileged private final class GetAttributePrivilegedAction implements PrivilegedAction> { @@ -253,6 +258,7 @@ public RequestFacade(Request request) { * default-web-module will be masked, false otherwise */ public RequestFacade(Request request, boolean maskDefaultContextMapping) { + this.catalinaConnectorRequest = request; this.request = request; this.maskDefaultContextMapping = maskDefaultContextMapping; this.reqFacHelper = new RequestFacadeHelper(request); @@ -294,6 +300,7 @@ protected Object clone() throws CloneNotSupportedException { * Clear facade. */ public void clear() { + catalinaConnectorRequest = null; request = null; if (reqFacHelper != null) { reqFacHelper.clear(); @@ -833,6 +840,19 @@ public java.security.Principal getUserPrincipal() { return p; } + // returns the original, unwrapped principal from the underlying request + public Principal getRequestPrincipal() { + checkRequestNull(); + + return catalinaConnectorRequest.getUserPrincipal(); + } + + private void checkRequestNull() { + if (catalinaConnectorRequest == null) { + throw new IllegalStateException(rb.getString(LogFacade.CANNOT_USE_REQUEST_OBJECT_OUTSIDE_SCOPE_EXCEPTION)); + } + } + @Override public String getRequestedSessionId() { diff --git a/nucleus/common/common-util/src/main/java/com/sun/enterprise/util/Utility.java b/nucleus/common/common-util/src/main/java/com/sun/enterprise/util/Utility.java index 74900981348..6e9a938e253 100644 --- a/nucleus/common/common-util/src/main/java/com/sun/enterprise/util/Utility.java +++ b/nucleus/common/common-util/src/main/java/com/sun/enterprise/util/Utility.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.util; @@ -578,4 +578,24 @@ private static void clear(CharBuffer charBuffer) { chars[i] = '0'; } } + + /** + * Returns true if the given string is null or is empty. + * + * @param string The string to be checked on emptiness. + * @return True if the given string is null or is empty. + */ + public static boolean isEmpty(String string) { + return string == null || string.isEmpty(); + } + + public static boolean isAllNull(Object... values) { + for (Object value : values) { + if (value != null) { + return false; + } + } + + return true; + } } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java index 74653006bfb..a49d4faf25e 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java @@ -101,8 +101,8 @@ public class SecurityContext extends AbstractSecurityContext { // Did the client log in as or did the server generate the context private boolean serverGeneratedCredentials; - - + + private Principal sessionPrincipal; // ### Static public methods @@ -328,6 +328,14 @@ public Subject getSubject() { return subject; } + public Principal getSessionPrincipal() { + return sessionPrincipal; + } + + public void setSessionPrincipal(Principal sessionPrincipal) { + this.sessionPrincipal = sessionPrincipal; + } + public Set getPrincipalSet() { return subject.getPrincipals(); } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/LoginContextDriver.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/LoginContextDriver.java index e76db444e9d..718279eca13 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/LoginContextDriver.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/LoginContextDriver.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.auth.login; @@ -49,10 +49,13 @@ import static com.sun.enterprise.security.common.SecurityConstants.CLIENT_JAAS_CERTIFICATE; import static com.sun.enterprise.security.common.SecurityConstants.CLIENT_JAAS_PASSWORD; import static com.sun.enterprise.security.common.SecurityConstants.USERNAME_PASSWORD; -import static java.util.logging.Level.FINEST; -import static java.util.logging.Level.INFO; -import static java.util.logging.Level.SEVERE; +import static com.sun.enterprise.util.Utility.isEmpty; +import static java.util.logging.Level.*; +import com.sun.enterprise.security.SecurityContext; +import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; +import java.security.Principal; +import java.util.Enumeration; import java.util.Iterator; import java.util.function.Function; import java.util.logging.Logger; @@ -61,6 +64,7 @@ import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginContext; +import javax.security.auth.x500.X500Principal; import org.glassfish.internal.api.Globals; import com.sun.enterprise.security.SecurityLoggerInfo; @@ -73,6 +77,7 @@ import com.sun.enterprise.security.auth.realm.NoSuchRealmException; import com.sun.enterprise.security.auth.realm.Realm; import com.sun.enterprise.security.common.ClientSecurityContext; +import org.glassfish.security.common.Group; /** * @@ -345,4 +350,143 @@ public static void auditAuthenticate(String username, String realm, boolean succ } } + public static void jmacLogin(Subject subject, Principal callerPrincipal, String realmName) throws LoginException { + if (CertificateRealm.AUTH_TYPE.equals(realmName)) { + if (callerPrincipal instanceof X500Principal) { + LoginContextDriver.jmacLogin(subject, (X500Principal) callerPrincipal); + } + } else if (!callerPrincipal.equals(SecurityContext.getDefaultCallerPrincipal())) { + LoginContextDriver.jmacLogin(subject, callerPrincipal.getName(), realmName); + } + } + + public static Subject jmacLogin(Subject subject, X500Principal x500Principal) throws LoginException { + if (subject == null) { + subject = new Subject(); + } + + String userName = ""; + try { + userName = x500Principal.getName(); + subject.getPublicCredentials().add(x500Principal); + + CertificateRealm certRealm = (CertificateRealm) Realm.getInstance(CertificateRealm.AUTH_TYPE); + String jaasCtx = certRealm.getJAASContext(); + if (jaasCtx != null) { + // The subject has the Certificate Credential. + new LoginContext(jaasCtx, subject, dummyCallback).login(); + } + certRealm.authenticate(subject, x500Principal); + } catch (Exception ex) { + LOGGER.log(INFO, auditAtnRefusedError, userName); + if (getAuditManager().isAuditOn()) { + getAuditManager().authentication(userName, CertificateRealm.AUTH_TYPE, false); + } + + if (ex instanceof LoginException) { + throw (LoginException) ex; + } + throw new LoginException("Authentication failed.", ex); + } + + LOGGER.log(FINE, "JMAC cert login succeeded for {0}", userName); + + if (getAuditManager().isAuditOn()) { + getAuditManager().authentication(userName, CertificateRealm.AUTH_TYPE, true); + } + // do not set the security Context + + return subject; + } + + public static Subject jmacLogin(Subject subject, String userName, String realm) throws LoginException { + if (subject == null) { + subject = new Subject(); + } + + try { + if (isEmpty(realm)) { + realm = Realm.getDefaultRealm(); + } + + Enumeration groups = Realm.getInstance(realm).getGroupNames(userName); + if (groups != null) { + while (groups.hasMoreElements()) { + subject.getPrincipals().add(new Group(groups.nextElement())); + } + } + } catch (Exception ex) { + LOGGER.log(FINE, "Exception when trying to populate groups for CallerPrincipal " + userName, ex); + } + + return subject; + } + + /** + * Performs login for JMAC security. The difference between this method and others is that it just verifies whether the login + * will succeed in the given realm. It does not set the result of the authentication in the appserver runtime environment A + * silent return from this method means that the given user succeeding in authenticating with the given password in the given + * realm + * + * @param subject + * @param username + * @param password + * @param realmName the realm to authenticate under + * @returns Subject on successful authentication + * @throws LoginException + */ + public static Subject jmacLogin(Subject subject, String username, char[] password, String realmName) throws LoginException { + if (realmName == null || !Realm.isValidRealm(realmName)) { + realmName = Realm.getDefaultRealm(); + } + + if (subject == null) { + subject = new Subject(); + } + + final PasswordCredential passwordCredential = new PasswordCredential(username, password, realmName); + subject.getPrivateCredentials().add(passwordCredential); + + String jaasCtx = getJaasCtx(realmName); + + LOGGER.log(FINE, "JMAC login user {0} into realm {1} using JAAS module {2}", + new Object[] {username, realmName, jaasCtx}); + + try { + // A dummyCallback is used to satisfy JAAS but it is never used. + // name/pwd info is already contained in Subject's Credential + new LoginContext(jaasCtx, subject, dummyCallback).login(); + + } catch (Exception e) { + LOGGER.log(INFO, SecurityLoggerInfo.auditAtnRefusedError, username); + if (getAuditManager().isAuditOn()) { + getAuditManager().authentication(username, realmName, false); + } + + if (e instanceof LoginException) { + throw (LoginException) e; + } + throw new LoginException("Login failed: " + e.getMessage(), e); + } + if (getAuditManager().isAuditOn()) { + getAuditManager().authentication(username, realmName, true); + } + LOGGER.log(FINE, "jmac Password login succeeded for {0}", username); + + return subject; + // do not set the security Context + } + + private static String getJaasCtx(String realm) { + try { + return Realm.getInstance(realm).getJAASContext(); + } catch (Exception ex) { + if (ex instanceof LoginException) { + throw (LoginException) ex; + } + + throw (LoginException) new LoginException(ex.toString()).initCause(ex); + } + } + } From 97caef7a19c9140bf054b552a4e38ef8e1cde497 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Tue, 26 Nov 2024 23:15:23 -0600 Subject: [PATCH 19/34] FISH-8925: trying to set starting policy factory for exousia --- .../acc/AppClientContainerSecurityHelper.java | 27 +- .../main/java/com/sun/ejb/InvocationInfo.java | 4 +- .../com/sun/ejb/containers/BaseContainer.java | 10 +- .../containers/EJBHomeInvocationHandler.java | 4 +- .../EJBLocalHomeInvocationHandler.java | 4 +- .../application/EJBSecurityManager.java | 505 ++----- .../glassfish/ejb/startup/EjbDeployer.java | 2 +- .../entitybean/container/EntityContainer.java | 2 +- .../container/ReadOnlyBeanContainer.java | 5 +- .../appclient/AppClientSecurityInfoImpl.java | 79 +- .../integration/AppClientSecurityInfo.java | 3 +- appserver/security/core-ee/osgi.bundle | 4 +- .../security/ee/J2EESecurityManager.java | 140 -- .../security/ee/JavaEESecurityLifecycle.java | 24 +- .../security/ee/SecurityDeployer.java | 164 ++- .../enterprise/security/ee/SecurityUtil.java | 5 +- .../AuthorizationUtil.java | 63 +- .../EJBPolicyContextDelegate.java | 2 - .../GlassFishToExousiaConverter.java | 4 +- .../authorization}/PolicyContextDelegate.java | 4 +- .../ee/authorization/PolicyLoader.java | 244 ++++ .../WebAuthorizationManagerService.java | 573 ++------ .../cache/CachedPermission.java | 4 +- .../cache/CachedPermissionImpl.java | 4 +- .../authorization}/cache/PermissionCache.java | 24 +- .../cache/PermissionCacheFactory.java | 22 +- .../authorization}/cache/package-info.java | 4 +- .../web/integration/WebSecurityManager.java | 14 +- .../WebSecurityManagerFactory.java | 27 +- .../jacc/JaccEJBConstraintsTranslator.java | 342 ----- .../jacc/JaccWebConstraintsTranslator.java | 1251 ----------------- .../context/PolicyContextHandlerData.java | 130 -- .../context/PolicyContextHandlerImpl.java | 132 -- .../context/PolicyContextRegistration.java | 85 -- .../security/jacc/context/package-info.java | 52 - .../security/jacc/package-info.java | 65 - .../com/sun/web/security/RealmAdapter.java | 40 +- .../webservices/SecurityServiceImpl.java | 2 - .../com/sun/enterprise/web/WebContainer.java | 5 - .../sun/enterprise/security/PolicyLoader.java | 340 ----- .../security/SecurityLifecycle.java | 5 - .../enterprise/security/SecurityManager.java | 12 +- .../security/SecurityUpgradeService.java | 8 +- 43 files changed, 698 insertions(+), 3742 deletions(-) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/J2EESecurityManager.java rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/{web/integration => authorization}/AuthorizationUtil.java (72%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{web/integration => ee/authorization}/GlassFishToExousiaConverter.java (97%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jacc/context => ee/authorization}/PolicyContextDelegate.java (95%) create mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/PolicyLoader.java rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jacc => ee/authorization}/cache/CachedPermission.java (95%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jacc => ee/authorization}/cache/CachedPermissionImpl.java (96%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jacc => ee/authorization}/cache/PermissionCache.java (93%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jacc => ee/authorization}/cache/PermissionCacheFactory.java (91%) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jacc => ee/authorization}/cache/package-info.java (94%) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccEJBConstraintsTranslator.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebConstraintsTranslator.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextHandlerData.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextHandlerImpl.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextRegistration.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/package-info.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java delete mode 100644 nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainerSecurityHelper.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainerSecurityHelper.java index 8c04bc483ce..36643b2fa7d 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainerSecurityHelper.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainerSecurityHelper.java @@ -38,12 +38,15 @@ * holder. */ +// Portions Copyright [2024] [Payara Foundation and/or its affiliates] + package org.glassfish.appclient.client.acc; import com.sun.enterprise.container.common.spi.util.InjectionException; import com.sun.enterprise.container.common.spi.util.InjectionManager; import com.sun.enterprise.deployment.ApplicationClientDescriptor; import com.sun.enterprise.security.appclient.integration.AppClientSecurityInfo; +import jakarta.inject.Inject; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationHandler; @@ -53,17 +56,13 @@ import java.util.Arrays; import java.util.List; import java.util.Properties; -import java.util.logging.Level; import java.util.logging.Logger; -import jakarta.inject.Inject; import javax.security.auth.callback.CallbackHandler; import org.glassfish.appclient.client.acc.config.ClientCredential; import org.glassfish.appclient.client.acc.config.MessageSecurityConfig; import org.glassfish.appclient.client.acc.config.TargetServer; -//import org.glassfish.enterprise.iiop.api.GlassFishORBHelper; - -import org.jvnet.hk2.annotations.Service; import org.glassfish.hk2.api.PerLookup; +import org.jvnet.hk2.annotations.Service; /** * @@ -83,15 +82,11 @@ public class AppClientContainerSecurityHelper { private ClassLoader classLoader; - void init( - final TargetServer[] targetServers, - final List msgSecConfigs, - final Properties containerProperties, - final ClientCredential clientCredential, - final CallbackHandler callerSuppliedCallbackHandler, - final ClassLoader classLoader, - final ApplicationClientDescriptor acDesc, - final boolean isTextAuth) throws InstantiationException, IllegalAccessException, InjectionException, ClassNotFoundException, IOException { + void init(final TargetServer[] targetServers, final List msgSecConfigs, + final Properties containerProperties, final ClientCredential clientCredential, + final CallbackHandler callerSuppliedCallbackHandler, final ClassLoader classLoader, + final ApplicationClientDescriptor acDesc, final boolean isTextAuth) + throws InstantiationException, IllegalAccessException, InjectionException, ClassNotFoundException, IOException { this.classLoader = (classLoader == null) ? Thread.currentThread().getContextClassLoader() : classLoader; @@ -99,10 +94,10 @@ void init( CallbackHandler callbackHandler = initSecurity(callerSuppliedCallbackHandler, acDesc); - secInfo.initializeSecurity(Arrays.asList(targetServers), + secInfo.initializeSecurity( + Arrays.asList(targetServers), msgSecConfigs, callbackHandler, - AppClientSecurityInfo.CredentialType.USERNAME_PASSWORD, (clientCredential == null ? null : clientCredential.getUserName()), (clientCredential == null || clientCredential.getPassword() == null || diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/InvocationInfo.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/InvocationInfo.java index 240eda53184..37e616c11a3 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/InvocationInfo.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/InvocationInfo.java @@ -37,11 +37,11 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.ejb; import com.sun.ejb.containers.interceptors.InterceptorManager; -import com.sun.enterprise.security.jacc.cache.CachedPermission; +import com.sun.enterprise.security.ee.authorization.cache.CachedPermission; import org.glassfish.ejb.deployment.descriptor.EjbRemovalInfo; import java.lang.reflect.Method; diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/BaseContainer.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/BaseContainer.java index 5d3c51edc92..cf046d19601 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/BaseContainer.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/BaseContainer.java @@ -4237,7 +4237,7 @@ private RequestTraceSpanLog constructEjbMethodSpanLog(CallFlowInfo info, boolean } protected Object invokeTargetBeanMethod(Method beanClassMethod, EjbInvocation inv, Object target, - Object[] params, com.sun.enterprise.security.SecurityManager mgr) + Object[] params) throws Throwable { try { onEjbMethodStart(inv.invocationInfo.str_method_sig); @@ -4245,8 +4245,7 @@ protected Object invokeTargetBeanMethod(Method beanClassMethod, EjbInvocation in return inv.getBeanMethod().invoke(inv.ejb, inv.methodParams); } else { - return securityManager.invoke(beanClassMethod, inv.isLocal, target, - params); + return securityManager.invoke(target, beanClassMethod, params); } } catch (InvocationTargetException ite) { inv.exception = ite.getCause(); @@ -4813,7 +4812,7 @@ private Object __intercept(EjbInvocation inv) } } else { // invoke() has the same exc. semantics as Method.invoke result = this.invokeTargetBeanMethod(inv.getBeanMethod(), inv, inv.ejb, - inv.methodParams, null); + inv.methodParams); } return result; @@ -4832,8 +4831,7 @@ public Object invokeBeanMethod(EjbInvocation inv) { try { - return securityManager.invoke(inv.getBeanMethod(), inv.isLocal, inv.ejb, - inv.getParameters()); + return securityManager.invoke(inv.ejb, inv.getBeanMethod(), inv.getParameters()); } catch(InvocationTargetException ite) { throw ite.getCause(); diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/EJBHomeInvocationHandler.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/EJBHomeInvocationHandler.java index d9c3aa47cae..77ebc0f8d45 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/EJBHomeInvocationHandler.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/EJBHomeInvocationHandler.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2024] [Payara Foundation and/or its affiliates] package com.sun.ejb.containers; import java.lang.reflect.InvocationHandler; @@ -347,7 +347,7 @@ protected Object invokeTargetBeanMethod(BaseContainer container, Method beanClassMethod, EjbInvocation inv, Object target, Object[] params) throws Throwable { - return container.invokeTargetBeanMethod(beanClassMethod, inv, target, params, null); + return container.invokeTargetBeanMethod(beanClassMethod, inv, target, params); } private Object invokeEJBHomeMethod(String methodName, Object[] args) diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/EJBLocalHomeInvocationHandler.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/EJBLocalHomeInvocationHandler.java index 3d0a5ddbeb6..ec96c82908a 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/EJBLocalHomeInvocationHandler.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/EJBLocalHomeInvocationHandler.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package com.sun.ejb.containers; @@ -273,7 +273,7 @@ protected Object invokeTargetBeanMethod(BaseContainer container, Method beanClassMethod, EjbInvocation inv, Object target, Object[] params) throws Throwable { - return container.invokeTargetBeanMethod(beanClassMethod, inv, target, params, null); + return container.invokeTargetBeanMethod(beanClassMethod, inv, target, params); } } diff --git a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/security/application/EJBSecurityManager.java b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/security/application/EJBSecurityManager.java index ac21dc6213d..fda8ef3d34f 100644 --- a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/security/application/EJBSecurityManager.java +++ b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/security/application/EJBSecurityManager.java @@ -51,51 +51,44 @@ import com.sun.enterprise.security.common.AppservAccessController; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; -import com.sun.enterprise.security.jacc.JaccEJBConstraintsTranslator; -import com.sun.enterprise.security.jacc.cache.CachedPermission; -import com.sun.enterprise.security.jacc.cache.CachedPermissionImpl; -import com.sun.enterprise.security.jacc.cache.PermissionCache; -import com.sun.enterprise.security.jacc.cache.PermissionCacheFactory; -import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; +import com.sun.enterprise.security.ee.authorization.cache.PermissionCache; +import com.sun.enterprise.security.ee.authorization.cache.PermissionCacheFactory; import com.sun.enterprise.security.web.integration.GlassFishPrincipalMapper; import com.sun.logging.LogDomains; import jakarta.security.jacc.EJBMethodPermission; -import jakarta.security.jacc.EJBRoleRefPermission; -import jakarta.security.jacc.Policy; import jakarta.security.jacc.PolicyConfigurationFactory; import jakarta.security.jacc.PolicyContext; import jakarta.security.jacc.PolicyContextException; -import jakarta.security.jacc.PolicyFactory; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.AccessControlException; +import java.security.CodeSource; +import java.security.Principal; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import javax.security.auth.Subject; import org.glassfish.api.invocation.ComponentInvocation; import org.glassfish.api.invocation.InvocationException; import org.glassfish.api.invocation.InvocationManager; import org.glassfish.deployment.common.SecurityRoleMapperFactory; import org.glassfish.ejb.deployment.descriptor.EjbDescriptor; import org.glassfish.ejb.security.factory.EJBSecurityManagerFactory; +import org.glassfish.exousia.AuthorizationService; import org.glassfish.exousia.permissions.RolesToPermissionsTransformer; import org.glassfish.external.probe.provider.PluginPoint; import org.glassfish.external.probe.provider.StatsProviderManager; - -import javax.security.auth.Subject; -import javax.security.auth.SubjectDomainCombiner; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.*; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Collectors; - -import org.glassfish.exousia.AuthorizationService; - import org.glassfish.security.common.Role; -import static com.sun.enterprise.security.common.AppservAccessController.doPrivileged; import static com.sun.enterprise.security.common.AppservAccessController.privileged; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; +import static java.util.logging.Level.*; /** * This class is used by the EJB server to manage security. All the container object only call into this object for @@ -110,9 +103,7 @@ public final class EJBSecurityManager implements SecurityManager { private static final Logger _logger = LogDomains.getLogger(EJBSecurityManager.class, LogDomains.EJB_LOGGER); private AppServerAuditManager auditManager; - - private static final PolicyContextHandlerImpl pcHandlerImpl = (PolicyContextHandlerImpl) PolicyContextHandlerImpl.getInstance(); - + private final SecurityRoleMapperFactory roleMapperFactory; private final EjbDescriptor deploymentDescriptor; @@ -127,7 +118,6 @@ public final class EJBSecurityManager implements SecurityManager { // contextId id is the same as an appname. This will be used to get // a PolicyConfiguration object per application. private String contextId; - private CodeSource codesource; private String realmName; // We use two protection domain caches until we decide how to @@ -142,9 +132,7 @@ public final class EJBSecurityManager implements SecurityManager { private final Map accessControlContextCache = Collections.synchronizedMap(new WeakHashMap()); private PermissionCache uncheckedMethodPermissionCache; - - private final Policy policy; - + private static final CodeSource managerCodeSource = EJBSecurityManager.class.getProtectionDomain().getCodeSource(); private final InvocationManager invocationManager; @@ -159,64 +147,24 @@ public EJBSecurityManager(EjbDescriptor ejbDescriptor, InvocationManager invocat this.deploymentDescriptor = ejbDescriptor; this.invocationManager = invocationManager; roleMapperFactory = SecurityUtil.getRoleMapperFactory(); - // get the default policy - policy = PolicyFactory.getPolicyFactory().getPolicy(); securityManagerFactory = fact; - boolean runas = !(deploymentDescriptor.getUsesCallerIdentity()); - if (runas) { - runAs = deploymentDescriptor.getRunAsIdentity(); - - // Note: runAs may be null even when runas==true if this EJB - // is an MDB. - if (runAs != null) { - if (_logger.isLoggable(FINE)) { - _logger.fine(deploymentDescriptor.getEjbClassName() + " will run-as: " + runAs.getPrincipal() + " (" - + runAs.getRoleName() + ")"); - } - } - } else { - runAs = null; - } - - if (ejbStatsProvider == null) { - synchronized (EjbSecurityStatsProvider.class) { - if (ejbStatsProvider == null) { - ejbStatsProvider = new EjbSecurityStatsProvider(); - StatsProviderManager.register("security", PluginPoint.SERVER, "security/ejb", ejbStatsProvider); - } - } - } + runAs = getRunAs(deploymentDescriptor); + setEnterpriseBeansStatsProvider(); contextId = getContextID(deploymentDescriptor); String appName = deploymentDescriptor.getApplication().getRegistrationName(); roleMapperFactory.setAppNameForContext(appName, contextId); - codesource = getApplicationCodeSource(contextId); ejbName = deploymentDescriptor.getName(); - realmName = deploymentDescriptor.getApplication().getRealm(); - - if (realmName == null) { - Set iorConfigs = deploymentDescriptor.getIORConfigurationDescriptors(); - // iorConfigs is not null from implementation of EjbDescriptor - Iterator iter = iorConfigs.iterator(); - if (iter != null) { - // there should be at most one element in the loop from - // definition of dtd - while (iter.hasNext()) { - realmName = iter.next().getRealmName(); - } - } - } + realmName = getRealmName(deploymentDescriptor); + _logger.fine(() -> "JACC: EJB name = '" + ejbName + "'. Context id (id under which all EJB's in application will be created) = '" + contextId + "'"); - loadPolicyConfiguration(deploymentDescriptor); - // translate the deployment descriptor to populate the role-ref permission cache - // addEJBRoleReferenceToCache(deploymentDescriptor); // create and initialize the unchecked permission cache. - uncheckedMethodPermissionCache = PermissionCacheFactory.createPermissionCache(this.contextId, this.codesource, + uncheckedMethodPermissionCache = PermissionCacheFactory.createPermissionCache(this.contextId, EJBMethodPermission.class, this.ejbName); auditManager = this.securityManagerFactory.getAuditManager(); @@ -239,10 +187,56 @@ public EJBSecurityManager(EjbDescriptor ejbDescriptor, InvocationManager invocat PayaraToExousiaConverter.getSecurityRoleRefsFromBundle(ejbDescriptor))); } + private String getRealmName(EjbDescriptor deploymentDescriptor) { + String realmName = deploymentDescriptor.getApplication().getRealm(); + + if (realmName == null) { + for (EjbIORConfigurationDescriptor iorConfig : deploymentDescriptor.getIORConfigurationDescriptors()) { + // There should be at most one element in the loop from + // definition of dtd + realmName = iorConfig.getRealmName(); + } + } + + return realmName; + } + public static String getContextID(EjbDescriptor ejbDescriptor) { return SecurityUtil.getContextID(ejbDescriptor.getEjbBundleDescriptor()); } + private void setEnterpriseBeansStatsProvider() { + if (ejbStatsProvider == null) { + synchronized (EjbSecurityStatsProvider.class) { + if (ejbStatsProvider == null) { + ejbStatsProvider = new EjbSecurityStatsProvider(); + StatsProviderManager.register("security", PluginPoint.SERVER, "security/ejb", ejbStatsProvider); + } + } + } + } + + private RunAsIdentityDescriptor getRunAs(EjbDescriptor deploymentDescriptor) { + if (deploymentDescriptor.getUsesCallerIdentity()) { + return null; + } + + RunAsIdentityDescriptor runAs = deploymentDescriptor.getRunAsIdentity(); + + // Note: runAs may be null even when runas==true if this Enterprise Bean + // is an MDB. + if (runAs != null) { + if (_logger.isLoggable(FINE)) { + _logger.log(FINE, + deploymentDescriptor.getEjbClassName() + " will run-as: " + runAs.getPrincipal() + + " (" + runAs.getRoleName() + ")"); + } + } + + return runAs; + + } + /** * This method is used by MDB Container - Invocation Manager to setup the run-as identity information. It has to be * coupled with the postSetRunAsIdentity method. This method is called for EJB/MDB Containers @@ -271,6 +265,11 @@ public void preInvoke(ComponentInvocation inv) { } } + @Override + public Object invoke(Object bean, Method beanClassMethod, Object[] methodParameters) throws Throwable { + return authorizationService.invokeBeanMethod(bean, beanClassMethod, methodParameters); + } + /** * This method is used by Message Driven Bean Container to remove the run-as identity information that was set up using * the preSetRunAsIdentity method @@ -285,31 +284,7 @@ public void postInvoke(ComponentInvocation inv) { public boolean getUsesCallerIdentity() { return runAs == null; } - - public void loadPolicyConfiguration(EjbDescriptor ejbDescriptor) throws Exception { - PolicyConfigurationFactory factory = getPolicyFactory(); - - boolean inService = factory.inService(contextId); - - // Only load the policy configuration if it isn't already in service. - // - // Consequently, all things that deploy modules (as apposed to/ loading already - // deployed modules) must make sure a pre-existing PolicyConfiguration - // is either in deleted or open state before this method is called. - // - // Note that policy statements are not removed to allow multiple EJBs to be - // represented by same PolicyConfiguration. - - if (!inService) { - // Translate the deployment descriptor to configure the policy rules - JaccEJBConstraintsTranslator.translateConstraintsToPermissions(ejbDescriptor, factory.getPolicyConfiguration(contextId, false)); - - if (_logger.isLoggable(FINE)) { - _logger.fine("JACC: policy translated for policy context:" + contextId); - } - } - } - + /** * This method is called by the EJB container to decide whether or not a method specified in the Invocation should be * allowed. @@ -328,79 +303,44 @@ public boolean authorize(ComponentInvocation componentInvocation) { return ejbInvocation.getAuth().booleanValue(); } - boolean isAuthorized = false; - - CachedPermission cachedPermission = null; - Permission permission = null; - - if (ejbInvocation.invocationInfo == null || ejbInvocation.invocationInfo.cachedPermission == null) { - permission = new EJBMethodPermission(ejbName, ejbInvocation.getMethodInterface(), ejbInvocation.method); - cachedPermission = new CachedPermissionImpl(uncheckedMethodPermissionCache, permission); - - if (ejbInvocation.invocationInfo != null) { - ejbInvocation.invocationInfo.cachedPermission = cachedPermission; - if (_logger.isLoggable(FINE)) { - _logger.fine("JACC: permission initialized in InvocationInfo: EJBMethodPermission (Name) = " + permission.getName() - + " (Action) = " + permission.getActions()); - } - } - } else { - cachedPermission = ejbInvocation.invocationInfo.cachedPermission; - permission = cachedPermission.getPermission(); - } - - String caller = null; - SecurityContext securityContext = null; - - pcHandlerImpl.getHandlerData().setInvocation(ejbInvocation); - - isAuthorized = cachedPermission.checkPermission(); + SecurityContext securityContext = SecurityContext.getCurrent(); - if (!isAuthorized) { - - securityContext = SecurityContext.getCurrent(); - - try { - // Set the policy context in the TLS. - String oldContextId = setPolicyContext(contextId); - - try { - isAuthorized = policy.implies(permission, securityContext.getSubject()); - } catch (Throwable t) { - _logger.log(SEVERE, "jacc_access_exception", t); - isAuthorized = false; - } finally { - resetPolicyContext(oldContextId, contextId); - } - } catch (Throwable t) { - _logger.log(SEVERE, "jacc_policy_context_exception", t); - isAuthorized = false; - } + boolean authorized = false; + try { + authorized = authorizationService.checkBeanMethodPermission( + ejbName, + ejbInvocation.getMethodInterface(), + ejbInvocation.method, + securityContext.getPrincipalSet()); + } catch (Throwable t) { + _logger.log(SEVERE, "Unexpected exception manipulating policy context", t); + authorized = false; } - ejbInvocation.setAuth(isAuthorized); + ejbInvocation.setAuth(authorized); - if (auditManager.isAuditOn()) { - if (securityContext == null) { - securityContext = SecurityContext.getCurrent(); - } - caller = securityContext.getCallerPrincipal().getName(); - auditManager.ejbInvocation(caller, ejbName, ejbInvocation.method.toString(), isAuthorized); - } + doAuditAuthorize(securityContext, ejbInvocation, authorized); - if (isAuthorized && ejbInvocation.isWebService && !ejbInvocation.isPreInvokeDone()) { + if (authorized && ejbInvocation.isWebService && !ejbInvocation.isPreInvokeDone()) { preInvoke(ejbInvocation); } + if (_logger.isLoggable(FINE)) { _logger.fine( - "JACC: Access Control Decision Result: " + isAuthorized + - " EJBMethodPermission (Name) = " + permission.getName() + - " (Action) = " + permission.getActions() + - " (Caller) = " + caller); + "JACC: Access Control Decision Result: " + authorized); } - return isAuthorized; + return authorized; + } + + private void doAuditAuthorize(SecurityContext securityContext, EjbInvocation ejbInvocation, boolean authorized) { + if (auditManager.isAuditOn()) { + String caller = securityContext.getCallerPrincipal().getName(); + auditManager.ejbInvocation(caller, ejbName, ejbInvocation.method.toString(), authorized); + + _logger.fine(() -> " (Caller) = " + caller); + } } /** @@ -411,103 +351,34 @@ public boolean authorize(ComponentInvocation componentInvocation) { */ @Override public boolean isCallerInRole(String role) { - /* - * In case of Run As - Should check isCallerInRole with respect to the old security context. - */ - boolean isCallerInRole = false; - if (_logger.isLoggable(FINE)) { _logger.entering("EJBSecurityManager", "isCallerInRole", role); - - } - EJBRoleRefPermission ejbRoleRefPermission = new EJBRoleRefPermission(ejbName, role); - - SecurityContext securityContext; - if (runAs != null) { - securityContext = (SecurityContext) invocationManager.getCurrentInvocation().getOldSecurityContext(); - } else { - securityContext = SecurityContext.getCurrent(); } + SecurityContext securityContext = getSecurityContext(); Set principalSet = securityContext != null ? securityContext.getPrincipalSet() : null; - ProtectionDomain prdm = getCachedProtectionDomain(principalSet, true); - String oldContextId = null; - try { - // set the policy context in the TLS. - oldContextId = setPolicyContext(this.contextId); - isCallerInRole = policy.implies(ejbRoleRefPermission, principalSet); - } catch (Throwable t) { - _logger.log(Level.SEVERE, "jacc_is_caller_in_role_exception", t); - isCallerInRole = false; - } finally { - try { - resetPolicyContext(oldContextId, contextId); - } catch (Throwable ex) { - _logger.log(Level.SEVERE, "jacc_policy_context_exception", ex); - isCallerInRole = false; - } - } + return authorizationService.checkBeanRoleRefPermission(ejbName, role, principalSet); + } - if (_logger.isLoggable(Level.FINE)) { - _logger.fine("JACC: isCallerInRole Result: " + isCallerInRole + " EJBRoleRefPermission (Name) = " + ejbRoleRefPermission.getName() + " (Action) = " - + ejbRoleRefPermission.getActions() + " (Codesource) = " + prdm.getCodeSource()); + private SecurityContext getSecurityContext() { + if (runAs == null) { + return SecurityContext.getCurrent(); } - return isCallerInRole; - } + // Return the principal associated with the old security context + ComponentInvocation componentInvocation = invocationManager.getCurrentInvocation(); - /** - * This method is similiar to the runMethod, except it keeps the semantics same as the one in reflection. On failure, if - * the exception is caused due to reflection, it returns the InvocationTargetException. This method is called from the - * containers for ejbTimeout, WebService and MDBs. - * - * @param beanClassMethod, the bean class method to be invoked - * @param isLocal, true if this invocation is through the local EJB view - * @param beanObject the object on which this method is to be invoked in this case the ejb, - * @param parameters the parameters for the method, - * manager. - * @return Object, the result of the execution of the method. - */ - @Override - public Object invoke(Method beanClassMethod, boolean isLocal, Object beanObject, Object[] parameters) throws Throwable { - - // Optimization. Skip doAsPrivileged call if this is a local invocation and the target EJB - // uses caller identity or the System Security Manager is disabled. - // - // Still need to execute it within the target bean's policy context. - // see CR 6331550 - if ((isLocal && getUsesCallerIdentity()) || System.getSecurityManager() == null) { - return runMethod(beanClassMethod, beanObject, parameters); + if (componentInvocation == null) { + throw new InvocationException(); } - try { - return doAsPrivileged(()-> beanClassMethod.invoke(beanObject, parameters)); - } catch (PrivilegedActionException pae) { - throw pae.getCause(); - } + return (SecurityContext) componentInvocation.getOldSecurityContext(); } - + @Override public void resetPolicyContext() { - try { - doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - ((PolicyContextHandlerImpl) PolicyContextHandlerImpl.getInstance()).reset(); - PolicyContext.setContextID(null); - return null; - } - }); - } catch (PrivilegedActionException pae) { - Throwable cause = pae.getCause(); - if (cause instanceof java.security.AccessControlException) { - _logger.log(Level.SEVERE, "jacc_policy_context_security_exception", cause); - } else { - _logger.log(Level.SEVERE, "jacc_policy_context_exception", cause); - } - throw new RuntimeException(cause); - } + PolicyContext.setContextID(null); } @@ -546,22 +417,19 @@ public Principal getCallerPrincipal() { @Override public void destroy() { try { + authorizationService.refresh(); - boolean wasInService = getPolicyFactory().inService(this.contextId); - if (wasInService) { - policy.refresh(); - } /* - * all ejbs of module share same policy context, but each has its own permission cache, which must be unregistered from - * factory to avoid leak. + * All enterprise beans of module share same policy context, but each has its + * own permission cache, which must be unregistered from factory to + * avoid leaks. */ PermissionCacheFactory.removePermissionCache(uncheckedMethodPermissionCache); uncheckedMethodPermissionCache = null; - roleMapperFactory.removeAppNameForContext(this.contextId); + roleMapperFactory.removeAppNameForContext(contextId); - } catch (PolicyContextException pce) { - // Just log it. - _logger.log(Level.WARNING, "ejbsm.could_not_delete", pce); + } catch (IllegalStateException e) { + _logger.log(WARNING, "ejbsm.could_not_delete", e); } probeProvider.securityManagerDestructionStartedEvent(ejbName); @@ -586,64 +454,6 @@ public Subject getCurrentSubject() { return SecurityContext.getCurrent().getSubject(); } - /* - * This method is used by SecurityUtil runMethod to run the action as the subject encapsulated in the current - * SecurityContext. - */ - @Override - public Object doAsPrivileged(PrivilegedExceptionAction pea) throws Throwable { - - SecurityContext sc = SecurityContext.getCurrent(); - Set principalSet = sc.getPrincipalSet(); - AccessControlContext acc = (AccessControlContext) accessControlContextCache.get(principalSet); - - if (acc == null) { - final ProtectionDomain[] pdArray = new ProtectionDomain[1]; - pdArray[0] = getCachedProtectionDomain(principalSet, false); - try { - if (principalSet != null) { - - final Subject s = sc.getSubject(); - - acc = (AccessControlContext) AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - return new AccessControlContext(new AccessControlContext(pdArray), new SubjectDomainCombiner(s)); - } - }); - } else { - acc = new AccessControlContext(pdArray); - } - - // form a new key set so that it does not share with - // cacheProtectionDomain and protectionDomainCache - if (principalSet != null) { - accessControlContextCache.put(new HashSet(principalSet), acc); - } - - _logger.fine("JACC: new AccessControlContext added to cache"); - - } catch (Exception e) { - _logger.log(Level.SEVERE, "java_security.security_context_exception", e); - acc = null; - throw e; - } - } - - Object rvalue = null; - String oldContextId = setPolicyContext(this.contextId); - if (_logger.isLoggable(Level.FINE)) { - _logger.fine("JACC: doAsPrivileged contextId(" + this.contextId + ")"); - } - - try { - rvalue = AccessController.doPrivileged(pea, acc); - } finally { - resetPolicyContext(oldContextId, this.contextId); - } - return rvalue; - } - /** * Runs a business method of an EJB within the bean's policy context. The original policy context is restored after * method execution. This method should only be used by com.sun.enterprise.security.SecurityUtil. @@ -664,71 +474,6 @@ public Object runMethod(Method beanClassMethod, Object beanObject, Object[] para } } - - // ### Private methods - - private ProtectionDomain getCachedProtectionDomain(Set principalSet, boolean applicationCodeSource) { - ProtectionDomain prdm = null; - Principal[] principals = null; - - /* - * Need to use the application codeSource for permission evaluations as the manager codesource is granted all - * permissions in server.policy. The manager codesource needs to be used for doPrivileged to allow system apps to have - * all permissions, but we either need to revert to real doAsPrivileged, or find a way to distinguish system apps. - */ - - CodeSource cs = null; - - if (applicationCodeSource) { - prdm = (ProtectionDomain) cacheProtectionDomain.get(principalSet); - cs = codesource; - } else { - prdm = (ProtectionDomain) protectionDomainCache.get(principalSet); - cs = managerCodeSource; - } - - if (prdm == null) { - - principals = (principalSet == null ? null : (Principal[]) principalSet.toArray(new Principal[principalSet.size()])); - - prdm = new ProtectionDomain(cs, null, null, principals); - - // form a new key set so that it does not share with others - Set newKeySet = ((principalSet != null) ? new HashSet(principalSet) : new HashSet()); - - if (applicationCodeSource) { - cacheProtectionDomain.put(newKeySet, prdm); - } else { - // form a new key set so that it does not share with others - protectionDomainCache.put(newKeySet, prdm); - } - - if (_logger.isLoggable(FINE)) { - _logger.fine("JACC: new ProtectionDomain added to cache"); - } - - } - - if (_logger.isLoggable(FINE)) { - if (principalSet == null) { - _logger.fine("JACC: returning cached ProtectionDomain PrincipalSet: null"); - } else { - StringBuilder pBuf = null; - principals = (Principal[]) principalSet.toArray(new Principal[principalSet.size()]); - for (int i = 0; i < principals.length; i++) { - if (i == 0) { - pBuf = new StringBuilder(principals[i].toString()); - } else { - pBuf.append(" " + principals[i].toString()); - } - } - _logger.fine("JACC: returning cached ProtectionDomain - CodeSource: (" + cs + ") PrincipalSet: " + pBuf); - } - } - - return prdm; - } - /** * Logs in a principal for run-as. This method is called if the run-as principal is required. The user has already * logged in - now it needs to change to the new principal. In order that all the correct permissions work - this method diff --git a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java index 46326ada624..f8889ca99ba 100644 --- a/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java +++ b/appserver/ejb/ejb-container/src/main/java/org/glassfish/ejb/startup/EjbDeployer.java @@ -89,7 +89,7 @@ import com.sun.enterprise.deployment.Application; import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.module.bootstrap.StartupContext; -import com.sun.enterprise.security.PolicyLoader; +import com.sun.enterprise.security.ee.authorization.PolicyLoader; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.util.IASSecurityException; import com.sun.enterprise.util.LocalStringManagerImpl; diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java index caf56d83822..4d4a6c75477 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java @@ -847,7 +847,7 @@ protected Object invokeFindByPrimaryKey(Method method, throws Throwable { Object pKeys = super.invokeTargetBeanMethod(method, - inv, inv.ejb, args, null); + inv, inv.ejb, args); return postFind(inv, pKeys, null); } diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/ReadOnlyBeanContainer.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/ReadOnlyBeanContainer.java index 639b8f2b8dc..b49eee335f2 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/ReadOnlyBeanContainer.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/ReadOnlyBeanContainer.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2024] [Payara Foundation and/or its affiliates] package org.glassfish.persistence.ejb.entitybean.container; @@ -572,7 +573,7 @@ protected Object invokeTargetBeanMethod(Method beanClassMethod, EjbInvocation in value = finderResultsCache.get(key); if (value == null) { returnValue = super.invokeTargetBeanMethod( - beanClassMethod, inv, target, params, mgr); + beanClassMethod, inv, target, params); finderResultsCache.put(key, new FinderResultsValue(returnValue, currentTimeInMillis)); } else { @@ -583,7 +584,7 @@ protected Object invokeTargetBeanMethod(Method beanClassMethod, EjbInvocation in } else { returnValue = super.invokeTargetBeanMethod(beanClassMethod, inv, - target, params, mgr); + target, params); } return returnValue; diff --git a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java index e5fd188d81e..fa06882b2bd 100644 --- a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java +++ b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/AppClientSecurityInfoImpl.java @@ -48,12 +48,10 @@ import com.sun.enterprise.security.common.ClientSecurityContext; import com.sun.enterprise.security.common.SecurityConstants; import com.sun.enterprise.security.common.Util; -import com.sun.enterprise.security.ee.J2EESecurityManager; import com.sun.enterprise.security.integration.AppClientSSL; import com.sun.enterprise.security.ssl.SSLUtils; import com.sun.logging.LogDomains; import jakarta.inject.Inject; -import jakarta.security.auth.message.config.AuthConfigFactory; import org.glassfish.appclient.client.acc.config.MessageSecurityConfig; import org.glassfish.appclient.client.acc.config.Security; import org.glassfish.appclient.client.acc.config.Ssl; @@ -65,9 +63,13 @@ import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import java.util.List; -import java.util.logging.Level; + import java.util.logging.Logger; +import static jakarta.security.auth.message.config.AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY; +import static java.util.logging.Level.WARNING; +import static java.util.logging.Level.FINE; + /** * * @author Kumar @@ -76,16 +78,16 @@ @Service public class AppClientSecurityInfoImpl implements AppClientSecurityInfo { - private static Logger _logger=null; + private static Logger logger = null; + static { - _logger=LogDomains.getLogger(AppClientSecurityInfoImpl.class, LogDomains.SECURITY_LOGGER); + logger = LogDomains.getLogger(AppClientSecurityInfoImpl.class, LogDomains.SECURITY_LOGGER); } private static final String DEFAULT_PARSER_CLASS = "com.sun.enterprise.security.appclient.ConfigXMLParser"; private CallbackHandler callbackHandler; - private CredentialType appclientCredentialType; boolean isJWS; boolean useGUIAuth; private List targetServers; @@ -101,16 +103,13 @@ public class AppClientSecurityInfoImpl implements AppClientSecurityInfo { @Inject private IIOPSSLUtil appClientSSLUtil; - public void initializeSecurity( - List tServers, - List configs, CallbackHandler handler, - CredentialType credType, String username, - char[] password, boolean isJWS, boolean useGUIAuth) { + public void initializeSecurity(List tServers, List configs, + CallbackHandler handler, String username, char[] password, + boolean isJWS, boolean useGUIAuth) { /* security init */ this.isJWS = isJWS; this.useGUIAuth = useGUIAuth; - this.appclientCredentialType = credType; if (handler != null) { this.callbackHandler = handler; } else { @@ -119,49 +118,21 @@ public void initializeSecurity( this.targetServers = tServers; this.msgSecConfigs = configs; - SecurityManager secMgr = System.getSecurityManager(); - if (!isJWS && secMgr != null && - !(J2EESecurityManager.class.equals(secMgr.getClass()))) { - J2EESecurityManager mgr = new J2EESecurityManager(); - System.setSecurityManager(mgr); - } - if (_logger.isLoggable(Level.FINE)) { - if (secMgr != null) { - _logger.fine("acc.secmgron"); - } else { - _logger.fine("acc.secmgroff"); - } - } - //set the parser to ConfigXMLParser System.setProperty("config.parser", DEFAULT_PARSER_CLASS); util.setAppClientMsgSecConfigs(msgSecConfigs); - try { - /* setup jsr 196 factory - * define default factory if it is not already defined - */ - String defaultFactory = java.security.Security.getProperty - (AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY); - _logger.fine("AuthConfigFactory obtained from java.security.Security.getProperty(\"authconfigprovider.factory\") :" - + ((defaultFactory != null) ? defaultFactory : "NULL")); - if (defaultFactory == null) { - java.security.Security.setProperty - (AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY, - AuthConfigFileFactory.class.getName()); - } - - } catch (Exception e) { - _logger.log(Level.WARNING, "main.jaspic_default_factory"); - } - - //TODO:V3 LoginContextDriver has a static variable dependency on AuditManager - //And since LoginContextDriver has too many static methods that use AuditManager - //we have to make this workaround here. - //Handles in LoginContextDriver - //LoginContextDriver.AUDIT_MANAGER = secServUtil.getAuditManager(); - - //secServUtil.initSecureSeed(); - + try { + // Setup Jakarta Authentication factory define default factory if it is not already defined + String defaultFactory = java.security.Security.getProperty(DEFAULT_FACTORY_SECURITY_PROPERTY); + logger.log(FINE, "AuthConfigFactory obtained from java.security.Security.getProperty(\"authconfigprovider.factory\"): {0}", + defaultFactory); + if (defaultFactory == null) { + java.security.Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, AuthConfigFileFactory.class.getName()); + } + } catch (Exception e) { + logger.log(WARNING, "SEC9001: ACC: Error in initializing Jakarta Authentication Default Factory", e); + } + setSSLData(this.getTargetServers()); if (username != null || password != null) { UsernamePasswordStore.set(username, password); @@ -209,13 +180,13 @@ private void setSSLData(List tServers) { // first one will be used. Security security = tServer.getSecurity(); if (security == null) { - _logger.fine("No Security input set in ClientContainer.xml"); + logger.log(FINE,"No Security input set in ClientContainer.xml"); // do nothing return; } Ssl ssl = security.getSsl(); if (ssl == null) { - _logger.fine("No SSL input set in ClientContainer.xml"); + logger.log(FINE,"No SSL input set in ClientContainer.xml"); // do nothing return; diff --git a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/integration/AppClientSecurityInfo.java b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/integration/AppClientSecurityInfo.java index 67190114165..8ebc5279567 100644 --- a/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/integration/AppClientSecurityInfo.java +++ b/appserver/security/appclient.security/src/main/java/com/sun/enterprise/security/appclient/integration/AppClientSecurityInfo.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.appclient.integration; import java.util.List; @@ -76,7 +76,6 @@ public void initializeSecurity( List tServers, List msgSecConfigs, CallbackHandler handler, - CredentialType appclientCredType, String username, char[] password, boolean isJWS, boolean useGUIAuth); diff --git a/appserver/security/core-ee/osgi.bundle b/appserver/security/core-ee/osgi.bundle index 35dbe68e0c6..4757c14bb50 100644 --- a/appserver/security/core-ee/osgi.bundle +++ b/appserver/security/core-ee/osgi.bundle @@ -46,6 +46,7 @@ com.sun.enterprise.security.ee.auth.login; \ com.sun.enterprise.security.auth.realm.jdbc; \ com.sun.enterprise.security.ee.authorization; \ + com.sun.enterprise.security.ee.authorization.cache; \ com.sun.enterprise.security.ee.authentication.jakarta; \ com.sun.enterprise.security.ee.authentication.jakarta.callback; \ com.sun.enterprise.security.ee.web; \ @@ -55,9 +56,6 @@ com.sun.enterprise.security.jaspic.callback; \ com.sun.enterprise.security.jaspic.config; \ com.sun.enterprise.security.auth.realm.pam; \ - com.sun.enterprise.security.jacc; \ - com.sun.enterprise.security.jacc.cache; \ - com.sun.enterprise.security.jacc.context; \ com.sun.enterprise.security.auth.digest.impl; \ com.sun.enterprise.security.permissionsxml; \ com.sun.enterprise.security.web.integration; version=${project.osgi.version} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/J2EESecurityManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/J2EESecurityManager.java deleted file mode 100644 index eb9b4eeda0d..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/J2EESecurityManager.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.ee; - -import com.sun.enterprise.security.jacc.cache.CachedPermissionImpl; -import com.sun.enterprise.security.jacc.cache.PermissionCache; -import com.sun.enterprise.security.ssl.SSLUtils; -import java.net.SocketPermission; - -import java.util.*; -// IASRI 4660742 START -// IASRI 4660742 END - -/** - * Java 2 security manager that enforces code security. - * - * @author Harish Prabandham - */ -public class J2EESecurityManager extends java.rmi.RMISecurityManager { - - private CachedPermissionImpl connectPerm; - - private PermissionCache cache; - - private boolean cacheEnabled = false; - - public J2EESecurityManager() { - } - - @Override - public void checkAccess(ThreadGroup t) { - super.checkAccess(t); - checkPermission(new java.lang.RuntimePermission("modifyThreadGroup")); - } - - @Override - public void checkPackageAccess(final String pkgname) { - // Remove this once 1.2.2 SecurityManager/ClassLoader bug is fixed. - if (!pkgname.startsWith("sun.")) - super.checkPackageAccess(pkgname); - } - - @Override - public void checkExit(int status) { - // Verify exit permission - super.checkExit(status); - } - - @Override - public void checkConnect(String host, int port) { - if (checkConnectPermission()) { - return; - } - super.checkConnect(host, port); - } - - @Override - public void checkConnect(String host, int port, Object context) { - if (checkConnectPermission()) { - return; - } - super.checkConnect(host, port, context); - } - - @Override - public void checkPropertyAccess(String key) { - if (checkProperty(key)) { - return; - } - super.checkPropertyAccess(key); - } - - private boolean checkConnectPermission() { - if (cacheEnabled()) { - return connectPerm.checkPermission(); - } - return false; - } - - private boolean checkProperty(String key) { - if (key.equals("javax.net.ssl.keyStorePassword") || key.equals("javax.net.ssl.trustStorePassword")) { - SSLUtils.checkPermission(key); - } - if (cacheEnabled()) { - return cache.checkPermission(new PropertyPermission(key, "read")); - } - return false; - } - - public synchronized boolean cacheEnabled() { - return cacheEnabled; - } - - public synchronized void enablePermissionCache(PermissionCache c) { - if (c != null) { - cache = c; - connectPerm = new CachedPermissionImpl(cache, new SocketPermission("*", "connect")); - cacheEnabled = true; - } - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java index 8218e65592b..306b5a873b5 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/JavaEESecurityLifecycle.java @@ -41,7 +41,7 @@ package com.sun.enterprise.security.ee; import com.sun.enterprise.security.ContainerSecurityLifecycle; -import com.sun.enterprise.security.PolicyLoader; +import com.sun.enterprise.security.ee.authorization.PolicyLoader; import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; @@ -61,14 +61,12 @@ import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; import org.glassfish.hk2.api.PostConstruct; import org.glassfish.hk2.api.Rank; -import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.internal.api.Globals; import org.glassfish.internal.api.InitRunLevel; import org.jvnet.hk2.annotations.Service; import static jakarta.security.auth.message.config.AuthConfigFactory.DEFAULT_FACTORY_SECURITY_PROPERTY; import static org.glassfish.epicyro.config.factory.file.AuthConfigFileFactory.DEFAULT_FACTORY_DEFAULT_PROVIDERS; -import static java.util.logging.Level.WARNING; /** @@ -89,28 +87,12 @@ public class JavaEESecurityLifecycle implements ContainerSecurityLifecycle, Post @Override public void postConstruct() { onInitialization(); - initializeJakartaAuthentication(); - initializeJakartaAuthorization(); } @Override public void onInitialization() { - LOG.finest(() -> "Initializing " + getClass()); - - // TODO: Need some way to not override the security manager if the EmbeddedServer was - // run with a different non-default security manager. - // - // Right now there seems no way to find out if the security manager is the VM's default security manager. - final SecurityManager systemSecurityManager = System.getSecurityManager(); - if (systemSecurityManager != null && !(J2EESecurityManager.class.equals(systemSecurityManager.getClass()))) { - J2EESecurityManager eeSecurityManager = new J2EESecurityManager(); - try { - System.setSecurityManager(eeSecurityManager); - LOG.config(() -> "System security manager has been set to " + eeSecurityManager); - } catch (SecurityException ex) { - LOG.log(WARNING, "security.secmgr.could.not.override", ex); - } - } + initializeJakartaAuthentication(); + initializeJakartaAuthorization(); } private void initializeJakartaAuthentication() { diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java index ccdf2f64323..6476b4888e9 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java @@ -52,7 +52,6 @@ import com.sun.enterprise.security.SecurityLifecycle; import com.sun.enterprise.security.WebSecurityDeployerProbeProvider; import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; -import com.sun.enterprise.security.ee.web.integration.WebSecurityManager; import com.sun.enterprise.security.util.IASSecurityException; import com.sun.enterprise.security.ee.web.integration.WebSecurityManagerFactory; import com.sun.logging.LogDomains; @@ -88,7 +87,7 @@ import static com.sun.enterprise.deployment.WebBundleDescriptor.AFTER_SERVLET_CONTEXT_INITIALIZED_EVENT; import static com.sun.enterprise.security.ee.SecurityUtil.getContextID; -import static java.util.logging.Level.CONFIG; +import static com.sun.enterprise.security.ee.SecurityUtil.removeRoleMapper; import static java.util.logging.Level.WARNING; import static org.glassfish.internal.deployment.Deployment.APPLICATION_LOADED; import static org.glassfish.internal.deployment.Deployment.APPLICATION_PREPARED; @@ -155,7 +154,7 @@ public void event(Event event) { return; } WebBundleDescriptor webBD = (WebBundleDescriptor) moduleInfo.getMetaData("org.glassfish.web.deployment.descriptor.WebBundleDescriptorImpl"); - loadPolicy(webBD, false); + loadWebPolicy(webBD, false); } else if (APPLICATION_LOADED.equals(event.type())) { ApplicationInfo appInfo = (ApplicationInfo) event.hook(); app = appInfo.getMetaData(Application.class); @@ -205,7 +204,7 @@ protected void generateArtifacts(DeploymentContext context) throws DeploymentExc for (WebBundleDescriptor webBundleDescriptor : webBundleDescriptors) { webBundleDescriptor.setApplicationClassLoader(context.getFinalClassLoader()); - loadPolicy(webBundleDescriptor, false); + loadWebPolicy(webBundleDescriptor, false); } } catch (Exception se) { @@ -216,11 +215,11 @@ protected void generateArtifacts(DeploymentContext context) throws DeploymentExc // removes security policy if needed @Override protected void cleanArtifacts(DeploymentContext context) throws DeploymentException { - removePolicy(context); - SecurityUtil.removeRoleMapper(context); + deletePolicy(context); + removeRoleMapper(context); OpsParams params = context.getCommandParameters(OpsParams.class); - if (this.appCnonceMap != null) { + if (appCnonceMap != null) { CNonceCache cache = appCnonceMap.remove(params.name()); if (cache != null) { cache.destroy(); @@ -250,39 +249,31 @@ public MetaData getMetaData() { /** * Translate Web Bundle Policy * - * @param webDescriptor + * @param webBundleDescriptor * @param remove boolean indicated whether any existing policy statements are removed form context before translation * @throws DeploymentException */ - public void loadPolicy(WebBundleDescriptor webDescriptor, boolean remove) throws DeploymentException { - if (webDescriptor == null) { - return; - } + private void loadWebPolicy(WebBundleDescriptor webBundleDescriptor, boolean remove) throws DeploymentException { try { - if (remove) { - WebAuthorizationManagerService authorizationManager = webSecurityManagerFactory - .getManager(getContextID(webDescriptor), null,true); - if (authorizationManager != null) { - authorizationManager.release(); + if (webBundleDescriptor != null) { + if (remove) { + String contextId = getContextID(webBundleDescriptor); + WebAuthorizationManagerService webAuthorizationManagerService = webSecurityManagerFactory.getManager(contextId, true); + if (webAuthorizationManagerService != null) { + webAuthorizationManagerService.release(); + } } + webSecurityManagerFactory.createManager(webBundleDescriptor, true, serverContext); } - webSecurityManagerFactory.createManager(webDescriptor, true, serverContext); - } catch (Exception e) { - // log stacktrace and throw, because stacktrace of causes will be lost in DeploymentException - _logger.log(CONFIG, - "[Web-Security] FATAL Exception. Unable to create WebSecurityManager: " + e.getMessage(), e); + + } catch (Exception se) { throw new DeploymentException( - "Error in generating security policy for " + webDescriptor.getModuleDescriptor().getModuleName(), e); + "Error in generating security policy for " + webBundleDescriptor.getModuleDescriptor().getModuleName(), se); } } - - - // ### Private methods - - /** - * Puts Web Bundle Policy In Service, repeats translation is Descriptor indicate policy was changed by ContextListener. + * Puts Web Bundle Policy In Service, repeats translation if Descriptor indicates policy was changed by ContextListener. * * @param webBundleDescriptor * @throws DeploymentException @@ -291,20 +282,22 @@ private void commitWebPolicy(WebBundleDescriptor webBundleDescriptor) throws Dep try { if (webBundleDescriptor != null) { if (webBundleDescriptor.isPolicyModified()) { - // redo policy translation for web module - loadPolicy(webBundleDescriptor, true); + // Redo policy translation for web module + loadWebPolicy(webBundleDescriptor, true); } - String contextId = SecurityUtil.getContextID(webBundleDescriptor); - + String contextId = getContextID(webBundleDescriptor); websecurityProbeProvider.policyCreationStartedEvent(contextId); - SecurityUtil.generatePolicyFile(contextId); + + commitViaManager(contextId); + websecurityProbeProvider.policyCreationEndedEvent(contextId); websecurityProbeProvider.policyCreationEvent(contextId); + } } catch (Exception se) { - String msg = "Error in generating security policy for " + webBundleDescriptor.getModuleDescriptor().getModuleName(); - throw new DeploymentException(msg, se); + throw new DeploymentException( + "Error in generating security policy for " + webBundleDescriptor.getModuleDescriptor().getModuleName(), se); } } @@ -317,7 +310,7 @@ private void commitWebPolicy(WebBundleDescriptor webBundleDescriptor) throws Dep private void commitEjbPolicies(Application app) throws DeploymentException { try { for (EjbBundleDescriptor ejbBD : app.getBundleDescriptors(EjbBundleDescriptor.class)) { - String contextId = SecurityUtil.getContextID(ejbBD); + String contextId = getContextID(ejbBD); ejbProbeProvider.policyCreationStartedEvent(contextId); SecurityUtil.generatePolicyFile(contextId); @@ -336,28 +329,34 @@ private void commitEjbPolicies(Application app) throws DeploymentException { * @param app * @param webBundleDescriptors */ - private void linkPolicies(Application app, Collection webBundleDescriptors) throws DeploymentException { + private void linkPolicies(Application application, Collection webBundleDescriptors) throws DeploymentException { try { - - String linkName = null; + String linkedContextId = null; boolean lastInService = false; + for (WebBundleDescriptor webBundleDescriptor : webBundleDescriptors) { - String name = SecurityUtil.getContextID(webBundleDescriptor); - lastInService = SecurityUtil.linkPolicyFile(name, linkName, lastInService); - linkName = name; + String contextId = getContextID(webBundleDescriptor); + + WebAuthorizationManagerService webAuthorizationManagerService = webSecurityManagerFactory.getManager(contextId); + if (webAuthorizationManagerService != null) { + lastInService = WebAuthorizationManagerService.linkPolicy(contextId, linkedContextId, lastInService); + linkedContextId = contextId; + } } - linkName = null; // reset link name - Set ejbs = app.getBundleDescriptors(EjbBundleDescriptor.class); - for (EjbBundleDescriptor ejbd : ejbs) { - String name = SecurityUtil.getContextID(ejbd); - lastInService = SecurityUtil.linkPolicyFile(name, linkName, lastInService); - linkName = name; + Set ejbBundleDescriptors = application.getBundleDescriptors(EjbBundleDescriptor.class); + for (EjbBundleDescriptor ejbBundleDescriptor : ejbBundleDescriptors) { + String contextId = getContextID(ejbBundleDescriptor); + + WebAuthorizationManagerService manager = webSecurityManagerFactory.getManager(contextId); + if (manager != null) { + lastInService = WebAuthorizationManagerService.linkPolicy(contextId, linkedContextId, lastInService); + linkedContextId = contextId; + } } - // extra commit (see above) - } catch (IASSecurityException se) { - throw new DeploymentException( "Error in linking security policy for " + app.getRegistrationName(), se); + } catch (IllegalStateException se) { + throw new DeploymentException("Error in linking security policy for " + application.getRegistrationName(), se); } } @@ -392,6 +391,34 @@ private void removePolicy(DeploymentContext context) throws DeploymentException cleanSecurityContext(appName); } + boolean linkViaManager(String contextId, String linkedContextId, boolean lastInService) { + WebAuthorizationManagerService webAuthorizationManagerService = webSecurityManagerFactory.getManager(contextId); + if (webAuthorizationManagerService != null) { + return webAuthorizationManagerService.linkPolicy(linkedContextId, lastInService); + } + + return WebAuthorizationManagerService.linkPolicy(contextId, linkedContextId, lastInService); + + } + + void commitViaManager(String contextId) { + WebAuthorizationManagerService webAuthorizationManagerService = webSecurityManagerFactory.getManager(contextId); + if (webAuthorizationManagerService != null) { + webAuthorizationManagerService.commitPolicy(); + } else { + WebAuthorizationManagerService.commitPolicy(contextId); + } + } + + void deleteViaManager(String contextId) { + WebAuthorizationManagerService webAuthorizationManagerService = webSecurityManagerFactory.getManager(contextId); + if (webAuthorizationManagerService != null) { + webAuthorizationManagerService.deletePolicy(); + } else { + WebAuthorizationManagerService.deletePolicy(contextId); + } + } + /** * Clean security policy generated at deployment time. NOTE: This routine calls destroy on the WebSecurityManagers, but * that does not cause deletion of the underlying policy (files). The underlying policy is deleted when removePolicy (in @@ -455,6 +482,39 @@ private void handleCNonceCacheBSInit(String appName, Set we } } + private void deletePolicy(DeploymentContext deploymentContext) throws DeploymentException { + OpsParams params = deploymentContext.getCommandParameters(OpsParams.class); + if (!params.origin.needsCleanArtifacts()) { + return; + } + + String applicationName = params.name(); + + // Remove policy files only if managers are not destroyed by cleanup + try { + String[] contextIds = webSecurityManagerFactory.getContextsForApp(applicationName, false); + if (contextIds != null) { + for (String contextId : contextIds) { + if (contextId != null) { + websecurityProbeProvider.policyDestructionStartedEvent(contextId); + + deleteViaManager(contextId); + + websecurityProbeProvider.policyDestructionEndedEvent(contextId); + websecurityProbeProvider.policyDestructionEvent(contextId); + } + } + } + } catch (IllegalStateException ex) { + String msg = "Error in removing security policy for " + applicationName; + _logger.log(WARNING, msg, ex); + throw new DeploymentException(msg, ex); + } + + // Destroy the managers if present + cleanSecurityContext(applicationName); + } + private boolean isHaEnabled() { boolean haEnabled = false; // lazily init the required services instead of diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityUtil.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityUtil.java index b47497e2811..f3230232254 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityUtil.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityUtil.java @@ -63,7 +63,7 @@ import com.sun.logging.LogDomains; /** - * This utility class contains JACC related utilities. + * This utility class contains Jakarta Authorization related utilities. * *

* This is mostly used by the SecurityDeployer, but the getContextID method @@ -163,8 +163,7 @@ public static void removeRoleMapper(DeploymentContext dc) { return; } String appName = params.name(); - SecurityRoleMapperFactory factory = getRoleMapperFactory(); - factory.removeRoleMapper(appName); + getRoleMapperFactory().removeRoleMapper(appName); } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/AuthorizationUtil.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/AuthorizationUtil.java similarity index 72% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/AuthorizationUtil.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/AuthorizationUtil.java index d4ca4acfb27..3db2a30f7af 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/AuthorizationUtil.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/AuthorizationUtil.java @@ -14,29 +14,22 @@ * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.ee.web.integration; +package com.sun.enterprise.security.ee.authorization; import com.sun.enterprise.deployment.Application; import com.sun.enterprise.deployment.EjbBundleDescriptor; import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.security.util.IASSecurityException; import com.sun.enterprise.util.LocalStringManagerImpl; - import jakarta.security.jacc.PolicyConfiguration; import jakarta.security.jacc.PolicyConfigurationFactory; import jakarta.security.jacc.PolicyContextException; import jakarta.security.jacc.PolicyFactory; - import java.util.Collection; - -import org.glassfish.api.deployment.DeploymentContext; -import org.glassfish.api.deployment.OpsParams; -import org.glassfish.deployment.common.SecurityRoleMapperFactory; import org.glassfish.deployment.versioning.VersioningUtils; -import static org.glassfish.deployment.versioning.VersioningUtils.getRepositoryName; - /** * This utility class contains several methods for working with (Jakarta) Authorization. * @@ -55,36 +48,7 @@ public class AuthorizationUtil { // The repository is defined in PolicyFileMgr. // It is repeated here since JACC provider is not reference directly. public static final String repository = System.getProperty(REPOSITORY_HOME_PROP); - - public static String getContextID(EjbBundleDescriptor ejbBundleDesc) { - if (ejbBundleDesc == null) { - return null; - } - - // Detect special case of EJBs embedded in a war, and make sure pseudo policy context id is - // unique within application. - Object root = ejbBundleDesc.getModuleDescriptor().getDescriptor(); - if (root != ejbBundleDesc && root instanceof WebBundleDescriptor) { - return createUniquePseudoModuleID(ejbBundleDesc); - } - - return getRepositoryName( - ejbBundleDesc.getApplication().getRegistrationName()) + - '/' + - ejbBundleDesc.getUniqueFriendlyId(); - } - - public static String getContextID(WebBundleDescriptor webBundleDescriptor) { - if (webBundleDescriptor == null) { - return null; - } - - return getRepositoryName( - webBundleDescriptor.getApplication().getRegistrationName()) + - '/' + - webBundleDescriptor.getUniqueFriendlyId(); - } - + /** * Inform the policy module to take the named policy context out of service. The policy context is transitioned to the * deleted state. In our provider implementation, the corresponding policy file is deleted, as the presence of a policy @@ -118,26 +82,7 @@ public static void removePolicy(String contextId) throws IASSecurityException { throw new IASSecurityException(pce.toString()); } } - - public static SecurityRoleMapperFactory getRoleMapperFactory() { - SecurityRoleMapperFactory factory = SecurityRoleMapperFactoryGen.getSecurityRoleMapperFactory(); - if (factory == null) { - throw new IllegalArgumentException("This application has no role mapper factory defined"); - } - - return factory; - } - - public static void removeRoleMapper(DeploymentContext deploymentContext) { - OpsParams params = deploymentContext.getCommandParameters(OpsParams.class); - if (params.origin != OpsParams.Origin.undeploy) { - return; - } - - getRoleMapperFactory().removeRoleMapper(params.name()); - - } - + /** * create pseudo module context id, and make sure it is unique, by chacking it against the names of all the other * modules in the app. diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/EJBPolicyContextDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/EJBPolicyContextDelegate.java index 112fe280899..8c691b44e38 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/EJBPolicyContextDelegate.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/EJBPolicyContextDelegate.java @@ -46,8 +46,6 @@ import org.glassfish.ejb.api.EJBInvocation; import org.jvnet.hk2.annotations.Service; -import com.sun.enterprise.security.jacc.context.PolicyContextDelegate; - /** * This class is primarily a delegate for PolicyContextHandler related queries * But also handles Authorization of WebServiceInvocations diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/GlassFishToExousiaConverter.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/GlassFishToExousiaConverter.java similarity index 97% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/GlassFishToExousiaConverter.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/GlassFishToExousiaConverter.java index 4ad7eeef5ac..991371b3308 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/web/integration/GlassFishToExousiaConverter.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/GlassFishToExousiaConverter.java @@ -13,8 +13,8 @@ * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ - -package com.sun.enterprise.security.web.integration; +// Portions Copyright [2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authorization; import static jakarta.servlet.annotation.ServletSecurity.TransportGuarantee.CONFIDENTIAL; import static jakarta.servlet.annotation.ServletSecurity.TransportGuarantee.NONE; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextDelegate.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/PolicyContextDelegate.java similarity index 95% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextDelegate.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/PolicyContextDelegate.java index a4393bf6739..7dac3563f3e 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextDelegate.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/PolicyContextDelegate.java @@ -37,8 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jacc.context; +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authorization; import org.glassfish.api.invocation.ComponentInvocation; import org.jvnet.hk2.annotations.Contract; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/PolicyLoader.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/PolicyLoader.java new file mode 100644 index 00000000000..e4372b810a0 --- /dev/null +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/PolicyLoader.java @@ -0,0 +1,244 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +// Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authorization; + +import com.sun.enterprise.config.serverbeans.JaccProvider; +import com.sun.enterprise.config.serverbeans.SecurityService; +import com.sun.enterprise.security.SecurityLoggerInfo; +import com.sun.enterprise.util.i18n.StringManager; +import jakarta.inject.Inject; +import jakarta.inject.Named; +import jakarta.inject.Singleton; +import jakarta.security.jacc.Policy; +import jakarta.security.jacc.PolicyFactory; +import java.util.logging.Logger; +import org.glassfish.exousia.modules.def.DefaultPolicyFactory; +import org.glassfish.hk2.api.IterableProvider; +import org.jvnet.hk2.annotations.Service; +import org.jvnet.hk2.config.types.Property; + +import static com.sun.enterprise.security.SecurityLoggerInfo.*; +import static java.util.logging.Level.*; +import static org.glassfish.api.admin.ServerEnvironment.DEFAULT_INSTANCE_NAME; + +/** + * Loads the default JACC Policy Provider into the system. + * + * @author Harpreet Singh + * @author Jyri J. Virkki + */ +@Service +@Singleton +public class PolicyLoader { + + private static final Logger LOGGER = SecurityLoggerInfo.getLogger(); + private static StringManager SM = StringManager.getManager(PolicyLoader.class); + private static final StringManager STRING_MANAGER = StringManager.getManager(PolicyLoader.class); + + private static final String POLICY_PROVIDER = "jakarta.security.jacc.policy.provider"; + public static final String POLICY_CONF_FACTORY = "jakarta.security.jacc.PolicyConfigurationFactory.provider"; + private static final String POLICY_PROP_PREFIX = "com.sun.enterprise.jaccprovider.property."; + + @Inject + @Named(DEFAULT_INSTANCE_NAME) + private SecurityService securityService; + + @Inject + private IterableProvider authorizationModules; + + private boolean isPolicyInstalled; + + /** + * Attempts to install the policy-provider. The policy-provider element in domain.xml is consulted for the class to use. Note + * that if the jakarta.security.jacc.policy.provider system property is set it will override the domain.xml configuration. This + * will normally not be the case in S1AS. + * + */ + public void loadPolicy() { + if (isPolicyInstalled) { + LOGGER.fine("Policy already installed. Will not re-install."); + return; + } + + // Get configuration object for the JACC provider (which handles the policies) + JaccProvider authorizationModule = getConfiguredJakartaAuthorizationModule(); + + // Set config properties (see method comments) + setPolicyConfigurationFactory(authorizationModule); + + + // Get policy class name via the "normal" ways + String policyClassName = System.getProperty(POLICY_PROVIDER); + + if (policyClassName == null) { + LOGGER.log(WARNING, policyProviderConfigOverrideWarning, new String[]{POLICY_PROVIDER, policyClassName}); + } else if (authorizationModule != null) { + policyClassName = authorizationModule.getPolicyProvider(); + } + + // Set the role mapper + // TODO: replace with standard version + if (System.getProperty("simple.jacc.provider.JACCRoleMapper.class") == null) { + System.setProperty("simple.jacc.provider.JACCRoleMapper.class", + "com.sun.enterprise.security.ee.authorization.GlassfishRoleMapper"); + } + + // Now install the policy provider if one was identified + if (policyClassName != null) { + + try { + LOGGER.log(INFO, policyLoading, policyClassName); + + Policy policy = loadPolicy(policyClassName); + PolicyFactory.setPolicyFactory(new DefaultPolicyFactory()); // TMP!!! + PolicyFactory.getPolicyFactory().setPolicy(policy); + } catch (Exception e) { + LOGGER.log(SEVERE, policyInstallError, e.getLocalizedMessage()); + throw new RuntimeException(e); + } + + // Success. + LOGGER.fine("Policy set to: " + policyClassName); + isPolicyInstalled = true; + + } else { + // no value for policy provider found + LOGGER.warning(policyNotLoadingWarning); + } + } + + private Policy loadPolicy(String javaPolicyClassName) throws ReflectiveOperationException, SecurityException { + Object javaPolicyInstance = + Thread.currentThread() + .getContextClassLoader() + .loadClass(javaPolicyClassName) + .getDeclaredConstructor() + .newInstance(); + + if (!(javaPolicyInstance instanceof Policy)) { + throw new RuntimeException(SM.getString("enterprise.security.plcyload.not14")); + } + + return (Policy) javaPolicyInstance; + } + + /** + * Returns an authorization module object representing the jacc element from domain.xml which is configured in security-service. + * + * @return The config object or null on errors. + * + */ + private JaccProvider getConfiguredJakartaAuthorizationModule() { + JaccProvider authorizationModule = null; + try { + String name = securityService.getJacc(); + authorizationModule = getAuthorizationModuleByName(name); + if (authorizationModule == null) { + LOGGER.log(WARNING, policyNoSuchName, name); + } + } catch (Exception e) { + LOGGER.warning(SecurityLoggerInfo.policyReadingError); + authorizationModule = null; + } + + return authorizationModule; + } + + private JaccProvider getAuthorizationModuleByName(String authorizationModuleName) { + if (authorizationModules == null || authorizationModuleName == null) { + return null; + } + + for (JaccProvider authorizationModule : authorizationModules) { + if (authorizationModule.getName().equals(authorizationModuleName)) { + return authorizationModule; + } + } + + return null; + } + + + /** + * Set internal properties based on domain.xml configuration. + * + *

+ * The POLICY_CONF_FACTORY property is consumed by the jacc-api as documented in JACC specification. It's value is set + * here to the value given in domain.xml unless it is already set in which case the value is not modified. + * + *

+ * Then and properties associated with this jacc provider from domain.xml are set as internal properties prefixed with + * POLICY_PROP_PREFIX. This is currently a workaround for bug 4846938. A cleaner interface should be adopted. + * + */ + private void setPolicyConfigurationFactory(JaccProvider authorizationModule) { + if (authorizationModule == null) { + return; + } + + // Handle JACC-specified property for factory + // TODO:V3 system property being read here + String factoryProperty = System.getProperty(POLICY_CONF_FACTORY); + if (factoryProperty != null) { + // Warn user of override + LOGGER.log(WARNING, policyFactoryOverride, new String[] { POLICY_CONF_FACTORY, factoryProperty}); + + } else { + // Use domain.xml value by setting the property to it + String factoryFromConfig = authorizationModule.getPolicyConfigurationFactoryProvider(); + if (factoryFromConfig == null) { + LOGGER.log(WARNING, policyConfigFactoryNotDefined); + } else { + System.setProperty(POLICY_CONF_FACTORY, factoryFromConfig); + } + } + + // Next, make properties of this authorization module available to provider + for (Property authorizationProperty : authorizationModule.getProperty()) { + String name = POLICY_PROP_PREFIX + authorizationProperty.getName(); + String value = authorizationProperty.getValue(); + LOGGER.log(FINEST, () -> "PolicyLoader set [" + name + "] to [" + value + "]"); + + System.setProperty(name, value); + } + } + +} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java index 69c0711736d..2d063882807 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java @@ -42,14 +42,7 @@ package com.sun.enterprise.security.ee.authorization; -import com.sun.enterprise.config.serverbeans.ApplicationRef; -import com.sun.enterprise.config.serverbeans.Server; import com.sun.enterprise.deployment.WebBundleDescriptor; -import com.sun.enterprise.deployment.runtime.common.SecurityRoleMapping; -import com.sun.enterprise.deployment.runtime.common.wls.SecurityRoleAssignment; -import com.sun.enterprise.deployment.runtime.web.SunWebApp; -import com.sun.enterprise.deployment.web.LoginConfiguration; -import com.sun.enterprise.security.PolicyLoader; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityRoleMapperFactoryGen; import com.sun.enterprise.security.SecurityServicesUtil; @@ -58,18 +51,13 @@ import org.glassfish.security.common.UserNameAndPassword; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; -import com.sun.enterprise.security.jacc.JaccWebConstraintsTranslator; -import com.sun.enterprise.security.jacc.cache.CachedPermission; -import com.sun.enterprise.security.jacc.cache.CachedPermissionImpl; -import com.sun.enterprise.security.jacc.cache.PermissionCache; -import com.sun.enterprise.security.jacc.cache.PermissionCacheFactory; +import com.sun.enterprise.security.ee.authorization.cache.CachedPermission; +import com.sun.enterprise.security.ee.authorization.cache.CachedPermissionImpl; +import com.sun.enterprise.security.ee.authorization.cache.PermissionCache; +import com.sun.enterprise.security.ee.authorization.cache.PermissionCacheFactory; import com.sun.enterprise.security.web.integration.GlassFishPrincipalMapper; -import com.sun.enterprise.security.web.integration.GlassFishToExousiaConverter; import com.sun.enterprise.security.web.integration.WebPrincipal; -import com.sun.enterprise.security.ee.web.integration.WebSecurityManagerFactory; import com.sun.logging.LogDomains; -import fish.payara.jacc.JaccConfigurationFactory; -import jakarta.security.enterprise.CallerPrincipal; import jakarta.security.jacc.Policy; import jakarta.security.jacc.PolicyConfiguration; import jakarta.security.jacc.PolicyConfigurationFactory; @@ -77,43 +65,26 @@ import jakarta.security.jacc.PolicyContextException; import jakarta.security.jacc.PolicyFactory; import jakarta.security.jacc.WebResourcePermission; -import jakarta.security.jacc.WebRoleRefPermission; import jakarta.security.jacc.WebUserDataPermission; import jakarta.servlet.http.HttpServletRequest; -import org.glassfish.deployment.common.SecurityRoleMapperFactory; -import org.glassfish.exousia.AuthorizationService; -import org.glassfish.internal.api.ServerContext; -import org.glassfish.security.common.Group; - -import org.glassfish.security.common.Role; - -import javax.security.auth.Subject; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.AccessControlException; import java.security.CodeSource; import java.security.Permission; import java.security.Principal; -import java.security.PrivilegedActionException; import java.security.ProtectionDomain; -import java.security.cert.Certificate; -import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.logging.Level; import java.util.logging.Logger; -import java.util.stream.Collectors; +import javax.security.auth.Subject; +import org.glassfish.exousia.AuthorizationService; -import static com.sun.enterprise.security.common.AppservAccessController.privilegedException; +import static com.sun.enterprise.security.ee.authorization.GlassFishToExousiaConverter.getConstraintsFromBundle; +import static com.sun.enterprise.security.ee.authorization.GlassFishToExousiaConverter.getSecurityRoleRefsFromBundle; +import static com.sun.enterprise.security.ee.authorization.cache.PermissionCacheFactory.createPermissionCache; import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; -import static org.glassfish.api.web.Constants.ADMIN_VS; +import static java.util.stream.Collectors.toSet; /** * This class is the entry point for authorization decisions in the web container. It implements JACC, @@ -176,78 +147,65 @@ public class WebAuthorizationManagerService { // Unchecked permission cache used by the CachedPermissions defined above. private PermissionCache uncheckedPermissionCache; - private final WebSecurityManagerFactory webSecurityManagerFactory; - private final ServerContext serverContext; - - private final WebBundleDescriptor webBundleDescriptor; - // ProbeProvider private final WebSecurityDeployerProbeProvider probeProvider = new WebSecurityDeployerProbeProvider(); private boolean register = true; private final ThreadLocal currentRequest = new ThreadLocal<>(); private AuthorizationService authorizationService; - - public WebAuthorizationManagerService(WebBundleDescriptor webBundleDescriptor, ServerContext serverContext, WebSecurityManagerFactory webSecurityManagerFactory, boolean register) throws PolicyContextException { + + public WebAuthorizationManagerService(WebBundleDescriptor webBundleDescriptor, boolean register) throws PolicyContextException { this.register = register; - this.webBundleDescriptor = webBundleDescriptor; - this.CONTEXT_ID = getContextID(webBundleDescriptor); - this.serverContext = serverContext; - this.webSecurityManagerFactory = webSecurityManagerFactory; - - preprocessParams(webBundleDescriptor); + this.CONTEXT_ID = SecurityUtil.getContextID(webBundleDescriptor); - String appname = getAppId(); - SecurityRoleMapperFactory securityRoleMapperFactory = SecurityRoleMapperFactoryGen.getSecurityRoleMapperFactory(); - securityRoleMapperFactory.setAppNameForContext(getAppId(), CONTEXT_ID); - initialise(appname); + String appName = webBundleDescriptor.getApplication().getRegistrationName(); + SecurityRoleMapperFactoryGen.getSecurityRoleMapperFactory().setAppNameForContext(appName, CONTEXT_ID); - Collection roles = new ArrayList<>(); + initPermissionCache(); - while (securityRoleMapperFactory.getRoleMapper(getAppId()).getRoles().hasNext()){ - roles.add((String) securityRoleMapperFactory.getRoleMapper(getAppId()).getRoles().next()); - } - + webBundleDescriptor.getContextParametersSet() + .stream() + .filter(param -> param.getName().equals(PolicyConfigurationFactory.FACTORY_NAME)) + .findAny() + .map(param -> loadFactory(webBundleDescriptor, param.getValue())) + .ifPresent(clazz -> installPolicyConfigurationFactory(webBundleDescriptor, clazz)); + webBundleDescriptor.getContextParametersSet() + .stream() + .filter(param -> param.getName().equals(PolicyFactory.FACTORY_NAME)) + .findAny() + .map(param -> loadFactory(webBundleDescriptor, param.getValue())) + .ifPresent(clazz -> installPolicyFactory(webBundleDescriptor, clazz)); authorizationService = new AuthorizationService( CONTEXT_ID, () -> SecurityContext.getCurrent().getSubject(), - () -> new GlassFishPrincipalMapper(CONTEXT_ID) - ); + () -> new GlassFishPrincipalMapper(CONTEXT_ID)); + authorizationService.setConstrainedUriRequestAttribute(CONSTRAINT_URI); - authorizationService.setRequestSupplier(CONTEXT_ID, currentRequest::get); + authorizationService.setRequestSupplier(CONTEXT_ID, + () -> currentRequest.get()); + authorizationService.addConstraintsToPolicy( - GlassFishToExousiaConverter.getConstraintsFromBundle(webBundleDescriptor), + getConstraintsFromBundle(webBundleDescriptor), webBundleDescriptor.getRoles() .stream() .map(Role::getName) .collect(Collectors.toSet()), webBundleDescriptor.isDenyUncoveredHttpMethods(), - GlassFishToExousiaConverter.getSecurityRoleRefsFromBundle(webBundleDescriptor)); + getSecurityRoleRefsFromBundle(webBundleDescriptor)); } - public WebAuthorizationManagerService(WebBundleDescriptor webBundleDescriptor, boolean register) throws PolicyContextException { - this.CONTEXT_ID = getContextID(webBundleDescriptor); - this.webSecurityManagerFactory = null; - this.serverContext = null; - this.webBundleDescriptor = webBundleDescriptor; - } - - private void preprocessParams(WebBundleDescriptor webBundleDescriptor) { - //evaluate if the context param was set for the property jakarta.security.jacc.PolicyFactory.provider - //if this is true load class and assign as a custom configuration for the PolicyConfigurationFactory - webBundleDescriptor.getContextParametersSet().stream() - .filter(c -> c.getName().equals(PolicyLoader.POLICY_CONF_FACTORY)) - .findAny().map(p -> loadFactory(webBundleDescriptor, p.getValue())) - .ifPresent(cl -> installPolicyConfigurationFactory(webBundleDescriptor, cl)); - - // evaluate if the context param was set for the property jakarta.security.jacc.PolicyFactory.provider - //if this is true load class and assign as a custom policy for the - webBundleDescriptor.getContextParametersSet().stream() - .filter(c -> c.getName().equals(PolicyLoader.POLICY_FACTORY_PROVIDER)) - .findAny().map(p -> loadFactory(webBundleDescriptor, p.getValue())) - .ifPresent(cl -> installPolicyFactory(webBundleDescriptor, cl)); + private void initPermissionCache() { + if (uncheckedPermissionCache == null) { + if (register) { + uncheckedPermissionCache = createPermissionCache(CONTEXT_ID, protoPerms, null); + allResourcesCachedPermission = new CachedPermissionImpl(uncheckedPermissionCache, allResources); + allConnectionsCachedPermission = new CachedPermissionImpl(uncheckedPermissionCache, allConnections); + } + } else { + uncheckedPermissionCache.reset(); + } } private Class loadFactory(WebBundleDescriptor webBundleDescriptor, String factoryClassName) { @@ -303,7 +261,7 @@ public boolean hasNoConstrainedResources() { if (noConstrainedResources) { try { - setPolicyContext(CONTEXT_ID); + AuthorizationService.setThreadContextId(CONTEXT_ID); } catch (Throwable t) { throw new RuntimeException(t); } @@ -380,11 +338,39 @@ public int hasUserDataPermission(HttpServletRequest servletRequest, String uri, return result; } - public boolean isPermitAll(HttpServletRequest request) { - setSecurityInfo(request); - return authorizationService.checkWebResourcePermission(request, (Subject) null); + public boolean linkPolicy(String linkedContextId, boolean lastInService) { + return authorizationService.linkPolicy(linkedContextId, lastInService); + } + + public static boolean linkPolicy(String contextId, String linkedContextId, boolean lastInService) { + return AuthorizationService.linkPolicy(contextId, linkedContextId, lastInService); + } + + public void commitPolicy() { + authorizationService.commitPolicy(); + } + + public static void commitPolicy(String contextId) { + AuthorizationService.commitPolicy(contextId); + } + + public void refresh() { + authorizationService.refresh(); } + public void deletePolicy() { + authorizationService.deletePolicy(); + } + + public static void deletePolicy(String contextId) { + AuthorizationService.deletePolicy(contextId); + } + + public boolean permitAll(HttpServletRequest httpServletRequest) { + setSecurityInfo(httpServletRequest); + return authorizationService.checkWebResourcePermission(httpServletRequest, (Subject) null); + } + public void setSecurityInfo(HttpServletRequest httpRequest) { if (httpRequest != null) { currentRequest.set(httpRequest); @@ -393,6 +379,20 @@ public void setSecurityInfo(HttpServletRequest httpRequest) { AuthorizationService.setThreadContextId(CONTEXT_ID); } + public void onLogin(HttpServletRequest httpServletRequest) { + this.setSecurityInfo(httpServletRequest); + } + + public void onLogout() { + this.resetSecurityInfo(); + } + + public void resetSecurityInfo() { + currentRequest.remove(); + PolicyContext.setContextID(null); + } + + /** * Perform access control based on the HttpServletRequest. Return true if this constraint is * satisfied and processing should continue, or false otherwise. @@ -426,44 +426,19 @@ public boolean hasResourcePermission(HttpServletRequest servletRequest) { * @return true is the resource is granted, false if denied */ public boolean hasRoleRefPermission(String servletName, String role, Principal principal) { - WebRoleRefPermission requestedPermission = new WebRoleRefPermission(servletName, role); + boolean isGranted = authorizationService.checkWebRoleRefPermission( + servletName, + role, + getSecurityContext(principal).getSubject()); - Set principalSetFromSecurityContext = getSecurityContext(principal).getPrincipalSet(); - boolean isGranted = checkPermission(requestedPermission, principalSetFromSecurityContext); - if (!isGranted) { - isGranted = checkPermissionForModifiedPrincipalSet(principalSetFromSecurityContext, isGranted, requestedPermission); - } - - if (logger.isLoggable(Level.FINE)) { - logger.log(FINE, "[Web-Security] hasRoleRef perm: {0}", requestedPermission); + if (logger.isLoggable(FINE)) { + logger.log(FINE, "[Web-Security] hasRoleRef perm: {0}", servletName + " " + role); logger.log(FINE, "[Web-Security] hasRoleRef isGranted: {0}", isGranted); } return isGranted; } - /* If the principal set contains CallerPrincipal, replace it with UserPrincipal. - This is because CallerPrincipal isn't equal to UserPrincipal and doesn't imply it. - CallerPrincipal doesn't even implement equals method, so 2 CallerPrincipals with the same name are not equal. - Because CallerPrincipal is from Jakarta EE, we can't change it. - */ - private boolean checkPermissionForModifiedPrincipalSet(Set principalSetFromSecurityContext, boolean isGranted, WebRoleRefPermission requestedPermission) { - boolean principalSetContainsCallerPrincipal = false; - Set modifiedPrincipalSet = new HashSet(principalSetFromSecurityContext.size()); - for (Principal p : principalSetFromSecurityContext) { - if (p instanceof CallerPrincipal) { - principalSetContainsCallerPrincipal = true; - modifiedPrincipalSet.add(new UserNameAndPassword(p.getName())); - } else { - modifiedPrincipalSet.add(p); - } - } - if (principalSetContainsCallerPrincipal) { - isGranted = checkPermission(requestedPermission, modifiedPrincipalSet); - } - return isGranted; - } - /** * Analogous to destroy, except does not remove links from Policy Context, and does not remove context_id from role * mapper factory. Used to support Policy Changes that occur via ServletContextListener. @@ -471,283 +446,19 @@ private boolean checkPermissionForModifiedPrincipalSet(Set principalS * @throws PolicyContextException */ public void release() throws PolicyContextException { - logger.config(() -> "release(); id of the context: " + CONTEXT_ID); - boolean wasInService = getPolicyFactory().inService(CONTEXT_ID); - PolicyConfiguration config = getPolicyFactory().getPolicyConfiguration(CONTEXT_ID, false); - removePolicyStatements(config, webBundleDescriptor); - - // Refresh policy if the context was in service - if (wasInService) { - PolicyFactory.getPolicyFactory().getPolicy().refresh(); - } + authorizationService.removeStatementsFromPolicy(null); PermissionCacheFactory.removePermissionCache(uncheckedPermissionCache); uncheckedPermissionCache = null; - webSecurityManagerFactory.getManager(CONTEXT_ID, null, true); } public void destroy() throws PolicyContextException { - logger.config(() -> "destroy(); id of the context: " + CONTEXT_ID); - PolicyConfigurationFactory policyFactory = getPolicyFactory(); - - boolean wasInService = policyFactory.inService(CONTEXT_ID); - if (wasInService) { - policy.refresh(); - } + authorizationService.refresh(); + authorizationService.destroy(); PermissionCacheFactory.removePermissionCache(uncheckedPermissionCache); uncheckedPermissionCache = null; SecurityRoleMapperFactoryGen.getSecurityRoleMapperFactory().removeAppNameForContext(CONTEXT_ID); - - if (policyFactory instanceof JaccConfigurationFactory) { - ((JaccConfigurationFactory) policyFactory).removeContextProviderByPolicyContextId(CONTEXT_ID); - ((JaccConfigurationFactory) policyFactory).removeContextIdMappingByPolicyContextId(CONTEXT_ID); - } - - webSecurityManagerFactory.getManager(CONTEXT_ID, null, true); - } - - - /** - * Initialise this class and specifically load permissions into the JACC Policy Configuration. - * - * @param appName - * @throws PolicyContextException - */ - private void initialise(String appName) throws PolicyContextException { - logger.finest(() -> String.format("initialise(appName=%s)", appName)); - getPolicyFactory(); - CODEBASE = removeSpaces(CONTEXT_ID); - - if (ADMIN_VS.equals(getVirtualServers(appName))) { - LoginConfiguration loginConfiguration = webBundleDescriptor.getLoginConfiguration(); - if (loginConfiguration != null) { - String realmName = loginConfiguration.getRealmName(); - - // Process mappings from sun-web.xml - SunWebApp sunDes = webBundleDescriptor.getSunDescriptor(); - if (sunDes != null) { - - SecurityRoleMapping[] roleMappings = sunDes.getSecurityRoleMapping(); - if (roleMappings != null) { - for (SecurityRoleMapping roleMapping : roleMappings) { - for (String principal : roleMapping.getPrincipalName()) { - webSecurityManagerFactory.addAdminPrincipal(principal, realmName, new UserNameAndPassword(principal)); - } - for (String group : roleMapping.getGroupNames()) { - webSecurityManagerFactory.addAdminGroup(group, realmName, new Group(group)); - } - } - } - - SecurityRoleAssignment[] roleAssignments = sunDes.getSecurityRoleAssignments(); - if (roleAssignments != null) { - for (SecurityRoleAssignment roleAssignment : roleAssignments) { - if (roleAssignment.isExternallyDefined()) { - webSecurityManagerFactory.addAdminGroup(roleAssignment.getRoleName(), realmName, new Group(roleAssignment.getRoleName())); - continue; - } - - for (String principal : roleAssignment.getPrincipalNames()) { - webSecurityManagerFactory.addAdminPrincipal(principal, realmName, new UserNameAndPassword(principal)); - } - } - } - } - } - } - - // Will require stuff in hash format for reference later on. - try { - try { - logger.log(FINE, "[Web-Security] Creating a Codebase URI with = {0}", CODEBASE); - - URI uri = new URI("file:///" + CODEBASE); - if (uri != null) { - codesource = new CodeSource(new URL(uri.toString()), (Certificate[]) null); - } - - } catch (URISyntaxException use) { - // Manually create the URL - logger.log(FINE, "[Web-Security] Error Creating URI ", use); - throw new RuntimeException(use); - } - - } catch (MalformedURLException mue) { - logger.log(SEVERE, "[Web-Security] Exception while getting the CodeSource", mue); - throw new RuntimeException(mue); - } - - logger.log(FINE, "[Web-Security] Context id (id under which WEB component in application will be created) = {0}", CONTEXT_ID); - logger.log(FINE, "[Web-Security] Codebase (module id for web component) {0}", CODEBASE); - - // Generate permissions and store these into the JACC policyConfiguration - // The JACC Policy (to which we delegate) will use these permissions later to make authorization decisions. - loadPermissionsInToPolicyConfiguration(); - - if (uncheckedPermissionCache == null) { - if (register) { - uncheckedPermissionCache = PermissionCacheFactory.createPermissionCache(CONTEXT_ID, codesource, protoPerms, null); - - allResourcesCachedPermission = new CachedPermissionImpl(uncheckedPermissionCache, allResources); - allConnectionsCachedPermission = new CachedPermissionImpl(uncheckedPermissionCache, allConnections); - } - } else { - uncheckedPermissionCache.reset(); - } - } - - private void loadPermissionsInToPolicyConfiguration() throws PolicyContextException { - PolicyConfigurationFactory policyFactory = getPolicyFactory(); - - // Only regenerate policy file if it isn't already in service. - // - // Consequently all things that deploy modules (as opposed to loading already deployed modules) - // must make sure a pre-exiting PolicyConfiguration is either in deleted or open state before - // this method (i.e. initialize) is called. That is, before constructing the WebSecurityManager. - // - // Note that policy statements are not removed to allow multiple web modules to be represented by - // the same PolicyConfiguration. - - if (!policyFactory.inService(CONTEXT_ID)) { - - // Get the JACC PolicyConfiguration. If we are a single web application (with only one web module) - // this will be still empty, otherwise it may already contain permissions. - // - // Note that the PolicyConfiguration is pluggable and can have been replaced by the user - policyConfiguration = policyFactory.getPolicyConfiguration(CONTEXT_ID, false); - try { - - // Translate the constraints in the webBundleDescriptor into permissions that will be stored - // in the policyConfiguration. - JaccWebConstraintsTranslator.translateConstraintsToPermissions(webBundleDescriptor, policyConfiguration); - } catch (PolicyContextException pce) { - logger.log(FINE, "[Web-Security] FATAL Permission Translation: " + pce.getMessage()); - throw pce; - } - } - - } - - private String removeSpaces(String withSpaces) { - return withSpaces.replace(' ', '_'); - } - - - - // #### Other private methods - - // this will change too - get the application id name - private String getAppId() { - return webBundleDescriptor.getApplication().getRegistrationName(); - } - - /** - * Invoke the Policy to determine if the Permission object has security permission. - * - * @param requestedPermission an instance of Permission. - * @param principalSet a set containing the principals to check for authorization - * - * @return true if granted, false if denied. - */ - private boolean checkPermission(Permission requestedPermission, Set principalSet) { - boolean hasPermission = false; - - if (uncheckedPermissionCache != null) { - hasPermission = uncheckedPermissionCache.checkPermission(requestedPermission); - } - - if (hasPermission == false) { - hasPermission = checkPermissionWithoutCache(requestedPermission, principalSet); - } else { - try { - setPolicyContext(CONTEXT_ID); - } catch (Throwable t) { - if (logger.isLoggable(FINE)) { - logger.log(FINE, "[Web-Security] Web Permission Access Denied.", t); - } - hasPermission = false; - } - } - - return hasPermission; - } - - private boolean checkPermissionWithoutCache(Permission requestedPermission, Set principals) { - try { - // NOTE: there is an assumption here, that this setting of the Policy Context will - // remain in affect through the component dispatch, and that the/ component will not - // call into any other policy contexts. - // - // Even so, could likely reset on failed check. - setPolicyContext(CONTEXT_ID); - - } catch (Throwable t) { - if (logger.isLoggable(FINE)) { - logger.log(FINE, "[Web-Security] Web Permission Access Denied.", t); - } - return false; - } - - if (logger.isLoggable(FINE)) { - logger.log(FINE, "[Web-Security] Codesource with Web URL: {0}", codesource.getLocation().toString()); - logger.log(FINE, "[Web-Security] Checking Web Permission with Principals : {0}", principalSetToString(principals)); - logger.log(FINE, "[Web-Security] Web Permission = {0}", requestedPermission.toString()); - } - - // Check whether the requested permission is granted to any of the given principals - return principals == null ? policy.implies(requestedPermission) : policy.implies(requestedPermission, principals); - } - - private PolicyConfigurationFactory getPolicyFactory() throws PolicyContextException { - if (policyConfigurationFactory != null) { - return policyConfigurationFactory; - } - - return _getPolicyFactory(); - } - - private synchronized PolicyConfigurationFactory _getPolicyFactory() throws PolicyContextException { - if (policyConfigurationFactory == null) { - try { - policyConfigurationFactory = PolicyConfigurationFactory.getPolicyConfigurationFactory(); - } catch (ClassNotFoundException cnfe) { - logger.severe("WebSecurityManager - Exception while getting the PolicyFactory"); - throw new PolicyContextException(cnfe); - } catch (PolicyContextException pce) { - logger.severe("WebSecurityManager - Exception while getting the PolicyFactory"); - throw pce; - } - } - - return policyConfigurationFactory; - } - - private static String setPolicyContext(String newContextID) throws Throwable { - String oldContextID = PolicyContext.getContextID(); - - if (oldContextID != newContextID && (oldContextID == null || newContextID == null || !oldContextID.equals(newContextID))) { - - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "[Web-Security] Setting Policy Context ID: old = {0} ctxID = {1}", new Object[] { oldContextID, newContextID }); - } - - try { - privilegedException(() -> PolicyContext.setContextID(newContextID)); - } catch (PrivilegedActionException pae) { - Throwable cause = pae.getCause(); - if (cause instanceof AccessControlException) { - logger.log(SEVERE, "[Web-Security] setPolicy SecurityPermission required to call PolicyContext.setContextID", cause); - } else { - logger.log(SEVERE, "[Web-Security] Unexpected Exception while setting policy context", cause); - } - throw cause; - } - } else { - logger.log(FINE, "[Web-Security] Policy Context ID was: {0}", oldContextID); - } - - return oldContextID; } /** @@ -775,17 +486,6 @@ private SecurityContext getSecurityContext(Principal principal) { return securityContext; } - /** - * This is an private method for policy context handler data info - * - * @param httpRequest - */ - private void setServletRequestForJACC(HttpServletRequest httpRequest) { - if (httpRequest != null) { - webSecurityManagerFactory.pcHandlerImpl.getHandlerData().setHttpServletRequest(httpRequest); - } - } - private void recordWebInvocation(HttpServletRequest servletRequest, String type, boolean isGranted) { AuditManager auditManager = SecurityServicesUtil.getInstance().getAuditManager(); @@ -797,78 +497,7 @@ private void recordWebInvocation(HttpServletRequest servletRequest, String type, appServerAuditManager.webInvocation(user, servletRequest, type, isGranted); } } - - /** - * Remove All Policy Statements from Configuration config must be in open state when this method is called - * - * @param policyConfiguration - * @param webBundleDescriptor - * @throws PolicyContextException - */ - private void removePolicyStatements(PolicyConfiguration policyConfiguration, WebBundleDescriptor webBundleDescriptor) throws PolicyContextException { - policyConfiguration.removeUncheckedPolicy(); - policyConfiguration.removeExcludedPolicy(); - - // Iteration done for old providers - for (Role role : webBundleDescriptor.getRoles()) { - policyConfiguration.removeRole(role.getName()); - } - - // 1st call will remove "*" role if present. 2nd will remove all roles (if supported). - policyConfiguration.removeRole("*"); - policyConfiguration.removeRole("*"); - } - - private String principalSetToString(Set principalSet) { - StringBuilder principalStringBuilder = null; - - if (principalSet != null) { - Principal[] principals = principalSet.toArray(new Principal[0]); - for (int i = 0; i < principals.length; i++) { - if (i == 0) { - principalStringBuilder = new StringBuilder(principals[i].toString()); - } else { - principalStringBuilder.append(", ").append(principals[i].toString()); - } - } - } - - return principalStringBuilder != null ? principalStringBuilder.toString() : null; - } - - /** - * Virtual servers are maintained in the reference contained in Server element. First, we need to find the server and - * then get the virtual server from the correct reference - * - * @param applicationName Name of the application for which to get the virtual servers - * - * @return virtual servers as a string (separated by space or comma) - */ - private String getVirtualServers(String applicationName) { - Server server = serverContext.getDefaultServices().getService(Server.class); - for (ApplicationRef applicationRef : server.getApplicationRef()) { - if (applicationRef.getRef().equals(applicationName)) { - return applicationRef.getVirtualServers(); - } - } - - return null; - } - - private void logProtectionDomainCreated(Principal[] principals) { - if (logger.isLoggable(FINE)) { - logger.log(FINE, "[Web-Security] Generating a protection domain for Permission check."); - - if (principals != null) { - for (Principal principal : principals) { - logger.log(FINE, "[Web-Security] Checking with Principal : {0}", principal.toString()); - } - } else { - logger.log(FINE, "[Web-Security] Checking with Principals: null"); - } - } - } - + private static String getUriMinusContextPath(HttpServletRequest request) { String uri = request.getRequestURI(); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/CachedPermission.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/CachedPermission.java similarity index 95% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/CachedPermission.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/CachedPermission.java index a08ff2fb224..b6c0b7b8133 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/CachedPermission.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/CachedPermission.java @@ -37,8 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jacc.cache; +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authorization.cache; import java.security.Permission; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/CachedPermissionImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/CachedPermissionImpl.java similarity index 96% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/CachedPermissionImpl.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/CachedPermissionImpl.java index 0dc1a7be55d..4dd6fcc5f1b 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/CachedPermissionImpl.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/CachedPermissionImpl.java @@ -37,8 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jacc.cache; +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] +package com.sun.enterprise.security.ee.authorization.cache; import java.security.Permission; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/PermissionCache.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCache.java similarity index 93% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/PermissionCache.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCache.java index 1d4d2339f9f..50f655fc1fb 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/PermissionCache.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCache.java @@ -38,7 +38,7 @@ * holder. */ // Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jacc.cache; +package com.sun.enterprise.security.ee.authorization.cache; import static java.util.Collections.list; import static java.util.logging.Level.SEVERE; @@ -59,7 +59,6 @@ import jakarta.security.jacc.PolicyContext; import com.sun.enterprise.security.common.AppservAccessController; -import com.sun.enterprise.security.jacc.cache.CachedPermissionImpl.Epoch; import com.sun.logging.LogDomains; import jakarta.security.jacc.PolicyFactory; @@ -75,7 +74,6 @@ public class PermissionCache extends Object { private static AllPermission allPermission = new AllPermission(); private Permissions cache; - private CodeSource codesource; private Permission[] protoPerms; private Class[] classes; private String name; @@ -105,12 +103,7 @@ public class PermissionCache extends Object { * value matches the name parameter will be included in the cache. This value may be null, in which case permission name * does not factor into the permission caching. */ - public PermissionCache(Integer key, String pcID, CodeSource codesource, Permission[] perms, String name) { - if (codesource == null) { - this.codesource = new CodeSource(null, (java.security.cert.Certificate[]) null); - } else { - this.codesource = codesource; - } + public PermissionCache(Integer key, String pcID, Permission[] perms, String name) { this.factoryKey = key; this.cache = null; this.pcID = pcID; @@ -150,12 +143,7 @@ public PermissionCache(Integer key, String pcID, CodeSource codesource, Permissi * value matches the name parameter will be included in the cache. This value may be null, in which case permission name * does not factor into the permission caching. */ - public PermissionCache(Integer key, String pcID, CodeSource codesource, Class clazz, String name) { - if (codesource == null) { - this.codesource = new CodeSource(null, (java.security.cert.Certificate[]) null); - } else { - this.codesource = codesource; - } + public PermissionCache(Integer key, String pcID, Class clazz, String name) { this.factoryKey = key; this.cache = null; this.pcID = pcID; @@ -177,7 +165,7 @@ public Integer getFactoryKey() { return factoryKey; } - private boolean checkLoadedCache(Permission permission, Epoch e) { + private boolean checkLoadedCache(Permission permission, CachedPermissionImpl.Epoch e) { if (e == null) { return cache.implies(permission); } @@ -190,7 +178,7 @@ private boolean checkLoadedCache(Permission permission, Epoch e) { return e.granted; } - private boolean checkCache(Permission permissionToCheck, Epoch epoch) { + private boolean checkCache(Permission permissionToCheck, CachedPermissionImpl.Epoch epoch) { // Test-and-set to guard critical section rLock.lock(); @@ -324,7 +312,7 @@ private boolean checkCache(Permission permissionToCheck, Epoch epoch) { } } - boolean checkPermission(Permission permission, Epoch e) { + boolean checkPermission(Permission permission, CachedPermissionImpl.Epoch e) { return checkCache(permission, e); } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/PermissionCacheFactory.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCacheFactory.java similarity index 91% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/PermissionCacheFactory.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCacheFactory.java index b3fc151195c..842a79234a7 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/PermissionCacheFactory.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCacheFactory.java @@ -38,7 +38,7 @@ * holder. */ // Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jacc.cache; +package com.sun.enterprise.security.ee.authorization.cache; import java.net.SocketPermission; import java.security.CodeSource; @@ -48,7 +48,6 @@ import java.util.Iterator; import java.util.PropertyPermission; -import com.sun.enterprise.security.ee.J2EESecurityManager; import jakarta.security.jacc.PolicyFactory; /** @@ -95,7 +94,7 @@ private static Integer getNextKey() { } private static synchronized PermissionCache createSecurityManagerCache() { - return registerPermissionCache(new PermissionCache(getNextKey(), null, null, protoPerms, null)); + return registerPermissionCache(new PermissionCache(getNextKey(), null, protoPerms, null)); } /** @@ -110,14 +109,14 @@ private static synchronized PermissionCache createSecurityManagerCache() { * value matches the name parameter will be included in the cache. This value may be null, in which case permission name * dos not factor into the permission caching. */ - public static synchronized PermissionCache createPermissionCache(String pcID, CodeSource codesource, Permission[] perms, String name) { + public static synchronized PermissionCache createPermissionCache(String pcID, Permission[] perms, String name) { if (!supportsReuse) { return null; } Integer key = getNextKey(); - PermissionCache cache = new PermissionCache(key, pcID, codesource, perms, name); + PermissionCache cache = new PermissionCache(key, pcID, perms, name); return registerPermissionCache(cache); } @@ -134,14 +133,14 @@ public static synchronized PermissionCache createPermissionCache(String pcID, Co * value matches the name parameter will be included in the cache. This value may be null, in which case permission name * dos not factor into the permission caching. */ - public static synchronized PermissionCache createPermissionCache(String pcID, CodeSource codesource, Class clazz, String name) { + public static synchronized PermissionCache createPermissionCache(String pcID, Class clazz, String name) { if (!supportsReuse) { return null; } - return registerPermissionCache(new PermissionCache(getNextKey(), pcID, codesource, clazz, name)); + return registerPermissionCache(new PermissionCache(getNextKey(), pcID, clazz, name)); } - + /** * Register a PermissionCache object with the factory. If an object is already registered at the key, it will be * overidden. @@ -177,13 +176,6 @@ public static synchronized PermissionCache removePermissionCache(PermissionCache public static synchronized void resetCaches() { supportsReuse = true; - SecurityManager sm = System.getSecurityManager(); - if (sm != null && sm instanceof J2EESecurityManager) { - if (!((J2EESecurityManager) sm).cacheEnabled()) { - ((J2EESecurityManager) sm).enablePermissionCache(securityManagerCache); - } - } - Iterator iter = cacheMap.values().iterator(); while (iter.hasNext()) { Object cache = iter.next(); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/package-info.java similarity index 94% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/package-info.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/package-info.java index 21c28cf3f9d..640d1e3ef5e 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/cache/package-info.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/package-info.java @@ -1,7 +1,7 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * - * Copyright (c) [2017-2018] Payara Foundation and/or its affiliates. + * Copyright (c) [2017-2024] Payara Foundation and/or its affiliates. * All rights reserved. * * The contents of this file are subject to the terms of either the GNU @@ -46,4 +46,4 @@ * permissions. * */ -package com.sun.enterprise.security.jacc.cache; \ No newline at end of file +package com.sun.enterprise.security.ee.authorization.cache; \ No newline at end of file diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManager.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManager.java index 45e07121e48..2975596a98c 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManager.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManager.java @@ -27,9 +27,9 @@ import com.sun.enterprise.deployment.web.LoginConfiguration; +import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; import jakarta.security.jacc.PolicyContextException; -import jakarta.servlet.http.HttpServletRequest; import java.util.List; @@ -65,7 +65,7 @@ public class WebSecurityManager { this.authorizationService = new WebAuthorizationManagerService(webBundleDescriptor, register); this.webSecurityManagerFactory = webSecurityManagerFactory; - this.contextId = AuthorizationUtil.getContextID(webBundleDescriptor); + this.contextId = SecurityUtil.getContextID(webBundleDescriptor); if (ADMIN_VS.equals(getVirtualServers(webBundleDescriptor, serverContext))) { handleAdminVirtualServer(webBundleDescriptor, webSecurityManagerFactory); @@ -83,15 +83,7 @@ public class WebSecurityManager { public WebAuthorizationManagerService getAuthorizationService() { return authorizationService; } - - public void onLogin(HttpServletRequest httpServletRequest) { - authorizationService.setSecurityInfo(httpServletRequest); - } - - public void onLogout() { - //authorizationService.resetSecurityInfo(); - } - + /** * Analogous to destroy, except does not remove links from Policy Context, and does not remove context_id from role mapper * factory. Used to support Policy Changes that occur via ServletContextListener. diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java index 99225be7920..af616db7906 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/web/integration/WebSecurityManagerFactory.java @@ -42,9 +42,8 @@ import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.security.WebSecurityDeployerProbeProvider; +import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.factory.SecurityManagerFactory; -import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; -import com.sun.enterprise.security.jacc.context.PolicyContextRegistration; import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; import java.security.Principal; @@ -80,22 +79,12 @@ public class WebSecurityManagerFactory extends SecurityManagerFactory { private final Map adminPrincipals = new ConcurrentHashMap<>(); private final Map adminGroups = new ConcurrentHashMap<>(); - public final PolicyContextHandlerImpl pcHandlerImpl = (PolicyContextHandlerImpl) PolicyContextHandlerImpl.getInstance(); - - public final Map adminPrincipalsPerApp = new ConcurrentHashMap<>(); - public final Map adminGroupsPerApp = new ConcurrentHashMap<>(); - // Stores the Context IDs to application names for standalone web applications private final Map> CONTEXT_IDS = new HashMap<>(); private final Map> SECURITY_MANAGERS = new HashMap<>(); - public WebSecurityManagerFactory() { - // Registers the JACC policy handlers, which provide objects JACC Providers and other code can use - PolicyContextRegistration.registerPolicyHandlers(); - } - public WebAuthorizationManagerService createManager(WebBundleDescriptor webBundleDescriptor, boolean register, ServerContext context) { - String contextId = AuthorizationUtil.getContextID(webBundleDescriptor); + String contextId = SecurityUtil.getContextID(webBundleDescriptor); WebAuthorizationManagerService manager = null; if (register) { @@ -109,7 +98,7 @@ public WebAuthorizationManagerService createManager(WebBundleDescriptor webBundl // As "side-effect" of constructing the manager, the web constraints in the web bundle // descriptor will be translated to permissions and loaded into a JACC policy configuration - manager = new WebAuthorizationManagerService(webBundleDescriptor, context, this, register); + manager = new WebAuthorizationManagerService(webBundleDescriptor, register); probeProvider.securityManagerCreationEndedEvent(webBundleDescriptor.getModuleID()); @@ -172,13 +161,5 @@ public void putAdminGroup(String group, String realmName, Group principal) { // FIXME: can be hacked: "ab+cd" = "a+bcd" adminGroups.put(realmName + group, principal); } - - public void addAdminPrincipal(String username, String realmName, Principal principal) { - adminPrincipalsPerApp.put(realmName + username, principal); - } - - public void addAdminGroup(String group, String realmName, Principal principal) { - adminGroupsPerApp.put(realmName + group, principal); - } - + } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccEJBConstraintsTranslator.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccEJBConstraintsTranslator.java deleted file mode 100644 index c4314a04a80..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccEJBConstraintsTranslator.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright 2019-2024 Payara Foundation and/or its affiliates -package com.sun.enterprise.security.jacc; - -import static com.sun.logging.LogDomains.SECURITY_LOGGER; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; - -import java.lang.reflect.Method; -import java.security.Permissions; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.logging.Level; -import java.util.logging.Logger; - -import jakarta.security.jacc.EJBMethodPermission; -import jakarta.security.jacc.EJBRoleRefPermission; -import jakarta.security.jacc.PolicyConfiguration; -import jakarta.security.jacc.PolicyContextException; - -import org.glassfish.security.common.Role; - -import com.sun.enterprise.deployment.EjbDescriptor; -import com.sun.enterprise.deployment.MethodDescriptor; -import com.sun.enterprise.deployment.MethodPermission; -import com.sun.enterprise.deployment.RoleReference; - -/** - * This class is used for translating security constrains from ejb-jar.xml and corresponding - * annotations into JACC permissions, and writing this to the pluggable {@link PolicyConfiguration} (which is - * EE standard permission repository). - * - * @author Harpreet Singh, monzillo - * @author Arjan Tijms (refactoring) - * - */ -public class JaccEJBConstraintsTranslator { - - private static final Logger _logger = Logger.getLogger(SECURITY_LOGGER); - - private JaccEJBConstraintsTranslator() { - - } - - /** - * Translate the security constraints presents in the given EjbDescriptor to JACC permissions - * and store those in the given PolicyConfiguration. - * - * @param ejbDescriptor the source of the security constraints - * @param policyConfiguration the target of the security permissions - * @throws PolicyContextException - */ - public static void translateConstraintsToPermissions(EjbDescriptor ejbDescriptor, PolicyConfiguration policyConfiguration) throws PolicyContextException { - createEJBMethodPermissions(ejbDescriptor, policyConfiguration); - createEJBRoleRefPermissions(ejbDescriptor, policyConfiguration); - } - - /** - * This method converts the dd in two phases. Phase 1: gets a map representing the methodPermission elements exactly as - * they occured for the ejb in the dd. The map is keyed by method-permission element and each method-permission is - * mapped to a list of method elements representing the method elements of the method permision element. Each method - * element is converted to a corresponding EJBMethodPermission and added, based on its associated method-permission, to - * the policy configuration object. phase 2: configures additional EJBMethodPermission policy statements for the purpose - * of optimizing Permissions.implies matching by the policy provider. This phase also configures unchecked policy - * statements for any uncovered methods. This method gets the list of method descriptors for the ejb from the - * EjbDescriptor object. For each method descriptor, it will get a list of MethodPermission objects that signify the - * method permissions for the Method and convert each to a corresponding EJBMethodPermission to be added to the policy - * configuration object. - * - * @param ejbDescriptor the ejb descriptor for this EJB. - * @param policyConfiguration, the policy configuration - */ - private static void createEJBMethodPermissions(EjbDescriptor ejbDescriptor, PolicyConfiguration policyConfiguration) throws PolicyContextException { - String ejbName = ejbDescriptor.getName(); - - Permissions uncheckedPermissions = null; - Permissions excludedPermissions = null; - Map perRolePermissions = null; - - - // Phase 1 - - Map> methodPermissions = ejbDescriptor.getMethodPermissionsFromDD(); - - for (Entry> permissionEntry : methodPermissions.entrySet()) { - MethodPermission methodPermission = permissionEntry.getKey(); - - for (MethodDescriptor methodDescriptor : permissionEntry.getValue()) { - String methodName = methodDescriptor.getName().equals("*") ? null : methodDescriptor.getName(); - String methodInterface = methodDescriptor.getEjbClassSymbol(); - String methodParams[] = methodDescriptor.getStyle() == 3 ? methodDescriptor.getParameterClassNames() : null; - - EJBMethodPermission ejbMethodPermission = new EJBMethodPermission(ejbName, methodName, methodInterface, methodParams); - - perRolePermissions = addToRolePermissions(perRolePermissions, methodPermission, ejbMethodPermission); - uncheckedPermissions = addToUncheckedPermissions(uncheckedPermissions, methodPermission, ejbMethodPermission); - excludedPermissions = addToExcludedPermissions(excludedPermissions, methodPermission, ejbMethodPermission); - } - } - - // Phase 2 - configures additional permissions: - // * To optimize performance of Permissions.implies - // * To cause any uncovered methods to be unchecked - - for (MethodDescriptor methodDescriptor : ejbDescriptor.getMethodDescriptors()) { - Method method = methodDescriptor.getMethod(ejbDescriptor); - if (method == null) { - continue; - } - - String methodInterface = methodDescriptor.getEjbClassSymbol(); - if (methodInterface == null || methodInterface.equals("")) { - _logger.log(SEVERE, "method_descriptor_not_defined", - new Object[] { ejbName, methodDescriptor.getName(), methodDescriptor.getParameterClassNames() }); - - continue; - } - - EJBMethodPermission ejbMethodPermission = new EJBMethodPermission(ejbName, methodInterface, method); - - for (MethodPermission methodPermission : ejbDescriptor.getMethodPermissionsFor(methodDescriptor)) { - perRolePermissions = addToRolePermissions(perRolePermissions, methodPermission, ejbMethodPermission); - uncheckedPermissions = addToUncheckedPermissions(uncheckedPermissions, methodPermission, ejbMethodPermission); - excludedPermissions = addToExcludedPermissions(excludedPermissions, methodPermission, ejbMethodPermission); - } - } - - if (uncheckedPermissions != null) { - policyConfiguration.addToUncheckedPolicy(uncheckedPermissions); - } - - if (excludedPermissions != null) { - policyConfiguration.addToExcludedPolicy(excludedPermissions); - } - - if (perRolePermissions != null) { - for (Entry entry : perRolePermissions.entrySet()) { - policyConfiguration.addToRole(entry.getKey(), entry.getValue()); - } - } - } - - /** - * This method converts ejb role references to jacc permission objects and adds them to the policy configuration object - * It gets the list of role references from the ejb descriptor. For each such role reference, create a - * EJBRoleRefPermission and add it to the PolicyConfiguration object. - * - * @param ejbDescriptor the ejb descriptor - * @param pcid, the policy context identifier - */ - private static void createEJBRoleRefPermissions(EjbDescriptor ejbDescriptor, PolicyConfiguration policyConfiguration) throws PolicyContextException { - - List ejbScopedRoleNames = new ArrayList(); - Collection allRoles = ejbDescriptor.getEjbBundleDescriptor().getRoles(); - - Role anyAuthUserRole = new Role("**"); - boolean rolesetContainsAnyAuthUserRole = allRoles.contains(anyAuthUserRole); - - // Name of EJB being processed in this call - String ejbName = ejbDescriptor.getName(); - - writeOutPermissionsForRoleRefRoles(ejbDescriptor.getRoleReferences(), ejbScopedRoleNames, ejbName, policyConfiguration); - - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, - "JACC: Converting role-ref: Going through the list of roles not present in RoleRef elements and creating EJBRoleRefPermissions "); - } - - // For every role in the application for which there is no mapping (role reference) defined for this EJB - // we insert a 1:1 role mapping. E.g global role "foo" maps to an identical named role "foo" in the scope of EJB - // "MyEJB" - // - // Note this is the most common situation as mapping roles per EJB is quite rare in practice - writeOutPermissionsForNonRoleRefRoles(allRoles, ejbScopedRoleNames, ejbName, policyConfiguration); - - /** - * JACC MR8 add EJBRoleRefPermission for the any authenticated user role '**' - */ - if ((!ejbScopedRoleNames.contains(anyAuthUserRole)) && !rolesetContainsAnyAuthUserRole) { - addAnyAuthenticatedUserRoleRef(policyConfiguration, ejbName); - } - } - - private static void writeOutPermissionsForRoleRefRoles(Collection roleReferences, List ejbScopedRoleNames, String ejbName, PolicyConfiguration policyConfiguration) throws PolicyContextException { - for (RoleReference roleReference : roleReferences) { - - // The name of a role, local (scoped) to a single EJB - String ejbScopedRoleName = roleReference.getRoleName(); - ejbScopedRoleNames.add(new Role(ejbScopedRoleName)); - - // The name of the global role to which the local EJB scoped role links (is mapped) - String globalRoleName = roleReference.getSecurityRoleLink().getName(); - - // Write the role reference to the target policy configuration - policyConfiguration.addToRole(globalRoleName, new EJBRoleRefPermission(ejbName, ejbScopedRoleName)); - - if (_logger.isLoggable(FINE)) { - _logger.fine( - "JACC: Converting role-ref -> " + roleReference.toString() + - " to permission with name(" + ejbName + ")" + - " and actions (" + ejbScopedRoleName + ")" + - " mapped to role (" + globalRoleName + ")"); - } - } - } - - - private static void writeOutPermissionsForNonRoleRefRoles(Collection allRoles, Collection ejbScopedRoleNames, String ejbName, PolicyConfiguration policyConfiguration) throws PolicyContextException { - for (Role role : allRoles) { - if (_logger.isLoggable(FINE)) { - _logger.fine("JACC: Converting role-ref: Looking at Role = " + role.getName()); - } - - if (!ejbScopedRoleNames.contains(role)) { - String roleName = role.getName(); - policyConfiguration.addToRole(roleName, new EJBRoleRefPermission(ejbName, roleName)); - - if (_logger.isLoggable(FINE)) { - _logger.fine( - "JACC: Converting role-ref: Role = " + role.getName() + - " is added as a permission with name(" + ejbName + ")" + - " and actions (" + roleName + ")" + - " mapped to role (" + roleName + ")"); - } - } - } - } - - /** - * JACC MR8 add WebRoleRefPermission for the any authenticated user role '**' - */ - private static void addAnyAuthenticatedUserRoleRef(PolicyConfiguration policyConfiguration, String ejbName) throws PolicyContextException { - String rolename = "**"; - policyConfiguration.addToRole(rolename, new EJBRoleRefPermission(ejbName, rolename)); - - if (_logger.isLoggable(Level.FINE)) { - _logger.fine( - "JACC: Converting role-ref: Adding any authenticated user role-ref " + - " to permission with name(" + ejbName + ")" + - " and actions (" + rolename + ")" + - " mapped to role (" + rolename + ")"); - } - } - - - - // collect role permisisions in table of collections - private static Map addToRolePermissions(Map perRolePermissions, MethodPermission methodPermission, EJBMethodPermission ejbMethodPermission) { - if (methodPermission.isRoleBased()) { - if (perRolePermissions == null) { - perRolePermissions = new HashMap<>(); - } - - String roleName = methodPermission.getRole().getName(); - - perRolePermissions.computeIfAbsent(roleName, e -> new Permissions()) - .add(ejbMethodPermission); - - if (_logger.isLoggable(FINE)) { - _logger.fine("JACC DD conversion: EJBMethodPermission ->(" + ejbMethodPermission.getName() + " " + ejbMethodPermission.getActions() + ")protected by role -> " + roleName); - } - } - - return perRolePermissions; - } - - // collect unchecked permissions in collection - private static Permissions addToUncheckedPermissions(Permissions permissions, MethodPermission methodPermission, EJBMethodPermission ejbMethodPermission) { - if (methodPermission.isUnchecked()) { - if (permissions == null) { - permissions = new Permissions(); - } - - permissions.add(ejbMethodPermission); - - if (_logger.isLoggable(FINE)) { - _logger.fine("JACC DD conversion: EJBMethodPermission ->(" + ejbMethodPermission.getName() + " " + ejbMethodPermission.getActions() + ") is (unchecked)"); - } - } - return permissions; - } - - // collect excluded permissions in collection - private static Permissions addToExcludedPermissions(Permissions permissions, MethodPermission methodPermission, EJBMethodPermission ejbMethodPermission) { - if (methodPermission.isExcluded()) { - if (permissions == null) { - permissions = new Permissions(); - } - - permissions.add(ejbMethodPermission); - - if (_logger.isLoggable(FINE)) { - _logger.fine("JACC DD conversion: EJBMethodPermission ->(" + ejbMethodPermission.getName() + " " + ejbMethodPermission.getActions() + ") is (excluded)"); - } - } - - return permissions; - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebConstraintsTranslator.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebConstraintsTranslator.java deleted file mode 100644 index c47d4dce4e5..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/JaccWebConstraintsTranslator.java +++ /dev/null @@ -1,1251 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jacc; - -import com.sun.enterprise.deployment.SecurityRoleDescriptor; -import com.sun.enterprise.deployment.WebBundleDescriptor; -import com.sun.enterprise.deployment.WebComponentDescriptor; -import com.sun.enterprise.deployment.web.*; -import org.glassfish.security.common.Role; - -import jakarta.security.jacc.*; -import java.security.Permission; -import java.security.Permissions; -import java.util.*; -import java.util.Map.Entry; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static com.sun.enterprise.security.jacc.MethodValue.methodArrayToSet; -import static com.sun.logging.LogDomains.SECURITY_LOGGER; -import static java.util.Collections.list; -import static java.util.logging.Level.*; - -/** - * This class is used for translating security constrains from web.xml and corresponding - * annotations into JACC permissions, and writing this to the pluggable {@link PolicyConfiguration} (which is - * EE standard permission repository). - * - * @author Harpreet Singh - * @author Jean-Francois Arcand - * @author Ron Monzillo - * @author Arjan Tijms (refactoring) - */ -public class JaccWebConstraintsTranslator { - - static final Logger logger = Logger.getLogger(SECURITY_LOGGER); - - /* Changed to order default pattern / below extension */ - private static final int PT_DEFAULT = 0; - private static final int PT_EXTENSION = 1; - private static final int PT_PREFIX = 2; - private static final int PT_EXACT = 3; - - private JaccWebConstraintsTranslator() { - } - - /** - * Translate the security constraints presents in the given WebBundleDescriptor to JACC permissions - * and store those in the given PolicyConfiguration. - * - * @param webBundleDescriptor the source of the security constraints - * @param policyConfiguration the target of the security permissions - * @throws PolicyContextException - */ - public static void translateConstraintsToPermissions(WebBundleDescriptor webBundleDescriptor, PolicyConfiguration policyConfiguration) throws PolicyContextException { - createResourceAndDataPermissions(webBundleDescriptor, policyConfiguration); - createWebRoleRefPermission(webBundleDescriptor, policyConfiguration); - } - - private static void createResourceAndDataPermissions(WebBundleDescriptor webBundleDescriptor, PolicyConfiguration policyConfiguration) throws PolicyContextException { - if (logger.isLoggable(FINE)) { - logger.entering(JaccWebConstraintsTranslator.class.getSimpleName(), "processConstraints"); - logger.log(FINE, "JACC: constraint translation: CODEBASE = " + policyConfiguration.getContextID()); - } - - // ### 1 ### - - // Parse the constraints in the webBundleDescriptor (representing web.xml and annotations) into - // a number of raw pattern builders. From these pattern builders we'll generate and write out - // permissions below - - Map patternBuilderMap = parseConstraints(webBundleDescriptor); - - // Permissions for resources that can't be accessed by anyone - Permissions excluded = new Permissions(); - - // Permissions for resources that are open to be accessed by everyone - Permissions unchecked = new Permissions(); - - // Permissions for resources that require a role - Map perRole = new HashMap(); - - boolean deny = webBundleDescriptor.isDenyUncoveredHttpMethods(); - - if (logger.isLoggable(FINE)) { - logger.fine( - "JACC: constraint capture: begin processing qualified url patterns" + - " - uncovered http methods will be " + - (deny ? "denied" : "permitted")); - } - - - // ### 2 ### - - // For all patterns that were created by the "parseConstraints" methods above, we now - // create permissions and add these to the various collections defined above. - - for (PatternBuilder patternBuilder : patternBuilderMap.values()) { - if (!patternBuilder.irrelevantByQualifier) { - - String urlPatternSpec = patternBuilder.urlPatternSpec.toString(); - - if (logger.isLoggable(FINE)) { - logger.fine("JACC: constraint capture: urlPattern: " + urlPatternSpec); - } - - // Handle uncovered methods - patternBuilder.handleUncovered(deny); - - // Handle excluded methods - adds resource permissions to the excluded collection - handleExcluded(excluded, patternBuilder, urlPatternSpec); - - // Handle methods requiring a role - adds resource permissions to the per role collection - handlePerRole(perRole, patternBuilder, urlPatternSpec); - - // Handle unchecked methods - adds resource permissions to the unchecked collection - handleUnchecked(unchecked, patternBuilder, urlPatternSpec); - - // Handle transport constraints - adds data permissions to the unchecked collection - handleConnections(unchecked, patternBuilder, urlPatternSpec); - } - } - - // ### 3 ### - - // Now that we have created and added permissions to the various collections, we'll write them - // out to the policyConfiguration - - - // Write out the translated/generated excluded permissions - policyConfiguration.addToExcludedPolicy(excluded); - - // Write out the translated/generated unchecked permissions - policyConfiguration.addToUncheckedPolicy(unchecked); - - logExcludedUncheckedPermissionsWritten(excluded, unchecked); - - // Write out the translated/generated per role permissions - for (Entry roleEntry : perRole.entrySet()) { - String role = roleEntry.getKey(); - Permissions permissions = roleEntry.getValue(); - - policyConfiguration.addToRole(role, permissions); - - logPerRolePermissionsWritten(role, permissions); - } - - if (logger.isLoggable(Level.FINE)) { - logger.exiting(JaccWebConstraintsTranslator.class.getSimpleName(), "processConstraints"); - } - } - - private static Map parseConstraints(WebBundleDescriptor webBundleDescriptor) { - if (logger.isLoggable(FINE)) { - logger.entering(JaccWebConstraintsTranslator.class.getSimpleName(), "parseConstraints"); - } - - Set roleSet = webBundleDescriptor.getRoles(); - - Map patternBuilderMap = new HashMap<>(); - - // Bootstrap the map with the default pattern; the default pattern will not be "committed", unless a constraint is - // defined on "\". This will ensure that a more restrictive constraint can be assigned to it - patternBuilderMap.put("/", new PatternBuilder("/")); - - // Iterate over security constraints - for (SecurityConstraint securityConstraint : webBundleDescriptor.getSecurityConstraintsSet()) { - - logger.fine("JACC: constraint translation: begin parsing security constraint"); - - AuthorizationConstraint authorizationConstraint = securityConstraint.getAuthorizationConstraint(); - UserDataConstraint dataConstraint = securityConstraint.getUserDataConstraint(); - - // Iterate over collections of URLPatterns within constraint - for (WebResourceCollection webResourceCollection : securityConstraint.getWebResourceCollections()) { - - logger.fine("JACC: constraint translation: begin parsing web resource collection"); - - // Enumerate over URLPatterns within collection - for (String urlPattern : webResourceCollection.getUrlPatterns()) { - if (urlPattern != null) { - // FIX TO BE CONFIRMED: encode all colons - urlPattern = urlPattern.replaceAll(":", "%3A"); - } - - if (logger.isLoggable(FINE)) { - logger.fine("JACC: constraint translation: process url pattern: " + urlPattern); - } - - // Determine if pattern is already in map - PatternBuilder patternBuilder = patternBuilderMap.get(urlPattern); - - // Apply new patterns to map - if (patternBuilder == null) { - patternBuilder = new PatternBuilder(urlPattern); - - // Iterate over patterns in map - for (Entry patternBuilderEntry : patternBuilderMap.entrySet()) { - - String otherUrl = patternBuilderEntry.getKey(); - - int otherUrlType = patternType(otherUrl); - switch (patternType(urlPattern)) { - - // If the new url/pattern is a path-prefix pattern, it must be qualified by every - // different (from it) path-prefix pattern (in the map) that is implied by the new - // pattern, and every exact pattern (in the map) that is implied by the new URL. - // - // Also, the new pattern must be added as a qualifier of the default pattern, and every - // extension pattern (existing in the map), and of every different path-prefix pattern that - // implies the new pattern. - // - // Note that we know that the new pattern does not exist in the map, thus we know that the - // new pattern is different from any existing path prefix pattern. - - case PT_PREFIX: - if ((otherUrlType == PT_PREFIX || otherUrlType == PT_EXACT) && implies(urlPattern, otherUrl)) { - patternBuilder.addQualifier(otherUrl); - } else if (otherUrlType == PT_PREFIX && implies(otherUrl, urlPattern)) { - patternBuilderEntry.getValue().addQualifier(urlPattern); - } else if (otherUrlType == PT_EXTENSION || otherUrlType == PT_DEFAULT) { - patternBuilderEntry.getValue().addQualifier(urlPattern); - } - break; - - // If the new pattern is an extension pattern, it must be qualified by every path-prefix - // pattern (in the map), and every exact pattern (in the map) that is implied by - // the new pattern. - // - // Also, it must be added as a qualifier of the default pattern, if it exists in the - // map. - case PT_EXTENSION: - if (otherUrlType == PT_PREFIX || (otherUrlType == PT_EXACT && implies(urlPattern, otherUrl))) { - patternBuilder.addQualifier(otherUrl); - } else if (otherUrlType == PT_DEFAULT) { - patternBuilderEntry.getValue().addQualifier(urlPattern); - } - break; - - // If the new pattern is the default pattern it must be qualified by every other pattern - // in the map. - case PT_DEFAULT: - if (otherUrlType != PT_DEFAULT) { - patternBuilder.addQualifier(otherUrl); - } - break; - - // If the new pattern is an exact pattern, it is not be qualified, but it must be added as - // as a qualifier to the default pattern, and to every path-prefix or extension pattern (in - // the map) that implies the new pattern. - case PT_EXACT: - if ((otherUrlType == PT_PREFIX || otherUrlType == PT_EXTENSION) && implies(otherUrl, urlPattern)) { - patternBuilderEntry.getValue().addQualifier(urlPattern); - } - else if (otherUrlType == PT_DEFAULT) { - patternBuilderEntry.getValue().addQualifier(urlPattern); - } - break; - default: - break; - } - } - - // Add the new pattern and its pattern spec builder to the map - patternBuilderMap.put(urlPattern, patternBuilder); - - } - - BitSet methods = methodArrayToSet(webResourceCollection.getHttpMethodsAsArray()); - - BitSet omittedMethods = null; - if (methods.isEmpty()) { - omittedMethods = methodArrayToSet(webResourceCollection.getHttpMethodOmissionsAsArray()); - } - - // Set and commit the method outcomes on the pattern builder - // - // Note that an empty omitted method set is used to represent - // the set of all HTTP methods - patternBuilder.setMethodOutcomes(roleSet, authorizationConstraint, dataConstraint, methods, omittedMethods); - - if (logger.isLoggable(FINE)) { - logger.fine("JACC: constraint translation: end processing url pattern: " + urlPattern); - } - } - - logger.fine("JACC: constraint translation: end parsing web resource collection"); - } - - logger.fine("JACC: constraint translation: end parsing security constraint"); - } - - if (logger.isLoggable(FINE)) { - logger.exiting(JaccWebConstraintsTranslator.class.getName(), "parseConstraints"); - } - - return patternBuilderMap; - } - - private static void handleExcluded(Permissions collection, PatternBuilder patternBuilder, String name) { - String actions = null; - BitSet excludedMethods = patternBuilder.getExcludedMethods(); - - if (patternBuilder.otherConstraint.isExcluded()) { - BitSet methods = patternBuilder.getMethodSet(); - methods.andNot(excludedMethods); - if (!methods.isEmpty()) { - actions = "!" + MethodValue.getActions(methods); - } - } else if (!excludedMethods.isEmpty()) { - actions = MethodValue.getActions(excludedMethods); - } else { - return; - } - - collection.add(new WebResourcePermission(name, actions)); - collection.add(new WebUserDataPermission(name, actions)); - - if (logger.isLoggable(FINE)) { - logger.fine("JACC: constraint capture: adding excluded methods: " + actions); - } - } - - private static void handlePerRole(Map map, PatternBuilder patternBuilder, String urlPatternSpec) { - Map roleMap = patternBuilder.getRoleMap(); - List roleList = null; - - // Handle the roles for the omitted methods - if (!patternBuilder.otherConstraint.isExcluded() && patternBuilder.otherConstraint.isAuthConstrained()) { - roleList = patternBuilder.otherConstraint.roleList; - - for (String roleName : roleList) { - BitSet methods = patternBuilder.getMethodSet(); - - // Reduce omissions for explicit methods granted to role - BitSet roleMethods = roleMap.get(roleName); - if (roleMethods != null) { - methods.andNot(roleMethods); - } - - String httpMethodSpec = null; - if (!methods.isEmpty()) { - httpMethodSpec = "!" + MethodValue.getActions(methods); - } - - addToRoleMap(map, roleName, new WebResourcePermission(urlPatternSpec, httpMethodSpec)); - } - } - - // Handle explicit methods, skip roles that were handled above - BitSet methods = patternBuilder.getMethodSet(); - - if (!methods.isEmpty()) { - for (Entry roleEntry : roleMap.entrySet()) { - String roleName = roleEntry.getKey(); - if (roleList == null || !roleList.contains(roleName)) { - BitSet roleMethods = roleEntry.getValue(); - if (!roleMethods.isEmpty()) { - addToRoleMap(map, roleName, new WebResourcePermission(urlPatternSpec, MethodValue.getActions(roleMethods))); - } - } - } - } - } - - private static void handleUnchecked(Permissions collection, PatternBuilder patternBuilder, String urlPatternSpec) { - String httpMethodSpec = null; - BitSet noAuthMethods = patternBuilder.getNoAuthMethods(); - - if (!patternBuilder.otherConstraint.isAuthConstrained()) { - BitSet methods = patternBuilder.getMethodSet(); - methods.andNot(noAuthMethods); - if (!methods.isEmpty()) { - httpMethodSpec = "!" + MethodValue.getActions(methods); - } - } else if (!noAuthMethods.isEmpty()) { - httpMethodSpec = MethodValue.getActions(noAuthMethods); - } else { - return; - } - - collection.add(new WebResourcePermission(urlPatternSpec, httpMethodSpec)); - - if (logger.isLoggable(FINE)) { - logger.fine("JACC: constraint capture: adding unchecked (for authorization) methods: " + httpMethodSpec); - } - } - - private static void handleConnections(Permissions permissions, PatternBuilder patternBuilder, String name) { - BitSet allConnectMethods = null; - boolean allConnectAtOther = patternBuilder.otherConstraint.isConnectAllowed(ConstraintValue.connectTypeNone); - - for (int i = 0; i < ConstraintValue.connectKeys.length; i++) { - - String actions = null; - String transport = ConstraintValue.connectKeys[i]; - - BitSet connectMethods = patternBuilder.getConnectMap(1 << i); - if (i == 0) { - allConnectMethods = connectMethods; - } else { - - // If connect type protected, remove methods that accept any connect - connectMethods.andNot(allConnectMethods); - } - - if (patternBuilder.otherConstraint.isConnectAllowed(1 << i)) { - if (i != 0 && allConnectAtOther) { - - // If all connect allowed at other - - if (connectMethods.isEmpty()) { - - // Skip, if remainder is empty, because methods that accept any connect were handled at i==0. - continue; - } - - // Construct actions using methods with specific connection requirements - actions = MethodValue.getActions(connectMethods); - } else { - BitSet methods = patternBuilder.getMethodSet(); - methods.andNot(connectMethods); - if (!methods.isEmpty()) { - actions = "!" + MethodValue.getActions(methods); - } - } - } else if (!connectMethods.isEmpty()) { - actions = MethodValue.getActions(connectMethods); - } else { - continue; - } - - actions = (actions == null) ? "" : actions; - String combinedActions = actions + ":" + transport; - - permissions.add(new WebUserDataPermission(name, combinedActions)); - - if (logger.isLoggable(FINE)) { - logger.fine( - "JACC: constraint capture: adding methods that accept connections with protection: " + - transport + - " methods: " + actions); - } - } - } - - static int patternType(Object urlPattern) { - String pattern = urlPattern.toString(); - - if (pattern.startsWith("*.")) { - return PT_EXTENSION; - } - - if (pattern.startsWith("/") && pattern.endsWith("/*")) { - return PT_PREFIX; - } - - if (pattern.equals("/")) { - return PT_DEFAULT; - } - - return PT_EXACT; - } - - static boolean implies(String pattern, String path) { - - // Check for exact match - if (pattern.equals(path)) { - return true; - } - - // Check for path prefix matching - if (pattern.startsWith("/") && pattern.endsWith("/*")) { - pattern = pattern.substring(0, pattern.length() - 2); - - int length = pattern.length(); - - if (length == 0) { - return true; // "/*" is the same as "/" - } - - return path.startsWith(pattern) && (path.length() == length || path.substring(length).startsWith("/")); - } - - // Check for suffix matching - if (pattern.startsWith("*.")) { - int slash = path.lastIndexOf('/'); - int period = path.lastIndexOf('.'); - if ((slash >= 0) && (period > slash) && path.endsWith(pattern.substring(1))) { - return true; - } - - return false; - } - - // Check for universal mapping - if (pattern.equals("/")) { - return true; - } - - return false; - } - - private static void addToRoleMap(Map roleMap, String roleName, Permission permission) { - roleMap.computeIfAbsent(roleName, e -> new Permissions()) - .add(permission); - - if (logger.isLoggable(FINE)) { - logger.fine("JACC: constraint capture: adding methods to role: " + roleName + " methods: " + permission.getActions()); - } - } - - private static void createWebRoleRefPermission(WebBundleDescriptor webBundleDescriptor, PolicyConfiguration policyConfiguration) throws PolicyContextException { - if (logger.isLoggable(FINE)) { - logger.entering(JaccWebConstraintsTranslator.class.getSimpleName(), "createWebRoleRefPermission"); - logger.log(FINE, "JACC: role-reference translation: Processing WebRoleRefPermission : CODEBASE = " + policyConfiguration.getContextID()); - } - - List servletScopedRoleNames = new ArrayList<>(); - Collection allRoles = webBundleDescriptor.getRoles(); - - Role anyAuthUserRole = new Role("**"); - boolean rolesetContainsAnyAuthUserRole = allRoles.contains(anyAuthUserRole); - - // Iterate through all Servlets in the application and write out role ref permissions for each - - for (WebComponentDescriptor componentDescriptor : webBundleDescriptor.getWebComponentDescriptors()) { - - // Name of Servlet being processed in this iteration - String servletName = componentDescriptor.getCanonicalName(); - - writeOutPermissionsForRoleRefRoles(componentDescriptor.getSecurityRoleReferenceSet(), servletScopedRoleNames, servletName, policyConfiguration); - - if (logger.isLoggable(FINE)) { - logger.fine("JACC: role-reference translation: Going through the list of roles not present in RoleRef elements and creating WebRoleRefPermissions "); - } - - // For every role in the application for which there is no mapping (role reference) defined for the current servlet - // we insert a 1:1 role mapping. E.g global role "foo" maps to an identical named role "foo" in the scope of Servlet - // "MyServlet" - // - // Note this is the most common situation as mapping roles per Servlet is quite rare in practice - writeOutPermissionsForNonRoleRefRoles(allRoles, servletScopedRoleNames, servletName, policyConfiguration); - - // JACC MR8 add WebRoleRefPermission for the any authenticated user role '**' - if ((!servletScopedRoleNames.contains(anyAuthUserRole)) && !rolesetContainsAnyAuthUserRole) { - addAnyAuthenticatedUserRoleRef(policyConfiguration, servletName); - } - } - - // After looking at roles per Servlet, look at global concerns - - // For every security role in the web application add a WebRoleRefPermission to the corresponding role. The name of all - // such permissions shall be the empty string, and the actions of each permission shall be the corresponding role name. - - // When checking a WebRoleRefPermission from a JSP not mapped to a servlet, use a permission with the empty string as - // its name and with the argument to isUserInRole as its actions - // - // Note, this has the effect of creating (web) application scoped roles (global roles), next to the Servlet scoped - // roles. - // - // See also S1AS8PE 4966609 - writeOutGlobalPermissionsForAllRoles(allRoles, policyConfiguration); - - // JACC MR8 add WebRoleRefPermission for the any authenticated user role '**' - if (!rolesetContainsAnyAuthUserRole) { - addAnyAuthenticatedUserRoleRef(policyConfiguration, ""); - } - - if (logger.isLoggable(FINE)) { - logger.exiting(JaccWebConstraintsTranslator.class.getName(), "createWebRoleRefPermission"); - } - } - - /** - * Writes out global WebRoleRefPermissions to the PolicyConfiguration, one for each role in - * the given role collection. - * - * @param allRoles collection of all roles in the web application - * @param policyConfiguration the target that receives the security permissions created by this method - * @throws PolicyContextException If the policy configuration throws an exception - */ - private static void writeOutGlobalPermissionsForAllRoles(Collection allRoles, PolicyConfiguration policyConfiguration) throws PolicyContextException { - for (Role role : allRoles) { - if (logger.isLoggable(FINE)) { - logger.fine("JACC: role-reference translation: Looking at Role = " + role.getName()); - } - - String roleName = role.getName(); - policyConfiguration.addToRole(roleName, new WebRoleRefPermission("", roleName)); - - if (logger.isLoggable(FINE)) { - logger.fine("JACC: role-reference translation: RoleRef = " + roleName + " is added for jsp's that can't be mapped to servlets"); - logger.fine("JACC: role-reference translation: Permission added for above role-ref =" + roleName + " " + ""); - } - } - } - - private static void writeOutPermissionsForRoleRefRoles(Collection securityRoleReferences, Collection servletScopedRoleNames, String servletName, PolicyConfiguration policyConfiguration) throws PolicyContextException { - for (SecurityRoleReference roleReference : securityRoleReferences) { - if (roleReference != null) { - - // The name of a role, local (scoped) to a single Servlet - String servletScopedRoleName = roleReference.getRoleName(); - servletScopedRoleNames.add(new Role(servletScopedRoleName)); - - // The name of the global role to which the local Servlet scoped role links (is mapped) - String globalRoleName = roleReference.getSecurityRoleLink().getName(); - - // Write the role reference to the target policy configuration - policyConfiguration.addToRole( - globalRoleName, - new WebRoleRefPermission(servletName, servletScopedRoleName)); - - if (logger.isLoggable(FINE)) { - logger.fine( - "JACC: role-reference translation: " + - "RoleRefPermission created with name (servlet-name) = " + servletName + - " and action (role-name tag) = " + servletScopedRoleName + - " added to role (role-link tag) = " + globalRoleName); - } - } - } - } - - /** - * - * @param allRoles collection of all roles in the web application - * @param roleRefRoles collection of roles for which there were role references (mappings from global roles) - * @param componentName name of the (servlet) component for which the permissions are created - * @param policyConfiguration the target that receives the security permissions created by this method - * @throws PolicyContextException If the policy configuration throws an exception - */ - private static void writeOutPermissionsForNonRoleRefRoles(Collection allRoles, Collection roleRefRoles, String componentName, PolicyConfiguration policyConfiguration) throws PolicyContextException { - for (Role role : allRoles) { - if (logger.isLoggable(FINE)) { - logger.fine("JACC: role-reference translation: Looking at Role = " + role.getName()); - } - - // For every role for which we didn't already create a role reference role, create a 1:1 mapping - // from the global roles. - if (!roleRefRoles.contains(role)) { - - String roleName = role.getName(); - policyConfiguration.addToRole(roleName, new WebRoleRefPermission(componentName, roleName)); - - if (logger.isLoggable(Level.FINE)) { - logger.fine("JACC: role-reference translation: RoleRef = " + roleName + " is added for servlet-resource = " + componentName); - logger.fine("JACC: role-reference translation: Permission added for above role-ref =" + componentName + " " + roleName); - } - } - } - } - - /** - * JACC MR8 add WebRoleRefPermission for the any authenticated user role '**' - */ - private static void addAnyAuthenticatedUserRoleRef(PolicyConfiguration policyConfiguration, String name) throws PolicyContextException { - String action = "**"; - policyConfiguration.addToRole(action, new WebRoleRefPermission(name, action)); - - if (logger.isLoggable(FINE)) { - logger.fine("JACC: any authenticated user role-reference translation: Permission added for role-ref =" + name + " " + action); - } - } - - private static void logExcludedUncheckedPermissionsWritten(Permissions excluded, Permissions unchecked) { - if (logger.isLoggable(FINE)) { - logger.fine("JACC: constraint capture: end processing qualified url patterns"); - - for (Permission p : list(excluded.elements())) { - String ptype = (p instanceof WebResourcePermission) ? "WRP " : "WUDP "; - logger.fine("JACC: permission(excluded) type: " + ptype + " name: " + p.getName() + " actions: " + p.getActions()); - } - - for (Permission p : list(unchecked.elements())) { - String ptype = (p instanceof WebResourcePermission) ? "WRP " : "WUDP "; - logger.fine("JACC: permission(unchecked) type: " + ptype + " name: " + p.getName() + " actions: " + p.getActions()); - } - } - } - - private static void logPerRolePermissionsWritten(String role, Permissions permissions) { - if (logger.isLoggable(FINE)) { - for (Permission p : list(permissions.elements())) { - String ptype = (p instanceof WebResourcePermission) ? "WRP " : "WUDP "; - - logger.fine("JACC: permission(" + role + ") type: " + ptype + " name: " + p.getName() + " actions: " + p.getActions()); - } - - } - } -} - -class ConstraintValue { - - static String connectKeys[] = { "NONE", "INTEGRAL", "CONFIDENTIAL" }; - - static int connectTypeNone = 1; - static HashMap connectHash = new HashMap(); - static { - for (int i = 0; i < connectKeys.length; i++) - connectHash.put(connectKeys[i], Integer.valueOf(1 << i)); - }; - - boolean excluded; - boolean ignoreRoleList; - final List roleList = new ArrayList(); - int connectSet; - - ConstraintValue() { - excluded = false; - ignoreRoleList = false; - connectSet = 0; - } - - static boolean bitIsSet(int map, int bit) { - return (map & bit) == bit ? true : false; - } - - void setRole(String role) { - synchronized (roleList) { - if (!roleList.contains(role)) { - roleList.add(role); - } - } - } - - void removeRole(String role) { - synchronized (roleList) { - if (roleList.contains(role)) { - roleList.remove(role); - } - } - } - - void setPredefinedOutcome(boolean outcome) { - if (!outcome) { - excluded = true; - } else { - ignoreRoleList = true; - } - } - - void addConnectType(String guarantee) { - int b = connectTypeNone; - if (guarantee != null) { - Integer bit = connectHash.get(guarantee); - if (bit == null) { - throw new IllegalArgumentException("constraint translation error-illegal trx guarantee"); - } - - b = bit.intValue(); - } - - connectSet |= b; - } - - boolean isExcluded() { - return excluded; - } - - /* - * ignoreRoleList is true if there was a security-constraint without an auth-constraint; such a constraint combines to - * allow access without authentication. - */ - boolean isAuthConstrained() { - if (excluded) { - return true; - } else if (ignoreRoleList || roleList.isEmpty()) { - return false; - } - return true; - } - - boolean isTransportConstrained() { - if (excluded || (connectSet != 0 && !bitIsSet(connectSet, connectTypeNone))) { - return true; - } - - return false; - } - - boolean isConnectAllowed(int cType) { - if (!excluded && (connectSet == 0 || bitIsSet(connectSet, connectTypeNone) || bitIsSet(connectSet, cType))) { - return true; - } - return false; - } - - void setOutcome(Set roleSet, AuthorizationConstraint ac, UserDataConstraint udc) { - if (ac == null) { - setPredefinedOutcome(true); - } else { - boolean containsAllRoles = false; - Enumeration eroles = ac.getSecurityRoles(); - if (!eroles.hasMoreElements()) { - setPredefinedOutcome(false); - } else - while (eroles.hasMoreElements()) { - SecurityRoleDescriptor srd = (SecurityRoleDescriptor) eroles.nextElement(); - String roleName = srd.getName(); - if ("*".equals(roleName)) { - containsAllRoles = true; - } else { - setRole(roleName); - } - } - /** - * JACC MR8 When role '*' named, do not include any authenticated user role '**' unless an application defined a role - * named '**' - */ - if (containsAllRoles) { - removeRole("**"); - Iterator it = roleSet.iterator(); - while (it.hasNext()) { - setRole(((Role) it.next()).getName()); - } - } - } - addConnectType(udc == null ? null : udc.getTransportGuarantee()); - - if (JaccWebConstraintsTranslator.logger.isLoggable(Level.FINE)) { - JaccWebConstraintsTranslator.logger.log(Level.FINE, "JACC: setOutcome yields: " + toString()); - } - - } - - void setValue(ConstraintValue constraint) { - excluded = constraint.excluded; - ignoreRoleList = constraint.ignoreRoleList; - roleList.clear(); - Iterator rit = constraint.roleList.iterator(); - while (rit.hasNext()) { - String role = (String) rit.next(); - roleList.add(role); - } - connectSet = constraint.connectSet; - } - - @Override - public String toString() { - StringBuilder roles = new StringBuilder(" roles: "); - Iterator rit = roleList.iterator(); - while (rit.hasNext()) { - roles.append(" ").append((String) rit.next()); - } - StringBuilder transports = new StringBuilder("transports: "); - for (int i = 0; i < connectKeys.length; i++) { - if (isConnectAllowed(1 << i)) { - transports.append(" ").append(connectKeys[i]); - } - } - return " ConstraintValue ( " + " excluded: " + excluded + " ignoreRoleList: " + ignoreRoleList + roles + transports + " ) "; - } - - /* - * ignoreRoleList is true if there was a security-constraint without an auth-constraint; such a constraint combines to - * allow access without authentication. - */ - boolean isUncovered() { - return (!excluded && !ignoreRoleList && roleList.isEmpty() && connectSet == 0); - } -} - -class MethodValue extends ConstraintValue { - - private static final List methodNames = new ArrayList<>(); - - int index; - - MethodValue(String methodName) { - index = getMethodIndex(methodName); - } - - MethodValue(String methodName, ConstraintValue constraint) { - index = getMethodIndex(methodName); - setValue(constraint); - } - - static String getMethodName(int index) { - synchronized (methodNames) { - return methodNames.get(index); - } - } - - static int getMethodIndex(String name) { - synchronized (methodNames) { - int index = methodNames.indexOf(name); - if (index < 0) { - index = methodNames.size(); - methodNames.add(index, name); - } - return index; - } - } - - static String getActions(BitSet methodSet) { - if (methodSet == null || methodSet.isEmpty()) { - return null; - } - - StringBuilder actions = null; - - for (int i = methodSet.nextSetBit(0); i >= 0; i = methodSet.nextSetBit(i + 1)) { - if (actions == null) { - actions = new StringBuilder(); - } else { - actions.append(","); - } - actions.append(getMethodName(i)); - } - - return (actions == null ? null : actions.toString()); - } - - static String[] getMethodArray(BitSet methodSet) { - if (methodSet == null || methodSet.isEmpty()) { - return null; - } - - int size = 0; - - List methods = new ArrayList<>(); - - for (int i = methodSet.nextSetBit(0); i >= 0; i = methodSet.nextSetBit(i + 1)) { - methods.add(getMethodName(i)); - size += 1; - } - - return methods.toArray(new String[size]); - } - - static BitSet methodArrayToSet(String[] methods) { - BitSet methodSet = new BitSet(); - - for (int i = 0; methods != null && i < methods.length; i++) { - if (methods[i] == null) { - throw new IllegalArgumentException("constraint translation error - null method name"); - } - int bit = getMethodIndex(methods[i]); - methodSet.set(bit); - } - - return methodSet; - } - - @Override - public String toString() { - return "MethodValue( " + getMethodName(index) + super.toString() + " )"; - } -} - -class PatternBuilder { - - final int patternType; - final int patternLength; - final StringBuilder urlPatternSpec; - final ConstraintValue otherConstraint; - final Map methodValues = new HashMap<>(); - - boolean committed; - boolean irrelevantByQualifier; - - PatternBuilder(String urlPattern) { - patternType = JaccWebConstraintsTranslator.patternType(urlPattern); - patternLength = urlPattern.length(); - urlPatternSpec = new StringBuilder(urlPattern); - otherConstraint = new ConstraintValue(); - } - - void addQualifier(String urlPattern) { - if (JaccWebConstraintsTranslator.implies(urlPattern, urlPatternSpec.substring(0, patternLength))) { - irrelevantByQualifier = true; - } - - urlPatternSpec.append(":" + urlPattern); - } - - MethodValue getMethodValue(int methodIndex) { - String methodName = MethodValue.getMethodName(methodIndex); - - synchronized (methodValues) { - MethodValue methodValue = methodValues.get(methodName); - if (methodValue == null) { - methodValue = new MethodValue(methodName, otherConstraint); - methodValues.put(methodName, methodValue); - - if (JaccWebConstraintsTranslator.logger.isLoggable(FINE)) { - JaccWebConstraintsTranslator.logger.log(FINE, "JACC: created MethodValue: " + methodValue); - } - } - - return methodValue; - } - } - - BitSet getExcludedMethods() { - BitSet methodSet = new BitSet(); - - synchronized (methodValues) { - for (MethodValue methodValue : methodValues.values()) { - if (methodValue.isExcluded()) { - methodSet.set(methodValue.index); - } - } - } - - return methodSet; - } - - BitSet getNoAuthMethods() { - BitSet methodSet = new BitSet(); - - synchronized (methodValues) { - for (MethodValue methodValue : methodValues.values()) { - if (!methodValue.isAuthConstrained()) { - methodSet.set(methodValue.index); - } - } - } - - return methodSet; - } - - BitSet getAuthConstrainedMethods() { - BitSet methodSet = new BitSet(); - - synchronized (methodValues) { - for (MethodValue methodValue : methodValues.values()) { - if (methodValue.isAuthConstrained()) { - methodSet.set(methodValue.index); - } - } - } - - return methodSet; - } - - BitSet getTransportConstrainedMethods() { - BitSet methodSet = new BitSet(); - - synchronized (methodValues) { - for (MethodValue methodValue : methodValues.values()) { - if (methodValue.isTransportConstrained()) { - methodSet.set(methodValue.index); - } - } - } - - return methodSet; - } - - /** - * Map of methods allowed per role - */ - HashMap getRoleMap() { - HashMap roleMap = new HashMap<>(); - - synchronized (methodValues) { - for (MethodValue methodValue : methodValues.values()) { - if (!methodValue.isExcluded() && methodValue.isAuthConstrained()) { - for (String role : methodValue.roleList) { - roleMap.computeIfAbsent(role, e -> new BitSet()) - .set(methodValue.index); - } - } - } - } - - return roleMap; - } - - BitSet getConnectMap(int cType) { - BitSet methodSet = new BitSet(); - - synchronized (methodValues) { - for (MethodValue methodValue : methodValues.values()) { - /* - * NOTE WELL: prior version of this method could not be called during constraint parsing because it finalized the - * connectSet when its value was 0 (indicating any connection, until some specific bit is set) if (v.connectSet == 0) { - * v.connectSet = MethodValue.connectTypeNone; } - */ - - if (methodValue.isConnectAllowed(cType)) { - methodSet.set(methodValue.index); - } - } - } - - return methodSet; - } - - BitSet getMethodSet() { - BitSet methodSet = new BitSet(); - - synchronized (methodValues) { - for (MethodValue methodValue : methodValues.values()) { - methodSet.set(methodValue.index); - } - } - - return methodSet; - } - - void setMethodOutcomes(Set roleSet, AuthorizationConstraint ac, UserDataConstraint udc, BitSet methods, BitSet omittedMethods) { - - committed = true; - - if (omittedMethods != null) { - - // Get the omitted methodSet - BitSet methodsInMap = getMethodSet(); - - BitSet saved = (BitSet) omittedMethods.clone(); - - // Determine methods being newly omitted - omittedMethods.andNot(methodsInMap); - - // Create values for newly omitted, init from otherConstraint - for (int i = omittedMethods.nextSetBit(0); i >= 0; i = omittedMethods.nextSetBit(i + 1)) { - getMethodValue(i); - } - - // Combine this constraint into constraint on all other methods - otherConstraint.setOutcome(roleSet, ac, udc); - - methodsInMap.andNot(saved); - - // Recursive call to combine constraint into prior omitted methods - setMethodOutcomes(roleSet, ac, udc, methodsInMap, null); - - } else { - for (int i = methods.nextSetBit(0); i >= 0; i = methods.nextSetBit(i + 1)) { - // Create values (and init from otherConstraint) if not in map - // then combine with this constraint. - getMethodValue(i).setOutcome(roleSet, ac, udc); - } - } - } - - void handleUncovered(boolean deny) { - - // Bypass any uncommitted patterns (e.g. the default pattern) which were entered in the map, but that were not named in - // a security constraint - - if (!committed) { - return; - } - - boolean otherIsUncovered = false; - synchronized (methodValues) { - BitSet uncoveredMethodSet = new BitSet(); - - // For all the methods in the mapValue - for (MethodValue methodValue : methodValues.values()) { - // If the method is uncovered add its id to the uncovered set - if (methodValue.isUncovered()) { - if (deny) { - methodValue.setPredefinedOutcome(false); - } - uncoveredMethodSet.set(methodValue.index); - } - } - - // If the constraint on all other methods is uncovered - if (otherConstraint.isUncovered()) { - - // This is the case where the problem is most severe, since a non-enumerable set of HTTP methods has - // been left uncovered. - // The set of method will be logged and denied. - - otherIsUncovered = true; - if (deny) { - otherConstraint.setPredefinedOutcome(false); - } - - // Ensure that the methods that are reported as uncovered includes any enumerated methods that were found to be - // uncovered. - BitSet otherMethodSet = getMethodSet(); - if (!uncoveredMethodSet.isEmpty()) { - - // UncoveredMethodSet contains methods that otherConstraint pertains to, so remove them from otherMethodSet - // which is the set to which the otherConstraint does not apply - otherMethodSet.andNot(uncoveredMethodSet); - } - - - // When otherIsUncovered, uncoveredMethodSet contains methods to which otherConstraint does NOT apply - uncoveredMethodSet = otherMethodSet; - } - - if (otherIsUncovered || !uncoveredMethodSet.isEmpty()) { - String uncoveredMethods = MethodValue.getActions(uncoveredMethodSet); - Object[] args = new Object[] { urlPatternSpec, uncoveredMethods }; - - if (deny) { - if (otherIsUncovered) { - JaccWebConstraintsTranslator.logger.log(INFO, "JACC: For the URL pattern {0}, all but the following methods have been excluded: {1}", args); - } else { - JaccWebConstraintsTranslator.logger.log(INFO, "JACC: For the URL pattern {0}, the following methods have been excluded: {1}", args); - } - } else { - if (otherIsUncovered) { - JaccWebConstraintsTranslator.logger.log(WARNING, "JACC: For the URL pattern {0}, all but the following methods were uncovered: {1}", args); - } else { - JaccWebConstraintsTranslator.logger.log(WARNING, "JACC: For the URL pattern {0}, the following methods were uncovered: {1}", args); - } - } - } - } - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextHandlerData.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextHandlerData.java deleted file mode 100644 index fe7c524621a..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextHandlerData.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jacc.context; - -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.EJB_ARGUMENTS; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.ENTERPRISE_BEAN; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.HTTP_SERVLET_REQUEST; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.REUSE; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.SOAP_MESSAGE; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.SUBJECT; - -import jakarta.servlet.http.HttpServletRequest; - -import com.sun.enterprise.security.SecurityContext; -import com.sun.enterprise.security.jacc.cache.PermissionCacheFactory; - -import org.glassfish.api.invocation.ComponentInvocation; -import org.glassfish.internal.api.Globals; -import java.lang.ref.WeakReference; - -/** - * This class implements thread scoped data used for the JACC PolicyContext. - * - *

- * Here the handlers for e.g. HTTP_SERVLET_REQUEST and SUBJECT are essentially implemented. - * - * @author Harry Singh - * @author Jyri Virkki - * @author Shing Wai Chan - * - */ -public class PolicyContextHandlerData { - - private HttpServletRequest httpServletRequest; - private WeakReference invocation; - private PolicyContextDelegate ejbDelegate; - - private PolicyContextHandlerData() { - ejbDelegate = Globals.getDefaultHabitat().getService(PolicyContextDelegate.class, "EJB"); - } - - public static PolicyContextHandlerData getInstance() { - return new PolicyContextHandlerData(); - } - - public void setHttpServletRequest(HttpServletRequest httpReq) { - this.httpServletRequest = httpReq; - } - - public void setInvocation(ComponentInvocation inv) { - this.invocation = new WeakReference<>(inv); - } - - public Object get(String key) { - if (HTTP_SERVLET_REQUEST.equalsIgnoreCase(key)) { - return httpServletRequest; - } - - if (SUBJECT.equalsIgnoreCase(key)) { - return SecurityContext.getCurrent().getSubject(); - } - - if (REUSE.equalsIgnoreCase(key)) { - PermissionCacheFactory.resetCaches(); - return Integer.valueOf(0); - } - - if (invocation == null) { - return null; - } - - if (SOAP_MESSAGE.equalsIgnoreCase(key)) { - return ejbDelegate != null ? ejbDelegate.getSOAPMessage(invocation.get()) : null; - } - - if (ENTERPRISE_BEAN.equalsIgnoreCase(key)) { - return ejbDelegate != null ? ejbDelegate.getEnterpriseBean(invocation.get()) : null; - } - - if (EJB_ARGUMENTS.equalsIgnoreCase(key)) { - return ejbDelegate != null ? ejbDelegate.getEJbArguments(invocation.get()) : null; - } - - return null; - } - - void reset() { - httpServletRequest = null; - invocation = null; - ejbDelegate = null; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextHandlerImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextHandlerImpl.java deleted file mode 100644 index 5abada08f65..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextHandlerImpl.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jacc.context; - -import java.security.SecurityPermission; -import jakarta.security.jacc.PolicyContextHandler; - -/** - * This class is created by the container and handed over to the JACC provider. This lets the JACC provider use the - * information in making authorization decisions, if it wishes to do so. - * - *

- * Instead of having separate classes for each handler, we only implement one handler that handles all - * requests for the context objects. This class implements the PolicyContextHandler interface, but resolving - * of the actual objects is delegated to {@link PolicyContextHandlerData}. - * - * @author Harpreet Singh - * @author Shing Wai Chan - */ -public class PolicyContextHandlerImpl implements PolicyContextHandler { - - public static final String HTTP_SERVLET_REQUEST = "jakarta.servlet.http.HttpServletRequest"; - public static final String SOAP_MESSAGE = "jakarta.xml.soap.SOAPMessage"; - public static final String ENTERPRISE_BEAN = "jakarta.ejb.EnterpriseBean"; - public static final String EJB_ARGUMENTS = "jakarta.ejb.arguments"; - public static final String SUBJECT = "javax.security.auth.Subject.container"; - public static final String REUSE = "java.security.Policy.supportsReuse"; - - private static PolicyContextHandlerImpl policyContextHandler; - - private ThreadLocal thisHandlerData = new ThreadLocal<>(); - - private PolicyContextHandlerImpl() { - } - - private synchronized static PolicyContextHandlerImpl _getInstance() { - if (policyContextHandler == null) { - policyContextHandler = new PolicyContextHandlerImpl(); - } - - return policyContextHandler; - } - - public static PolicyContextHandler getInstance() { - SecurityManager securityManager = System.getSecurityManager(); - if (securityManager != null) { - securityManager.checkPermission(new SecurityPermission("setPolicy")); - } - - return _getInstance(); - } - - @Override - public boolean supports(String key) { - String[] s = getKeys(); - for (int i = 0; i < s.length; i++) { - if (s[i].equalsIgnoreCase(key)) { - return true; - } - } - return false; - } - - @Override - public String[] getKeys() { - String[] s = { HTTP_SERVLET_REQUEST, SOAP_MESSAGE, ENTERPRISE_BEAN, SUBJECT, EJB_ARGUMENTS, REUSE }; - return s; - } - - @Override - public Object getContext(String key, Object data) { - // ignore data Object - return getHandlerData().get(key); - } - - public PolicyContextHandlerData getHandlerData() { - PolicyContextHandlerData handlerData = thisHandlerData.get(); - if (handlerData == null) { - handlerData = PolicyContextHandlerData.getInstance(); - thisHandlerData.set(handlerData); - } - - return handlerData; - } - - public void reset() { - PolicyContextHandlerData handlerData = thisHandlerData.get(); - if (handlerData != null) { - handlerData.reset(); - } - - thisHandlerData.set(null); - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextRegistration.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextRegistration.java deleted file mode 100644 index bdab8a93af3..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/PolicyContextRegistration.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jacc.context; - -import java.util.logging.Logger; - -import jakarta.security.jacc.PolicyContextException; -import jakarta.security.jacc.PolicyContextHandler; - -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.EJB_ARGUMENTS; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.ENTERPRISE_BEAN; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.HTTP_SERVLET_REQUEST; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.REUSE; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.SOAP_MESSAGE; -import static com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl.SUBJECT; -import static java.util.logging.Level.SEVERE; -import static jakarta.security.jacc.PolicyContext.registerHandler; - -public class PolicyContextRegistration { - private static final Logger LOG = Logger.getLogger(PolicyContextRegistration.class.getName()); - - /** - * This method registers the policy handlers, which provide objects JACC Providers - * and other code can use. - * - *

- * Note, in a full EE environment with CDI, only the JACC unique SUBJECT is typically - * really useful. - */ - public static void registerPolicyHandlers() { - LOG.finest("registerPolicyHandlers()"); - try { - PolicyContextHandler policyContextHandler = PolicyContextHandlerImpl.getInstance(); - - registerHandler(ENTERPRISE_BEAN, policyContextHandler, true); - registerHandler(SUBJECT, policyContextHandler, true); - registerHandler(EJB_ARGUMENTS, policyContextHandler, true); - registerHandler(SOAP_MESSAGE, policyContextHandler, true); - registerHandler(HTTP_SERVLET_REQUEST, policyContextHandler, true); - registerHandler(REUSE, policyContextHandler, true); - LOG.config("Policy handlers successfully registered."); - } catch (PolicyContextException ex) { - LOG.log(SEVERE, "Failed to register policy handlers!", ex); - } - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/package-info.java deleted file mode 100644 index 2f18f8d2ef7..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/context/package-info.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) [2017-2018] Payara Foundation and/or its affiliates. - * All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://github.com/payara/Payara/blob/main/LICENSE.txt - * See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at glassfish/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * The Payara Foundation designates this particular file as subject to the - * "Classpath" exception as provided by the Payara Foundation in the GPL - * Version 2 section of the License file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -/** - * This package contains the JACC Policy Context Handlers. - * - *

- * These handlers provide a number of convenient objects bound to thread local - * storage that can be obtained from "anywhere" like the current HTTP request and - * the current Subject. - * - *

- * These context handlers are a little like producers in CDI. - */ -package com.sun.enterprise.security.jacc.context; \ No newline at end of file diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java deleted file mode 100644 index 4fa54399e1c..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jacc/package-info.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) [2017-2018] Payara Foundation and/or its affiliates. - * All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://github.com/payara/Payara/blob/main/LICENSE.txt - * See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at glassfish/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * The Payara Foundation designates this particular file as subject to the - * "Classpath" exception as provided by the Payara Foundation in the GPL - * Version 2 section of the License file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] -/** - * This package contains much of the implementation code for JACC. - * - *

- * JACC is the EE standard for taking care of the authorization aspects - * of security. - * - *

- * Code in this package translates constraints - * from the web and EJB descriptors that are pre-parsed by Payara into - * various JACC Permission instances. - * These instances are stored into a pluggable PolicyConfiguration. By - * default Payara is configured to use the one from "jacc.provider.file". - * - * This package also contains the web authorization manager, which is the entry - * point for all authorization decisions from the web layer. This too - * is delegated to a pluggable component called the JACC Policy Provider. - * - *

- * The pluggable JACC components are loaded by a class in nucleus: - * {@link com.sun.enterprise.security.PolicyLoader} - * - */ -package com.sun.enterprise.security.jacc; \ No newline at end of file diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index d714f2a37b6..04f19d1bcad 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -58,17 +58,16 @@ import com.sun.enterprise.security.auth.login.DistinguishedPrincipalCredential; import com.sun.enterprise.security.auth.login.LoginContextDriver; import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; +import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; import com.sun.enterprise.security.ee.authentication.jakarta.callback.ServerContainerCallbackHandler; import com.sun.enterprise.security.integration.RealmInitializer; import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; -import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; import com.sun.enterprise.security.web.integration.WebPrincipal; import com.sun.enterprise.security.ee.web.integration.WebSecurityManagerFactory; import com.sun.enterprise.util.net.NetUtils; import com.sun.logging.LogDomains; -import com.sun.web.security.realmadapter.AuthenticatorProxy; import fish.payara.nucleus.requesttracing.RequestTracingService; import jakarta.security.auth.message.AuthStatus; import jakarta.security.auth.message.MessageInfo; @@ -138,7 +137,6 @@ import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.REGISTER_WITH_AUTHENTICATOR; import static com.sun.enterprise.util.Utility.isAllNull; import static com.sun.logging.LogDomains.WEB_LOGGER; -import static com.sun.web.security.realmadapter.AuthenticatorProxy.PROXY_AUTH_TYPE; import static java.lang.String.format; import static java.net.URLEncoder.encode; import static java.security.AccessController.doPrivileged; @@ -151,7 +149,7 @@ import static org.apache.catalina.realm.Constants.FORM_METHOD; import static org.glassfish.api.admin.ServerEnvironment.DEFAULT_INSTANCE_NAME; -import static com.sun.enterprise.security.ee.web.integration.AuthorizationUtil.getContextID; + import static org.glassfish.epicyro.config.helper.HttpServletConstants.POLICY_CONTEXT; import static org.glassfish.epicyro.config.helper.HttpServletConstants.REGISTER_SESSION; import static com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy.WEB_BUNDLE; @@ -339,7 +337,7 @@ public synchronized void initAuthenticationService(final ServletContext servletC private BaseAuthenticationService createAuthenticationService(final ServletContext servletContext) throws IOException { Map properties = new HashMap<>(); - String policyContextId = getContextID(webDescriptor); + String policyContextId = SecurityUtil.getContextID(webDescriptor); if (policyContextId != null) { properties.put(POLICY_CONTEXT, policyContextId); } @@ -582,7 +580,7 @@ public int preAuthenticateCheck(HttpRequest request, HttpResponse response, Secu disableProxyCaching(request, response, disableProxyCaching, securePagesWithPragma); if (ssoEnabled) { HttpServletRequest httpServletRequest = (HttpServletRequest) request.getRequest(); - if (!getWebSecurityManager(true).isPermitAll(httpServletRequest)) { + if (!getWebSecurityManager(true).permitAll(httpServletRequest)) { // Create a session for protected SSO association httpServletRequest.getSession(true); } @@ -636,7 +634,7 @@ private boolean validateRequest(HttpRequest request, HttpResponse response, Logi try { - isMandatory = this.webAuthorizationManagerService.isPermitAll(servletRequest); + isMandatory = this.webAuthorizationManagerService.permitAll(servletRequest); // Produce caller challenge if call originates from HttpServletRequest#authenticate if (isMandatory || calledFromAuthenticate) { messageInfo.getMap().put(HttpServletConstants.IS_MANDATORY, Boolean.TRUE.toString()); @@ -1165,10 +1163,11 @@ public void logout(HttpRequest httpRequest) { public void logout() { setSecurityContext(null); - doPrivileged((PrivilegedAction) () -> { - resetPolicyContext(); - return null; - }); + // Sets the security context for Jakarta Authorization + WebAuthorizationManagerService webAuthorizationManagerService = getWebSecurityManager(false); + if (webAuthorizationManagerService != null) { + webAuthorizationManagerService.onLogout(); + } } @Override @@ -1475,8 +1474,8 @@ protected Principal getPrincipal(String username) { * * @exception IOException if an input/output error occurs */ - private boolean invokeWebSecurityManager(HttpRequest request, HttpResponse response, SecurityConstraint[] constraints) throws IOException { - + private boolean invokeWebSecurityManager(HttpRequest request, HttpResponse response, + SecurityConstraint[] constraints) throws IOException { if (isRequestFormPage(request)) { return true; } @@ -1488,12 +1487,12 @@ private boolean invokeWebSecurityManager(HttpRequest request, HttpResponse respo " Principal: " + httpServletRequest.getUserPrincipal() + " ContextPath: " + httpServletRequest.getContextPath()); - //WebSecurityManager webSecurityManager = getWebSecurityManager(true); - //if (webSecurityManager == null) { - // return false; - //} + WebAuthorizationManagerService webAuthorizationManagerService = getWebSecurityManager(true); + if (webAuthorizationManagerService == null) { + return false; + } - return true; + return webAuthorizationManagerService.hasResourcePermission(httpServletRequest); } private void setServletPath(HttpRequest request) { @@ -1750,11 +1749,6 @@ private void sendServiceUnavailable(HttpResponse response, Throwable e) throws I response.setDetailMessage(resourceBundle.getString("realmBase.forbidden")); } - private void resetPolicyContext() { - ((PolicyContextHandlerImpl) PolicyContextHandlerImpl.getInstance()).reset(); - PolicyContext.setContextID(null); - } - private SecurityContext getSecurityContextForPrincipal(Principal principal) { if (principal == null) { return null; diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java index 344b64cb406..9f2f297df4b 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/webservices/SecurityServiceImpl.java @@ -46,7 +46,6 @@ import com.sun.enterprise.deployment.WebServiceEndpoint; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; -import com.sun.enterprise.security.jacc.context.PolicyContextHandlerImpl; import com.sun.enterprise.security.web.integration.WebPrincipal; import com.sun.enterprise.web.WebModule; import com.sun.web.security.RealmAdapter; @@ -212,7 +211,6 @@ public void resetSecurityContext() { @Override public void resetPolicyContext() { - ((PolicyContextHandlerImpl) PolicyContextHandlerImpl.getInstance()).reset(); PolicyContext.setContextID(null); } diff --git a/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/WebContainer.java b/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/WebContainer.java index 36d3dc4587c..05b42ac004e 100644 --- a/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/WebContainer.java +++ b/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/WebContainer.java @@ -51,7 +51,6 @@ import com.sun.enterprise.deployment.Application; import com.sun.enterprise.deployment.WebBundleDescriptor; import com.sun.enterprise.deployment.WebComponentDescriptor; -import com.sun.enterprise.security.ee.SecurityDeployer; import com.sun.enterprise.security.integration.RealmInitializer; import com.sun.enterprise.server.logging.LoggingRuntime; import com.sun.enterprise.util.Result; @@ -317,9 +316,6 @@ public class WebContainer implements org.glassfish.api.container.Container, Post @Inject ServerConfigLookup serverConfigLookup; - @Inject - private SecurityDeployer securityDeployer; - protected JspProbeProvider jspProbeProvider; protected RequestProbeProvider requestProbeProvider; protected ServletProbeProvider servletProbeProvider; @@ -1483,7 +1479,6 @@ public void loadDefaultWebModule(VirtualServer virtualServer) { protected void loadStandaloneWebModule(VirtualServer virtualServer, WebModuleConfig webModuleConfig) { try { loadWebModule(virtualServer, webModuleConfig, "null", null); - securityDeployer.loadPolicy(webModuleConfig.getDescriptor(), false); } catch (Throwable t) { logger.log(SEVERE, format(rb.getString(LOAD_WEB_MODULE_ERROR), webModuleConfig.getName()), t); } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java deleted file mode 100644 index 4071525d44d..00000000000 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/PolicyLoader.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2017-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security; - -import com.sun.enterprise.config.serverbeans.JaccProvider; -import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.util.i18n.StringManager; -import jakarta.inject.Inject; -import jakarta.inject.Named; -import jakarta.inject.Singleton; -import jakarta.security.jacc.Policy; -import jakarta.security.jacc.PolicyFactory; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.util.proxy.MethodHandler; -import javassist.util.proxy.ProxyFactory; -import javassist.util.proxy.ProxyObject; -import org.glassfish.hk2.api.IterableProvider; -import org.jvnet.hk2.annotations.Service; -import org.jvnet.hk2.config.types.Property; - -import java.lang.reflect.InvocationTargetException; -import java.util.logging.Logger; - -import static com.sun.enterprise.security.SecurityLoggerInfo.policyConfigFactoryNotDefined; -import static com.sun.enterprise.security.SecurityLoggerInfo.policyFactoryOverride; -import static com.sun.enterprise.security.SecurityLoggerInfo.policyInstallError; -import static com.sun.enterprise.security.SecurityLoggerInfo.policyNoSuchName; -import static com.sun.enterprise.security.SecurityLoggerInfo.policyNotLoadingWarning; -import static com.sun.enterprise.security.SecurityLoggerInfo.policyProviderConfigOverrideMsg; -import static com.sun.enterprise.security.SecurityLoggerInfo.policyProviderConfigOverrideWarning; -import static com.sun.enterprise.security.SecurityLoggerInfo.policyReadingError; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.FINEST; -import static java.util.logging.Level.INFO; -import static java.util.logging.Level.SEVERE; -import static java.util.logging.Level.WARNING; -import static javassist.Modifier.PUBLIC; -import static org.glassfish.api.admin.ServerEnvironment.DEFAULT_INSTANCE_NAME; - -/** - * Loads the default JACC Policy Provider into the system. - * - * @author Harpreet Singh - * @author Jyri J. Virkki - */ -@Service -@Singleton -public class PolicyLoader { - - private static final Logger LOGGER = SecurityLoggerInfo.getLogger(); - private static final StringManager STRING_MANAGER = StringManager.getManager(PolicyLoader.class); - - private static final String POLICY_PROVIDER_14 = "jakarta.security.jacc.policy.provider"; - private static final String POLICY_PROVIDER_13 = "jakarta.security.jacc.auth.policy.provider"; - public static final String POLICY_CONF_FACTORY = "jakarta.security.jacc.PolicyConfigurationFactory.provider"; - public static final String POLICY_FACTORY_PROVIDER = "jakarta.security.jacc.PolicyFactory.provider"; - private static final String POLICY_PROP_PREFIX = "com.sun.enterprise.jaccprovider.property."; - - private static final String AUTH_PROXY_HANDLER = "com.sun.enterprise.security.AuthenticationProxyHandler"; - private static final String DEFAULT_POLICY_PROVIDER = "fish.payara.security.jacc.provider.PolicyProviderImpl"; - - @Inject - @Named(DEFAULT_INSTANCE_NAME) - private SecurityService securityService; - - @Inject - private IterableProvider jaccProviders; - - private boolean isPolicyInstalled; - - /** - * Attempts to install the JACC policy-provider (authorization module) - * - *

- * The policy-provider element in domain.xml is consulted for the class to use. - * - *

- * Note that if the jakarta.security.jacc.policy.provider system property is set it will override - * the domain.xml configuration. This will normally not be the case in Payara. - * - *

- * The J2EE 1.3 property jakarta.security.jacc.auth.policy.provider is checked as a last resort. - * It should not be set in J2EE 1.4. - */ - public void loadPolicy() { - if (isPolicyInstalled) { - LOGGER.fine("Policy already installed. Will not re-install."); - return; - } - - // Get configuration object for the JACC provider (which handles the policies) - JaccProvider jaccProvider = getConfiguredJaccProvider(); - - // Set config properties (see method comments) - setPolicyConfigurationFactory(jaccProvider); - - boolean j2ee13 = false; - - // Get policy class name via the "normal" ways - String policyClassName = getConfiguredPolicyClassName(jaccProvider); - - if (policyClassName == null) { - // Try legacy fallback (at some point we might want to stop supporting this) - policyClassName = System.getProperty(POLICY_PROVIDER_13); - if (policyClassName != null) { - // Warn user j2ee13 property is being used - j2ee13 = true; - LOGGER.log(WARNING, policyProviderConfigOverrideWarning, new String[] { POLICY_PROVIDER_13, policyClassName }); - } - } - - if (policyClassName != null) { - // Now install the policy provider if one was identified - installPolicyFromClassName(policyClassName, j2ee13); - } else { - // No value for policy provider found - LOGGER.warning(policyNotLoadingWarning); - } - } - - private String getConfiguredPolicyClassName(JaccProvider jaccProvider) { - // Check if system property is set - String policyClassName = System.getProperty(POLICY_PROVIDER_14); - - if (policyClassName != null) { - // Inform user domain.xml is being ignored - LOGGER.log(INFO, policyProviderConfigOverrideMsg, new String[] { POLICY_PROVIDER_14, policyClassName }); - } else if (jaccProvider != null) { - // Otherwise obtain JACC policy-provider from domain.xml - policyClassName = jaccProvider.getPolicyProvider(); - } - - return policyClassName; - } - - /** - * Returns a JaccProvider object representing the jacc element from domain.xml which is configured in security-service. - * - * @return The config object or null on errors. - */ - private JaccProvider getConfiguredJaccProvider() { - JaccProvider jaccProvider = null; - try { - String name = securityService.getJacc(); - jaccProvider = getJaccProviderByName(name); - - if (jaccProvider == null) { - LOGGER.log(WARNING, policyNoSuchName, name); - } - } catch (Exception e) { - LOGGER.warning(policyReadingError); - jaccProvider = null; - } - - return jaccProvider; - } - - private JaccProvider getJaccProviderByName(String name) { - if (jaccProviders == null || name == null) { - return null; - } - - for (JaccProvider jaccProvider : jaccProviders) { - if (jaccProvider.getName().equals(name)) { - return jaccProvider; - } - } - - return null; - } - - /** - * Set internal properties based on domain.xml configuration. - * - *

- * The POLICY_CONF_FACTORY property is consumed by the jacc-api as documented in JACC specification. It's value is set - * here to the value given in domain.xml unless it is already set in which case the value is not modified. - * - *

- * Then and properties associated with this jacc provider from domain.xml are set as internal properties prefixed with - * POLICY_PROP_PREFIX. This is currently a workaround for bug 4846938. A cleaner interface should be adopted. - * - */ - private void setPolicyConfigurationFactory(JaccProvider jaccProvider) { - if (jaccProvider == null) { - return; - } - - // Handle JACC-specified property for factory - // TODO:V3 system property being read here - String prop = System.getProperty(POLICY_CONF_FACTORY); - if (prop != null) { - // Warn user of override - LOGGER.log(WARNING, policyFactoryOverride, new String[] { POLICY_CONF_FACTORY, prop }); - - } else { - // Use domain.xml value by setting the property to it - String factory = jaccProvider.getPolicyConfigurationFactoryProvider(); - if (factory == null) { - LOGGER.log(WARNING, policyConfigFactoryNotDefined); - } else { - System.setProperty(POLICY_CONF_FACTORY, factory); - } - } - - // Next, make properties of this JACC provider available to provider - for (Property jaccProperty : jaccProvider.getProperty()) { - String name = POLICY_PROP_PREFIX + jaccProperty.getName(); - String value = jaccProperty.getValue(); - LOGGER.log(FINEST, () -> "PolicyLoader set [" + name + "] to [" + value + "]"); - - System.setProperty(name, value); - } - } - - private void installPolicyFromClassName(String policyClassName, boolean j2ee13) { - try { - LOGGER.log(INFO, SecurityLoggerInfo.policyLoading, policyClassName); - Object policyInstance; - if (System.getSecurityManager() == null - || policyClassName.equals(DEFAULT_POLICY_PROVIDER)) { - policyInstance = loadClass(policyClassName); - } else { - policyInstance = loadPolicyAsProxy(policyClassName); - } - - installPolicy14(policyInstance); - - } catch (Exception e) { - LOGGER.log(SEVERE, policyInstallError, e.getLocalizedMessage()); - throw new RuntimeException(e); - } - - // Success. - LOGGER.log(FINE, () -> "Policy set to: " + policyClassName); - isPolicyInstalled = true; - } - - private void installPolicy14(Object policyInstance) { - if (!(policyInstance instanceof jakarta.security.jacc.Policy)) { - throw new RuntimeException(STRING_MANAGER.getString("enterprise.security.plcyload.not14")); - } - - Policy policy = (jakarta.security.jacc.Policy) policyInstance; - PolicyFactory.getPolicyFactory().setPolicy(policy); - - // TODO: causing ClassCircularity error when SM ON and deployment use library feature and - // ApplibClassLoader - // - // It is likely a problem caused by the way class loading is done in this case. - if (System.getSecurityManager() == null) { - policy.refresh(); - } - } - - - private Object loadClass(String policyClassName) - throws ClassNotFoundException, InstantiationException, - IllegalAccessException, NoSuchMethodException, - IllegalArgumentException, InvocationTargetException { - return Thread.currentThread() - .getContextClassLoader() - .loadClass(policyClassName) - .getDeclaredConstructor() - .newInstance(); - } - - private Policy loadPolicyAsProxy(String javaPolicyClassName) throws Exception { - - ClassPool pool = ClassPool.getDefault(); - CtClass clazz = pool.get(javaPolicyClassName); - clazz.defrost(); - clazz.setModifiers(PUBLIC); - Class targetClass = clazz.toClass( - Thread.currentThread() - .getContextClassLoader() - .loadClass(System.getProperty(POLICY_CONF_FACTORY))); - - ProxyObject instance; - - ProxyFactory factory = new ProxyFactory(); - factory.setSuperclass(targetClass); - instance = (ProxyObject) factory.createClass().getDeclaredConstructor().newInstance(); - - clazz = pool.get(AUTH_PROXY_HANDLER); - Class handlerClass = clazz.toClass(targetClass.getClassLoader(), targetClass.getProtectionDomain()); - MethodHandler handler = (MethodHandler) handlerClass - .getDeclaredConstructor(Policy.class) - .newInstance(PolicyFactory.getPolicyFactory().getPolicy()); - instance.setHandler(handler); - - if (!(instance instanceof Policy)) { - throw new RuntimeException(STRING_MANAGER.getString("enterprise.security.plcyload.not14")); - } - - instance.toString(); - - return (Policy) instance; - } - -} diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityLifecycle.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityLifecycle.java index fc4f5034c1b..cfc97bd426d 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityLifecycle.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityLifecycle.java @@ -77,9 +77,6 @@ public class SecurityLifecycle implements PostConstruct, PreDestroy { @Inject private ServerContext sc; - @Inject - private PolicyLoader policyLoader; - @Inject private SecurityServicesUtil secServUtil; @@ -149,8 +146,6 @@ public void onInitialization() { "com.sun.enterprise.security.web.integration.GlassfishRoleMapper"); } - policyLoader.loadPolicy(); - realmsManager.createRealms(); // start the audit mechanism AuditManager auditManager = secServUtil.getAuditManager(); diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityManager.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityManager.java index 376df32ae58..b2b2ad777d3 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityManager.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityManager.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; import java.lang.reflect.Method; @@ -80,6 +80,8 @@ public interface SecurityManager { */ void preInvoke(ComponentInvocation inv); + Object invoke(Object bean, Method beanClassMethod, Object[] methodParameters) throws Throwable; + /** * This method is used by the Invocation Manager to remove the run-as identity information that was set up using the * preInvoke @@ -107,12 +109,4 @@ public interface SecurityManager { */ void resetPolicyContext(); - /** - * This method is used by SecurityUtil runMethod to run the action as the subject encapsulated in the cuurent - * SecurityContext. - */ - public Object doAsPrivileged(PrivilegedExceptionAction pea) throws Throwable; - - public Object invoke(Method beanClassMethod, boolean isLocal, Object o, Object[] oa) throws Throwable; - } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityUpgradeService.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityUpgradeService.java index c158e0546f9..d5297235a5e 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityUpgradeService.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityUpgradeService.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2021-2022] Payara Foudation and/or affiliates +// Portions Copyright [2021-2024] Payara Foudation and/or affiliates package com.sun.enterprise.security; @@ -179,7 +179,7 @@ private void upgradeJACCProvider(SecurityService securityService) { try { List jaccProviders = securityService.getJaccProvider(); for (JaccProvider jacc : jaccProviders) { - if ("fish.payara.security.jacc.provider.PolicyConfigurationFactoryImpl".equals(jacc.getPolicyConfigurationFactoryProvider())) { + if ("org.glassfish.exousia.modules.locked.SimplePolicyConfigurationFactory".equals(jacc.getPolicyConfigurationFactoryProvider())) { //simple policy provider already present return; } @@ -188,8 +188,8 @@ private void upgradeJACCProvider(SecurityService securityService) { JaccProvider jacc = secServ.createChild(JaccProvider.class); //add the simple provider to the domain's security service jacc.setName("simple"); - jacc.setPolicyConfigurationFactoryProvider("fish.payara.security.jacc.provider.PolicyConfigurationFactoryImpl"); - jacc.setPolicyProvider("fish.payara.security.jacc.provider.PolicyProviderImpl"); + jacc.setPolicyConfigurationFactoryProvider("org.glassfish.exousia.modules.locked.SimplePolicyConfigurationFactory"); + jacc.setPolicyProvider("org.glassfish.exousia.modules.locked.SimplePolicyProvider"); secServ.getJaccProvider().add(jacc); return secServ; }, securityService); From 5109bce3657badfbe4b04c4d8e21f0c695b508a0 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Wed, 27 Nov 2024 21:07:57 -0600 Subject: [PATCH 20/34] FISH-8925: partially load of resources for admin console page --- .../admin/gf_template/src/main/resources/config/domain.xml | 6 ++++-- .../gf_template_web/src/main/resources/config/domain.xml | 6 ++++-- .../src/main/resources/config/domain.xml | 6 ++++-- .../src/main/resources/config/domain.xml | 6 ++++-- .../src/main/java/com/sun/web/security/RealmAdapter.java | 2 +- 5 files changed, 17 insertions(+), 9 deletions(-) diff --git a/appserver/admin/gf_template/src/main/resources/config/domain.xml b/appserver/admin/gf_template/src/main/resources/config/domain.xml index c00fa263fde..089e10bdab6 100644 --- a/appserver/admin/gf_template/src/main/resources/config/domain.xml +++ b/appserver/admin/gf_template/src/main/resources/config/domain.xml @@ -147,7 +147,7 @@ - + @@ -279,6 +279,7 @@ [Dynamic Code Evolution-11.0.10|]-XX:HotswapAgent=core [Dynamic Code Evolution-11.0.10|]-Xlog:redefine+class*=info + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy @@ -377,7 +378,7 @@ - + @@ -516,6 +517,7 @@ [Dynamic Code Evolution-11.0.10|]-XX:HotswapAgent=core [Dynamic Code Evolution-11.0.10|]-Xlog:redefine+class*=info + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy diff --git a/appserver/admin/gf_template_web/src/main/resources/config/domain.xml b/appserver/admin/gf_template_web/src/main/resources/config/domain.xml index 28804527ea1..7aea1e2a6b8 100644 --- a/appserver/admin/gf_template_web/src/main/resources/config/domain.xml +++ b/appserver/admin/gf_template_web/src/main/resources/config/domain.xml @@ -142,7 +142,7 @@ - + @@ -274,6 +274,7 @@ [Dynamic Code Evolution-11.0.10|]-XX:HotswapAgent=core [Dynamic Code Evolution-11.0.10|]-Xlog:redefine+class*=info + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy @@ -368,7 +369,7 @@ - + @@ -506,6 +507,7 @@ [Dynamic Code Evolution-11.0.10|]-XX:HotswapAgent=core [Dynamic Code Evolution-11.0.10|]-Xlog:redefine+class*=info + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy diff --git a/appserver/admin/production_domain_template/src/main/resources/config/domain.xml b/appserver/admin/production_domain_template/src/main/resources/config/domain.xml index a447b0260df..027827a7f1f 100644 --- a/appserver/admin/production_domain_template/src/main/resources/config/domain.xml +++ b/appserver/admin/production_domain_template/src/main/resources/config/domain.xml @@ -124,7 +124,7 @@ - + @@ -225,6 +225,7 @@ -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar -Djdk.attach.allowAttachSelf=true + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy @@ -328,7 +329,7 @@ - + @@ -438,6 +439,7 @@ -Dorg.jboss.weld.serialization.beanIdentifierIndexOptimization=false -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy diff --git a/appserver/admin/production_domain_template_web/src/main/resources/config/domain.xml b/appserver/admin/production_domain_template_web/src/main/resources/config/domain.xml index 11fa5ec0b00..7c58b5a0203 100644 --- a/appserver/admin/production_domain_template_web/src/main/resources/config/domain.xml +++ b/appserver/admin/production_domain_template_web/src/main/resources/config/domain.xml @@ -147,7 +147,7 @@ - + @@ -248,6 +248,7 @@ -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar -Djdk.attach.allowAttachSelf=true + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy @@ -346,7 +347,7 @@ - + @@ -455,6 +456,7 @@ -Dorg.jboss.weld.serialization.beanIdentifierIndexOptimization=false -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index 04f19d1bcad..603ae7fc4bf 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -634,7 +634,7 @@ private boolean validateRequest(HttpRequest request, HttpResponse response, Logi try { - isMandatory = this.webAuthorizationManagerService.permitAll(servletRequest); + isMandatory = !this.webAuthorizationManagerService.permitAll(servletRequest); // Produce caller challenge if call originates from HttpServletRequest#authenticate if (isMandatory || calledFromAuthenticate) { messageInfo.getMap().put(HttpServletConstants.IS_MANDATORY, Boolean.TRUE.toString()); From 849ced359b3ede2189e8fe8fb1fa2d04a2984b00 Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Thu, 28 Nov 2024 09:25:46 +0000 Subject: [PATCH 21/34] Fix missing imports --- .../ee/authorization/WebAuthorizationManagerService.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java index 2d063882807..162d9cd0036 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java @@ -48,6 +48,7 @@ import com.sun.enterprise.security.SecurityServicesUtil; import com.sun.enterprise.security.WebSecurityDeployerProbeProvider; import com.sun.enterprise.security.audit.AuditManager; +import org.glassfish.security.common.Role; import org.glassfish.security.common.UserNameAndPassword; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; @@ -77,6 +78,7 @@ import java.util.WeakHashMap; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.stream.Collectors; import javax.security.auth.Subject; import org.glassfish.exousia.AuthorizationService; From 82d35220efe42ccf5e9c9a2c56487d15c61e5f46 Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Thu, 28 Nov 2024 09:26:17 +0000 Subject: [PATCH 22/34] Fix renamed javadoc param --- .../ee/authorization/WebAuthorizationManagerService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java index 162d9cd0036..14019989042 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java @@ -293,7 +293,7 @@ public boolean hasNoConstrainedResources() { * * @param servletRequest the request that may be redirected * @param uri the request URI (minus the context path) to check - * @param method the request method to check + * @param httpMethod the request method to check * * @return 1 if access is permitted (as is or without SSL). -1 if the the access will be permitted after a redirect to * SSL. return 0 if access will be denied independent of whether a redirect to SSL is done. From a74838beb34d6b39fb63bc959619131fbd01b1c1 Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Thu, 28 Nov 2024 09:32:57 +0000 Subject: [PATCH 23/34] Fix incorrect record method names --- .../src/main/java/com/sun/web/security/RealmAdapter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index 603ae7fc4bf..3f8f1ab9015 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -846,7 +846,7 @@ private Subject reuseWebPrincipal(final WebPrincipal webPrincipal) { Set distinguishedCreds = securityContextSubject.getPublicCredentials(DistinguishedPrincipalCredential.class); if (distinguishedCreds.size() == 1) { for (DistinguishedPrincipalCredential cred : distinguishedCreds) { - if (cred.getPrincipal().equals(callerPrincipal)) { + if (cred.principal().equals(callerPrincipal)) { hasObject = true; } @@ -857,7 +857,7 @@ private Subject reuseWebPrincipal(final WebPrincipal webPrincipal) { Set distinguishedPrincipals = securityContextSubject.getPrincipals(DistinguishedPrincipalCredential.class); if (distinguishedPrincipals.size() == 1) { for (DistinguishedPrincipalCredential cred : distinguishedPrincipals) { - if (cred.getPrincipal().equals(callerPrincipal)) { + if (cred.principal().equals(callerPrincipal)) { hasObject = true; } } From 398dcbb237c236684dd2f6856ca704ff2c90b6f6 Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Thu, 28 Nov 2024 09:33:52 +0000 Subject: [PATCH 24/34] Fix incorrect javadoc --- .../src/main/java/com/sun/web/security/RealmAdapter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index 3f8f1ab9015..1044c1c2e7d 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -426,7 +426,7 @@ public SecurityConstraint[] findSecurityConstraints(String requestPathMB, String * instantiates a RealmAdapter * * @param logNull - * @return {@link webAuthorizationManagerService} or null + * @return {@link WebAuthorizationManagerService} or null */ public WebAuthorizationManagerService getWebSecurityManager(boolean logNull) { if (webAuthorizationManagerService == null && webSecurityManagerFactory != null) { From 7c726c442c4346b8a2b1031e18bedb7b92b73685 Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Thu, 28 Nov 2024 09:34:17 +0000 Subject: [PATCH 25/34] Remove unused imports --- .../src/main/java/com/sun/web/security/RealmAdapter.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index 1044c1c2e7d..3450f05a803 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -105,7 +105,6 @@ import jakarta.inject.Provider; import javax.security.auth.Subject; import jakarta.security.auth.message.AuthException; -import jakarta.security.jacc.PolicyContext; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServlet; @@ -139,7 +138,6 @@ import static com.sun.logging.LogDomains.WEB_LOGGER; import static java.lang.String.format; import static java.net.URLEncoder.encode; -import static java.security.AccessController.doPrivileged; import static java.util.Arrays.asList; import static java.util.logging.Level.*; import static jakarta.servlet.http.HttpServletResponse.*; From 58c6d120cd4991f8a53f6155e1d66489af1bfcec Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Thu, 28 Nov 2024 09:36:31 +0000 Subject: [PATCH 26/34] Remove usage of security manager --- .../java/com/sun/web/security/RealmAdapter.java | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index 3450f05a803..17f0a299c5f 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -115,10 +115,8 @@ import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; -import java.security.AccessController; import java.security.InvalidAlgorithmParameterException; import java.security.Principal; -import java.security.PrivilegedAction; import java.security.cert.X509Certificate; import java.util.Enumeration; import java.util.HashMap; @@ -1756,16 +1754,9 @@ private SecurityContext getSecurityContextForPrincipal(Principal principal) { return ((WebPrincipal) principal).getSecurityContext(); } - return AccessController.doPrivileged(new PrivilegedAction() { - - @Override - public SecurityContext run() { - Subject subject = new Subject(); - subject.getPrincipals().add(principal); - return new SecurityContext(principal.getName(), subject); - } - }); - + Subject subject = new Subject(); + subject.getPrincipals().add(principal); + return new SecurityContext(principal.getName(), subject); } public void setCurrentSecurityContextWithWebPrincipal(Principal principal) { From 4ebe3671fbf828e49e6ec95131fc12f11f8886ab Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Thu, 28 Nov 2024 09:37:37 +0000 Subject: [PATCH 27/34] Remove unused imports --- .../ee/authorization/WebAuthorizationManagerService.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java index 14019989042..efccb46682b 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java @@ -49,7 +49,6 @@ import com.sun.enterprise.security.WebSecurityDeployerProbeProvider; import com.sun.enterprise.security.audit.AuditManager; import org.glassfish.security.common.Role; -import org.glassfish.security.common.UserNameAndPassword; import com.sun.enterprise.security.ee.SecurityUtil; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; import com.sun.enterprise.security.ee.authorization.cache.CachedPermission; @@ -86,7 +85,6 @@ import static com.sun.enterprise.security.ee.authorization.GlassFishToExousiaConverter.getSecurityRoleRefsFromBundle; import static com.sun.enterprise.security.ee.authorization.cache.PermissionCacheFactory.createPermissionCache; import static java.util.logging.Level.FINE; -import static java.util.stream.Collectors.toSet; /** * This class is the entry point for authorization decisions in the web container. It implements JACC, From d600f29573b93baaa05bac5ee5a3509553b66bcb Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Thu, 28 Nov 2024 16:55:27 -0600 Subject: [PATCH 28/34] FISH-8925: changes to fix callback handler credentials validation and more removals --- .../security/AdminConsoleAuthModule.java | 4 +- appserver/security/core-ee/osgi.bundle | 3 - ...essageSecurityConfigEventListenerImpl.java | 2 +- .../BaseContainerCallbackHandler.java | 709 +----------------- .../ClientContainerCallbackHandler.java | 14 +- .../callback/ContainerCallbackHandler.java | 13 +- .../ServerContainerCallbackHandler.java | 9 +- .../jakarta/callback/ServerLoginCBHUtil.java | 76 -- .../jaspic/config/CallbackHandlerConfig.java | 50 -- .../jaspic/config/HandlerContext.java | 50 -- .../jaspic/config/HttpServletConstants.java | 56 -- .../jaspic/config/PayaraEpicyroServices.java | 75 -- .../config/PayaraEpicyroServletServices.java | 129 ---- .../security/jaspic/package-info.java | 68 -- .../com/sun/web/security/RealmAdapter.java | 3 +- .../config/SoapAuthenticationService.java | 28 +- 16 files changed, 49 insertions(+), 1240 deletions(-) rename appserver/security/core-ee/src/main/java/com/sun/enterprise/security/{jaspic => ee/authentication/jakarta}/MessageSecurityConfigEventListenerImpl.java (98%) delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerLoginCBHUtil.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/CallbackHandlerConfig.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/HandlerContext.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/HttpServletConstants.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java delete mode 100644 appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java diff --git a/appserver/admingui/common/src/main/java/org/glassfish/admingui/common/security/AdminConsoleAuthModule.java b/appserver/admingui/common/src/main/java/org/glassfish/admingui/common/security/AdminConsoleAuthModule.java index b60886fddaa..a297dbc54ad 100644 --- a/appserver/admingui/common/src/main/java/org/glassfish/admingui/common/security/AdminConsoleAuthModule.java +++ b/appserver/admingui/common/src/main/java/org/glassfish/admingui/common/security/AdminConsoleAuthModule.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package org.glassfish.admingui.common.security; @@ -244,9 +244,7 @@ public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthEx private AuthStatus doNothing(Subject clientSubject) throws AuthException { try { - // The JASPIC protocol for "do nothing" handler.handle(new Callback[] { new CallerPrincipalCallback(clientSubject, (Principal) null) }); - return SUCCESS; } catch (IOException | UnsupportedCallbackException e) { throw (AuthException) new AuthException().initCause(e); diff --git a/appserver/security/core-ee/osgi.bundle b/appserver/security/core-ee/osgi.bundle index 4757c14bb50..575d30e79ec 100644 --- a/appserver/security/core-ee/osgi.bundle +++ b/appserver/security/core-ee/osgi.bundle @@ -52,9 +52,6 @@ com.sun.enterprise.security.ee.web; \ com.sun.enterprise.security.ee.web.integration; \ com.sun.enterprise.security.jauth; \ - com.sun.enterprise.security.jaspic; \ - com.sun.enterprise.security.jaspic.callback; \ - com.sun.enterprise.security.jaspic.config; \ com.sun.enterprise.security.auth.realm.pam; \ com.sun.enterprise.security.auth.digest.impl; \ com.sun.enterprise.security.permissionsxml; \ diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/MessageSecurityConfigEventListenerImpl.java similarity index 98% rename from appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java rename to appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/MessageSecurityConfigEventListenerImpl.java index c74d027dec1..d8c9b3f3b9d 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/MessageSecurityConfigEventListenerImpl.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/MessageSecurityConfigEventListenerImpl.java @@ -39,7 +39,7 @@ */ // Portions Copyright [2016-2024] [Payara Foundation] -package com.sun.enterprise.security.jaspic; +package com.sun.enterprise.security.ee.authentication.jakarta; import static com.sun.logging.LogDomains.SECURITY_LOGGER; diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/BaseContainerCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/BaseContainerCallbackHandler.java index 9f8905cfa3d..b6c87d87d1e 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/BaseContainerCallbackHandler.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/BaseContainerCallbackHandler.java @@ -47,68 +47,26 @@ package com.sun.enterprise.security.ee.authentication.jakarta.callback; -import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityServicesUtil; -import com.sun.enterprise.security.auth.JaspicToJaasBridge; -import com.sun.enterprise.security.auth.login.DistinguishedPrincipalCredential; -import com.sun.enterprise.security.auth.login.common.LoginException; -import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; -import com.sun.enterprise.security.common.AppservAccessController; -import org.glassfish.security.common.UserNameAndPassword; -import com.sun.enterprise.security.jaspic.config.CallbackHandlerConfig; -import com.sun.enterprise.security.jaspic.config.HandlerContext; import com.sun.enterprise.security.ssl.SSLUtils; import com.sun.enterprise.security.store.PasswordAdapter; -import com.sun.enterprise.security.web.integration.WebPrincipal; import com.sun.enterprise.server.pluggable.SecuritySupport; import com.sun.logging.LogDomains; -import jakarta.security.auth.message.callback.CallerPrincipalCallback; -import jakarta.security.auth.message.callback.CertStoreCallback; -import jakarta.security.auth.message.callback.GroupPrincipalCallback; -import jakarta.security.auth.message.callback.PasswordValidationCallback; -import jakarta.security.auth.message.callback.PrivateKeyCallback; import jakarta.security.auth.message.callback.SecretKeyCallback; -import jakarta.security.auth.message.callback.TrustStoreCallback; -import org.glassfish.epicyro.config.helper.Caller; -import org.glassfish.epicyro.services.InMemoryStore; -import org.glassfish.internal.api.Globals; -import org.glassfish.security.common.Group; -import org.glassfish.security.common.MasterPassword; - -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.x500.X500Principal; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidAlgorithmParameterException; +import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStore.PrivateKeyEntry; import java.security.KeyStoreException; -import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.security.Principal; import java.security.PrivateKey; -import java.security.PrivilegedAction; -import java.security.cert.CertStore; -import java.security.cert.Certificate; -import java.security.cert.CollectionCertStoreParameters; -import java.security.cert.X509CertSelector; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Set; +import java.security.UnrecoverableKeyException; import java.util.logging.Level; import java.util.logging.Logger; - -import static com.sun.enterprise.security.SecurityContext.getDefaultCallerPrincipal; -import static com.sun.enterprise.security.common.AppservAccessController.privileged; -import static java.util.Arrays.stream; +import javax.crypto.SecretKey; +import org.glassfish.epicyro.config.helper.BaseCallbackHandler; +import org.glassfish.internal.api.Globals; +import org.glassfish.security.common.MasterPassword; /** * Base Callback Handler for Jakarta Authentication @@ -116,16 +74,13 @@ * @author Harpreet Singh * @author Shing Wai Chan */ -abstract class BaseContainerCallbackHandler implements CallbackHandler, CallbackHandlerConfig { - - private static final String DEFAULT_DIGEST_ALGORITHM = "SHA-1"; +abstract class BaseContainerCallbackHandler extends BaseCallbackHandler { + private static final String CLIENT_SECRET_KEYSTORE = "com.sun.appserv.client.secretKeyStore"; private static final String CLIENT_SECRET_KEYSTORE_PASSWORD = "com.sun.appserv.client.secretKeyStorePassword"; protected final static Logger _logger = LogDomains.getLogger(BaseContainerCallbackHandler.class, LogDomains.SECURITY_LOGGER); - - protected HandlerContext handlerContext; - + protected final SSLUtils sslUtils; protected final SecuritySupport securitySupport; protected final MasterPassword masterPasswordHelper; @@ -142,645 +97,49 @@ protected BaseContainerCallbackHandler() { masterPasswordHelper = Globals.getDefaultHabitat().getService(MasterPassword.class, "Security SSL Password Provider Service"); } } - + @Override - public void setHandlerContext(HandlerContext handlerContext) { - this.handlerContext = handlerContext; + protected KeyStore getTrustStore() { + return sslUtils.getMergedTrustStore(); } - /* - * To be implemented by a sub-class. The sub class decides which callbacks it supports. - * EjbServletWSSCallbackHandler supports:

  • SecretKeyCallback
  • TrustStoreCallback
  • - *
  • PasswordValidationCallback
  • CertStoreCallback
  • PrivateKeyCallback
  • - * AppclientWSSCallbackHandler supports:
  • NameCallback
  • PasswordCallback
  • ChoiceCallback
  • - */ - protected abstract boolean isSupportedCallback(Callback callback); - - protected abstract void handleSupportedCallbacks(Callback[] callbacks) throws IOException, UnsupportedCallbackException; - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - if (callbacks == null) { - return; - } - - for (Callback callback : callbacks) { - if (!isSupportedCallback(callback)) { - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "JASPIC: UnsupportedCallback : " + callback.getClass().getName()); - } - throw new UnsupportedCallbackException(callback); - } - } - - handleSupportedCallbacks(callbacks); - } - - /** - * gets the appropriate callback processor and hands the callback to processor to process the callback. - */ - protected void processCallback(Callback callback) throws UnsupportedCallbackException { - if (callback instanceof CallerPrincipalCallback) { - processCallerPrincipal((CallerPrincipalCallback) callback); - } else if (callback instanceof GroupPrincipalCallback) { - processGroupPrincipal((GroupPrincipalCallback) callback); - } else if (callback instanceof PasswordValidationCallback) { - processPasswordValidation((PasswordValidationCallback) callback); - } else if (callback instanceof PrivateKeyCallback) { - processPrivateKey((PrivateKeyCallback) callback); - } else if (callback instanceof TrustStoreCallback) { - TrustStoreCallback tstoreCallback = (TrustStoreCallback) callback; - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "JASPIC: In TrustStoreCallback Processor"); - } - tstoreCallback.setTrustStore(sslUtils.getMergedTrustStore()); - - } else if (callback instanceof CertStoreCallback) { - processCertStore((CertStoreCallback) callback); - } else if (callback instanceof SecretKeyCallback) { - processSecretKey((SecretKeyCallback) callback); - } else { - // sanity check =- should never come here. - // the isSupportedCallback method already takes care of this case - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "JASPIC: UnsupportedCallback : " + callback.getClass().getName()); - } - throw new UnsupportedCallbackException(callback); - } - } - - /** - * This method will distinguish the initiator principal (of the SecurityContext obtained from the WebPrincipal) as the - * caller principal, and copy all the other principals into the subject.... - * - * It is assumed that the input WebPrincipal is coming from a SAM, and that it was created either by the SAM (as - * described below) or by calls to the LoginContextDriver made by an Authenticator. - * - * A WebPrincipal constructed by the RealmAdapter will include a DPC; other constructions may not; this method - * interprets the absence of a DPC as evidence that the resulting WebPrincipal was not constructed by the RealmAdapter - * as described below. Note that presence of a DPC does not necessarily mean that the resulting WebPrincipal was - * constructed by the RealmAdapter... since some authenticators also add the credential). - * - * A. handling of CPCB by CBH: - * - * 1. handling of CPC by CBH modifies subject a. constructs UserPrincipal if called by name b. uses LoginContextDriver - * to add group principals for name c. puts principal in principal set, and DPC in public credentials - * - * B. construction of WebPrincipal by RealmAdapter (occurs after SAM uses CBH to set other than an unauthenticated - * result in the subject: - * - * a. SecurityContext construction done with subject (returned by SAM). Construction sets initiator/caller principal - * within SC from DPC set by CBH in public credentials of subject - * - * b WebPrincipal is constructed with initiator principal and SecurityContext - * - * @param fs receiving Subject - * @param wp WebPrincipal - * - * @return true when Security Context has been obtained from webPrincipal, and CB is finished. returns false when more - * CB processing is required. - */ - private boolean reuseWebPrincipal(final Subject fs, final WebPrincipal wp) { - - SecurityContext sc = wp.getSecurityContext(); - final Subject wps = sc != null ? sc.getSubject() : null; - final Principal callerPrincipal = sc != null ? sc.getCallerPrincipal() : null; - final Principal defaultPrincipal = SecurityContext.getDefaultCallerPrincipal(); - - return ((Boolean) AppservAccessController.doPrivileged(new PrivilegedAction() { - - /** - * this method uses 4 (numbered) criteria to determine if the argument WebPrincipal can be reused - */ - @Override - public Boolean run() { - - /* - * 1. WebPrincipal must contain a SecurityContext and SC must have a non-null, non-default callerPrincipal and a Subject - */ - if (callerPrincipal == null || callerPrincipal.equals(defaultPrincipal) || wps == null) { - return Boolean.FALSE; - } - - boolean hasObject = false; - Set distinguishedCreds = wps.getPublicCredentials(DistinguishedPrincipalCredential.class); - if (distinguishedCreds.size() == 1) { - for (DistinguishedPrincipalCredential cred : distinguishedCreds) { - if (cred.principal().equals(callerPrincipal)) { - hasObject = true; - } - } - } - - /** - * 2. Subject within SecurityContext must contain a single DPC that identifies the Caller Principal - */ - if (!hasObject) { - return Boolean.FALSE; - } - - hasObject = wps.getPrincipals().contains(callerPrincipal); - - /** - * 3. Subject within SecurityContext must contain the caller principal - */ - if (!hasObject) { - return Boolean.FALSE; - } - - /** - * 4. The webPrincipal must have a non null name that equals the name of the callerPrincipal. - */ - if (wp.getName() == null || !wp.getName().equals(callerPrincipal.getName())) { - return Boolean.FALSE; - } - - /* - * remove any existing DistinguishedPrincipalCredentials from receiving Subject - * - */ - Iterator iter = fs.getPublicCredentials().iterator(); - while (iter.hasNext()) { - Object obj = iter.next(); - if (obj instanceof DistinguishedPrincipalCredential) { - iter.remove(); - } - } - - /** - * Copy principals from Subject within SecurityContext to receiving Subject - */ - - for (Principal p : wps.getPrincipals()) { - fs.getPrincipals().add(p); - } - - /** - * Copy public credentials from Subject within SecurityContext to receiving Subject - */ - for (Object publicCred : wps.getPublicCredentials()) { - fs.getPublicCredentials().add(publicCred); - } - - /** - * Copy private credentials from Subject within SecurityContext to receiving Subject - */ - for (Object privateCred : wps.getPrivateCredentials()) { - fs.getPrivateCredentials().add(privateCred); - } - - return Boolean.TRUE; - } - })).booleanValue(); - } - - private void processCallerPrincipal(CallerPrincipalCallback callerPrincipalCallback) { - Subject subject = callerPrincipalCallback.getSubject(); - Principal principal = callerPrincipalCallback.getPrincipal(); - - // PAYARA-755 If the SAM has set a custom principal then we check that the original WebPrincipal has - // the same custom principal within it - if (principal != null && !(principal instanceof WebPrincipal)) { - Principal additional = SecurityContext.getCurrent().getAdditionalPrincipal(); - if ((additional != null) && (additional instanceof WebPrincipal) - && ((WebPrincipal) additional).getCustomPrincipal() == principal) { - principal = additional; - } - } - - if (principal instanceof WebPrincipal) { - WebPrincipal webPrincipal = (WebPrincipal) principal; - - /** - * Check if the WebPrincipal satisfies the criteria for reuse. If it does, the CBH will have already - * copied its contents into the Subject, and established the caller principal. - */ - if (reuseWebPrincipal(subject, webPrincipal)) { - return; - } - - /** - * Otherwise the webPrincipal must be distinguished as the callerPrincipal, but the contents of its - * internal SecurityContext will not be copied. For the special case where the WebPrincipal - * represents the defaultCallerPrincipal, the argument principal is set to null to cause the handler - * to assign its representation of the unauthenticated caller in the Subject. - */ - Principal defaultCallerPrincipal = SecurityContext.getDefaultCallerPrincipal(); - SecurityContext securityContext = webPrincipal.getSecurityContext(); - Principal callerPrincipal = securityContext != null ? securityContext.getCallerPrincipal() : null; - - if (webPrincipal.getName() == null || webPrincipal.equals(defaultCallerPrincipal) || callerPrincipal == null || callerPrincipal.equals(defaultCallerPrincipal)) { - principal = null; - } - } - - String realmName = null; - if (handlerContext != null) { - realmName = handlerContext.getRealmName(); - } - - boolean isCertRealm = CertificateRealm.AUTH_TYPE.equals(realmName); - if (principal == null) { - if (callerPrincipalCallback.getName() != null) { - if (isCertRealm) { - principal = new X500Principal(callerPrincipalCallback.getName()); - } else { - principal = new UserNameAndPassword(callerPrincipalCallback.getName()); - } - } else { - // Jakarta Authentication unauthenticated caller principal - principal = SecurityContext.getDefaultCallerPrincipal(); - } - } - - if (isCertRealm) { - if (principal instanceof X500Principal) { - JaspicToJaasBridge.jaasX500Login(subject, (X500Principal) principal); - } - } else { - if (!principal.equals(getDefaultCallerPrincipal())) { - JaspicToJaasBridge.addRealmGroupsToSubject(subject, principal.getName(), realmName); - } - } - - final Principal finalPrincipal = principal; - DistinguishedPrincipalCredential distinguishedPrincipalCredential = new DistinguishedPrincipalCredential(principal); - - privileged(() -> { - subject.getPrincipals().add(finalPrincipal); - - Iterator publicCredentials = subject.getPublicCredentials().iterator(); - while (publicCredentials.hasNext()) { - if (publicCredentials.next() instanceof DistinguishedPrincipalCredential) { - publicCredentials.remove(); - } - } - - subject.getPublicCredentials().add(distinguishedPrincipalCredential); - }); + protected KeyStore[] getKeyStores() { + return securitySupport.getKeyStores(); } - private void processGroupPrincipal(GroupPrincipalCallback groupCallback) { - Subject subject = groupCallback.getSubject(); - String[] groups = groupCallback.getGroups(); - - if (groups != null && groups.length > 0) { - privileged(() -> stream(groups).forEach(group -> subject.getPrincipals().add(new Group(group)))); - } else if (groups == null) { - privileged(() -> subject.getPrincipals().removeAll(subject.getPrincipals(Group.class))); - } - } - - protected void processPasswordValidation(PasswordValidationCallback pwdCallback) { - /*if (SecurityServicesUtil.getInstance().isACC()) { - _logger.log(Level.FINE, "JASPIC: In PasswordValidationCallback Processor for appclient - will do nothing"); - pwdCallback.setResult(true); - return; - } - String username = pwdCallback.getUsername(); - - char[] passwd = pwdCallback.getPassword(); - - _logger.log(Level.FINE, "JASPIC: In PasswordValidationCallback Processor"); - - try { - String realmName = null; - if (handlerContext != null) { - realmName = handlerContext.getRealmName(); - } - - JaspicToJaasBridge.validateUsernamePasswordByJaas(pwdCallback.getSubject(), username, passwd, realmName); - - _logger.log(Level.FINE, "JASPIC: authentication succeeded for user = ", username); - - // Explicitly ditch the password - if (passwd != null) { - for (int i = 0; i < passwd.length; i++) - passwd[i] = ' '; - } - - pwdCallback.setResult(true); - } catch (LoginException le) { - // login failed - _logger.log(Level.INFO, "jaspic.loginfail", username); - pwdCallback.setResult(false); - }*/ - // Default to a very basic in memory identity store. - // Clients may want to override this for more advanced features. - Caller caller = InMemoryStore.validate(pwdCallback.getUsername(), getPassword(pwdCallback)); - if (caller != null) { - processCallerPrincipal(new CallerPrincipalCallback(pwdCallback.getSubject(), caller.getCallerPrincipal())); - if (!caller.getGroups().isEmpty()) { - processGroupPrincipal(new GroupPrincipalCallback(pwdCallback.getSubject(), caller.getGroupsAsArray())); - } - pwdCallback.setResult(true); - } + @Override + protected PrivateKey getPrivateKeyForAlias(String alias, int keystoreIndex) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { + return securitySupport.getPrivateKeyForAlias(alias, keystoreIndex); } - private String getPassword(PasswordValidationCallback pwdCallback) { - char[] password = pwdCallback.getPassword(); - if (password == null) { - return null; - } - - return new String(password); + @Override + protected PrivateKeyEntry getPrivateKeyEntryFromTokenAlias(String certNickname) throws Exception { + return sslUtils.getPrivateKeyEntryFromTokenAlias(certNickname); } - private void processPrivateKey(PrivateKeyCallback privKeyCallback) { - KeyStore[] keyStores = securitySupport.getKeyStores(); - _logger.log(Level.FINE, "JASPIC: In PrivateKeyCallback Processor"); - - // Make sure we have a keystore - if (keyStores == null || keyStores.length == 0) { - // cannot get any information - privKeyCallback.setKey(null, null); - return; - } - - // get the request type - PrivateKeyCallback.Request request = privKeyCallback.getRequest(); - PrivateKey privateKey = null; - Certificate[] certificateChain = null; - if (request == null) { - // no request type - set default key - PrivateKeyEntry privateKeyEntry = getDefaultPrivateKeyEntry(keyStores); - if (privateKeyEntry != null) { - privateKey = privateKeyEntry.getPrivateKey(); - certificateChain = privateKeyEntry.getCertificateChain(); - } - privKeyCallback.setKey(privateKey, certificateChain); - return; - } + @Override + protected SecretKey getPasswordSecretKeyForAlias(String alias) throws GeneralSecurityException { + PasswordAdapter passwordAdapter = null; - // find key based on request type try { - if (request instanceof PrivateKeyCallback.AliasRequest) { - PrivateKeyCallback.AliasRequest aliasRequest = (PrivateKeyCallback.AliasRequest) request; - - String alias = aliasRequest.getAlias(); - PrivateKeyEntry privKeyEntry; - - if (alias == null) { - // use default key - privKeyEntry = getDefaultPrivateKeyEntry(keyStores); - } else { - privKeyEntry = sslUtils.getPrivateKeyEntryFromTokenAlias(alias); - } - - if (privKeyEntry != null) { - privateKey = privKeyEntry.getPrivateKey(); - certificateChain = privKeyEntry.getCertificateChain(); - } - } else if (request instanceof PrivateKeyCallback.IssuerSerialNumRequest) { - PrivateKeyCallback.IssuerSerialNumRequest issuerSerialNumRequest = (PrivateKeyCallback.IssuerSerialNumRequest) request; - - X500Principal issuer = issuerSerialNumRequest.getIssuer(); - BigInteger serialNum = issuerSerialNumRequest.getSerialNum(); - - if (issuer != null && serialNum != null) { - boolean found = false; - for (int i = 0; i < keyStores.length && !found; i++) { - Enumeration aliases = keyStores[i].aliases(); - while (aliases.hasMoreElements() && !found) { - String nextAlias = aliases.nextElement(); - PrivateKey key = securitySupport.getPrivateKeyForAlias(nextAlias, i); - if (key != null) { - Certificate[] certificates = keyStores[i].getCertificateChain(nextAlias); - // check issuer/serial - X509Certificate eeCert = (X509Certificate) certificates[0]; - if (eeCert.getIssuerX500Principal().equals(issuer) && eeCert.getSerialNumber().equals(serialNum)) { - privateKey = key; - certificateChain = certificates; - found = true; - } - } - } - } - } - } else if (request instanceof PrivateKeyCallback.SubjectKeyIDRequest) { - PrivateKeyCallback.SubjectKeyIDRequest subjectKeyIDRequest = (PrivateKeyCallback.SubjectKeyIDRequest) request; - byte[] subjectKeyID = subjectKeyIDRequest.getSubjectKeyID(); - - if (subjectKeyID != null) { - boolean found = false; - - X509CertSelector selector = new X509CertSelector(); - selector.setSubjectKeyIdentifier(toDerOctetString(subjectKeyID)); - - for (int i = 0; i < keyStores.length && !found; i++) { - Enumeration aliases = keyStores[i].aliases(); - while (aliases.hasMoreElements() && !found) { - String nextAlias = aliases.nextElement(); - PrivateKey key = securitySupport.getPrivateKeyForAlias(nextAlias, i); - - if (key != null) { - Certificate[] certificates = keyStores[i].getCertificateChain(nextAlias); - - if (selector.match(certificates[0])) { - privateKey = key; - certificateChain = certificates; - found = true; - } - } - } - } - } - } else if (request instanceof PrivateKeyCallback.DigestRequest) { - PrivateKeyCallback.DigestRequest digestRequest = (PrivateKeyCallback.DigestRequest) request; - byte[] digest = digestRequest.getDigest(); - String algorithm = digestRequest.getAlgorithm(); - - PrivateKeyEntry privateKeyEntry = null; - if (digest == null) { - // get default key - privateKeyEntry = getDefaultPrivateKeyEntry(keyStores); - } else { - if (algorithm == null) { - algorithm = DEFAULT_DIGEST_ALGORITHM; - } - MessageDigest messageDigest = MessageDigest.getInstance(algorithm); - privateKeyEntry = getPrivateKeyEntry(keyStores, messageDigest, digest); - } - - if (privateKeyEntry != null) { - privateKey = privateKeyEntry.getPrivateKey(); - certificateChain = privateKeyEntry.getCertificateChain(); - } + if (SecurityServicesUtil.getInstance().isACC()) { + passwordAdapter = new PasswordAdapter( + System.getProperty(CLIENT_SECRET_KEYSTORE), + System.getProperty(CLIENT_SECRET_KEYSTORE_PASSWORD).toCharArray()); } else { - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "invalid request type: " + request.getClass().getName()); - } - } - } catch (Exception e) { - // UnrecoverableKeyException - // NoSuchAlgorithmException - // KeyStoreException - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "JASPIC: In PrivateKeyCallback Processor: " + " Error reading key !", e); - } - } finally { - privKeyCallback.setKey(privateKey, certificateChain); + passwordAdapter = masterPasswordHelper.getMasterPasswordAdapter(); + }} + catch (IOException e) { + throw new GeneralSecurityException(e); } - } - - private byte[] toDerOctetString(byte[] value) throws IOException { - ByteArrayOutputStream subjectOutputStream = new ByteArrayOutputStream(); - - subjectOutputStream.write(0x04); // DER Octet String tag - subjectOutputStream.write(length2Bytes(value.length)); - subjectOutputStream.write(value); - - return subjectOutputStream.toByteArray(); - } - - /** - * Splits out an integer into a variable number of bytes with the first byte containing either - * the number of bytes, or the integer itself if small enough. - * - * @param length the integer to convert - * @return the integer in DER byte array form - */ - private byte[] length2Bytes(int length) { - // The first byte with the MSB bit a 0 encodes the direct length - // E.g. 0b00000001 for length = 1 - if (length <= 127) { - return new byte[] { (byte) length }; - } - - // Count how many bytes are in the "length" integer - int byteCount = 1; - int lengthValue = length; - - while ((lengthValue >>>= 8) != 0) { - byteCount++; - } - - byte[] lengthBytes = new byte[byteCount + 1]; - // The first byte with the MSB bit a 1 encodes the number of bytes used for the length - // E.g. 0b10000001 for 1 additional byte (for values up to 255) - lengthBytes[0] = (byte) (byteCount | 0b10000000); - - // Shift the integer in increments of 8 bits, and truncate the lowest 8 ones in every iteration. - // For numbers up to 255 shift 0 times, e.g. for length 255 take the binary version 0b11111111 directly. - // For numbers up to 65535 shift 1 time, e.g. for length 256 - // first byte = 0b100000000 >> 8 = 0b000000001 -> 0b00000001 - // second byte = 0b100000000 >> 0 = 0b000000000 -> 0b00000000 - int pos = 1; - for (int i = (byteCount - 1) * 8; i >= 0; i -= 8) { - lengthBytes[pos] = (byte) (length >> i); - pos++; - } - - return lengthBytes; - } - - /** - * Return the first key/chain that we can successfully get out of the keystore - */ - private PrivateKeyEntry getDefaultPrivateKeyEntry(KeyStore[] keyStores) { - PrivateKey privateKey = null; - Certificate[] certificates = null; - try { - for (int i = 0; i < keyStores.length && privateKey == null; i++) { - Enumeration aliases = keyStores[i].aliases(); - // loop thru aliases and try to get the key/chain - while (aliases.hasMoreElements() && privateKey == null) { - String nextAlias = (String) aliases.nextElement(); - privateKey = null; - certificates = null; - PrivateKey key = securitySupport.getPrivateKeyForAlias(nextAlias, i); - if (key != null) { - privateKey = key; - certificates = keyStores[i].getCertificateChain(nextAlias); - } - } - } - } catch (Exception e) { - // UnrecoverableKeyException - // NoSuchAlgorithmException - // KeyStoreException - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "Exception in getDefaultPrivateKeyEntry", e); - } - } - - return new PrivateKeyEntry(privateKey, certificates); - } - - private PrivateKeyEntry getPrivateKeyEntry(KeyStore[] kstores, MessageDigest md, byte[] digest) { - PrivateKey privKey = null; - Certificate[] certs = null; - try { - for (int i = 0; i < kstores.length && privKey == null; i++) { - Enumeration aliases = kstores[i].aliases(); - // loop thru aliases and try to get the key/chain - while (aliases.hasMoreElements() && privKey == null) { - String nextAlias = (String) aliases.nextElement(); - privKey = null; - certs = null; - PrivateKey key = securitySupport.getPrivateKeyForAlias(nextAlias, i); - if (key != null) { - certs = kstores[i].getCertificateChain(nextAlias); - md.reset(); - byte[] cDigest = md.digest(certs[0].getEncoded()); - if (Arrays.equals(digest, cDigest)) { - privKey = key; - } - } - } - } - } catch (Exception e) { - // UnrecoverableKeyException - // NoSuchAlgorithmException - // KeyStoreException - _logger.log(Level.FINE, "Exception in getPrivateKeyEntry for Digest", e); - } - - return new PrivateKeyEntry(privKey, certs); - } - - private void processCertStore(CertStoreCallback certStoreCallback) { - _logger.log(Level.FINE, "JASPIC: In CertStoreCallback Processor"); - - KeyStore certStore = sslUtils.getMergedTrustStore(); - if (certStore == null) {// should never happen - certStoreCallback.setCertStore(null); - } - - List list = new ArrayList(); - CollectionCertStoreParameters ccsp; - try { - if (certStore != null) { - Enumeration enu = certStore.aliases(); - while (enu.hasMoreElements()) { - String alias = enu.nextElement(); - if (certStore.isCertificateEntry(alias)) { - try { - Certificate cert = certStore.getCertificate(alias); - list.add(cert); - } catch (KeyStoreException kse) { - // ignore and move to next - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "JASPIC: Cannot retrieve certificate for alias " + alias); - } - } - } - } - } - ccsp = new CollectionCertStoreParameters(list); - CertStore certstore = CertStore.getInstance("Collection", ccsp); - certStoreCallback.setCertStore(certstore); - } catch (KeyStoreException kse) { - _logger.log(Level.FINE, "JASPIC: Cannot determine truststore aliases", kse); - } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException iape) { - _logger.log(Level.FINE, "JASPIC: Cannot instantiate CertStore", iape); - } + return passwordAdapter.getPasswordSecretKeyForAlias(alias); } - private void processSecretKey(SecretKeyCallback secretKeyCallback) { + protected void processSecretKey(SecretKeyCallback secretKeyCallback) { if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "JASPIC: In SecretKeyCallback Processor"); + _logger.log(Level.FINE, "Jakarta Authentication: In SecretKeyCallback Processor"); } String alias = ((SecretKeyCallback.AliasRequest) secretKeyCallback.getRequest()).getAlias(); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ClientContainerCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ClientContainerCallbackHandler.java index c06ae885df7..298519ec02e 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ClientContainerCallbackHandler.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ClientContainerCallbackHandler.java @@ -134,7 +134,6 @@ protected void handleSupportedCallbacks(Callback[] callbacks) throws IOException // Let control flow to the callback processors callbackHandler.handle(callbacks); } - processedSomeAppclientCallbacks = true; break; } @@ -146,15 +145,10 @@ protected void handleSupportedCallbacks(Callback[] callbacks) throws IOException } protected boolean isSupportedCallback(Callback callback) { - return callback instanceof NameCallback - || callback instanceof PasswordCallback - || callback instanceof ChoiceCallback - || callback instanceof CallerPrincipalCallback - || callback instanceof GroupPrincipalCallback - || callback instanceof CertStoreCallback - || callback instanceof PasswordValidationCallback - || callback instanceof SecretKeyCallback - || callback instanceof PrivateKeyCallback + return callback instanceof NameCallback || callback instanceof PasswordCallback || callback instanceof ChoiceCallback + || callback instanceof CallerPrincipalCallback || callback instanceof GroupPrincipalCallback + || callback instanceof CertStoreCallback || callback instanceof PasswordValidationCallback + || callback instanceof SecretKeyCallback || callback instanceof PrivateKeyCallback || callback instanceof TrustStoreCallback; } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ContainerCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ContainerCallbackHandler.java index 75fcafaaee8..3ac38863975 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ContainerCallbackHandler.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ContainerCallbackHandler.java @@ -48,8 +48,6 @@ package com.sun.enterprise.security.ee.authentication.jakarta.callback; import com.sun.enterprise.security.SecurityServicesUtil; -import com.sun.enterprise.security.jaspic.config.CallbackHandlerConfig; -import com.sun.enterprise.security.jaspic.config.HandlerContext; import java.io.IOException; @@ -66,7 +64,7 @@ */ @Service @ContractsProvided({ ContainerCallbackHandler.class, CallbackHandler.class }) -public final class ContainerCallbackHandler implements CallbackHandler, CallbackHandlerConfig { +public final class ContainerCallbackHandler implements CallbackHandler { private final CallbackHandler handler; @@ -81,12 +79,5 @@ public ContainerCallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { handler.handle(callbacks); } - - public void setHandlerContext(HandlerContext handlerContext) { - ((CallbackHandlerConfig) handler).setHandlerContext(handlerContext); - } - - public void setHandlerContext(String realm) { - ((BaseContainerCallbackHandler) handler).setHandlerContext(() -> realm); - } + } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerContainerCallbackHandler.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerContainerCallbackHandler.java index 001d90b6a6f..12c02ce0036 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerContainerCallbackHandler.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerContainerCallbackHandler.java @@ -85,12 +85,9 @@ protected void handleSupportedCallbacks(Callback[] callbacks) throws IOException } protected boolean isSupportedCallback(Callback callback) { - return callback instanceof CertStoreCallback - || callback instanceof PasswordValidationCallback - || callback instanceof CallerPrincipalCallback - || callback instanceof GroupPrincipalCallback - || callback instanceof SecretKeyCallback - || callback instanceof PrivateKeyCallback + return callback instanceof CertStoreCallback || callback instanceof PasswordValidationCallback + || callback instanceof CallerPrincipalCallback || callback instanceof GroupPrincipalCallback + || callback instanceof SecretKeyCallback || callback instanceof PrivateKeyCallback || callback instanceof TrustStoreCallback; } diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerLoginCBHUtil.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerLoginCBHUtil.java deleted file mode 100644 index 2f144cb935e..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authentication/jakarta/callback/ServerLoginCBHUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.ee.authentication.jakarta.callback; - -import static com.sun.enterprise.security.common.AppservAccessController.privileged; -import static java.util.Arrays.stream; - -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import jakarta.security.auth.message.callback.GroupPrincipalCallback; - -import org.glassfish.security.common.Group; - -/** - * - * @author vbkumarjayanti - */ -public class ServerLoginCBHUtil { - - private static void processGP(GroupPrincipalCallback groupCallback) { - Subject subject = groupCallback.getSubject(); - String[] groups = groupCallback.getGroups(); - - if (groups != null && groups.length > 0) { - privileged(() -> stream(groups).forEach(group -> subject.getPrincipals().add(new Group(group)))); - } else if (groups == null) { - privileged(() -> subject.getPrincipals().removeAll(subject.getPrincipals(Group.class))); - } - } - - // NOTE: this method is called by reflection from ServerLoginCallbackHandler - public static void processGroupPrincipal(Callback groupCallback) { - if (groupCallback instanceof GroupPrincipalCallback) { - processGP((GroupPrincipalCallback) groupCallback); - } - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/CallbackHandlerConfig.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/CallbackHandlerConfig.java deleted file mode 100644 index 7e5c12b7b7f..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/CallbackHandlerConfig.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -/** - * This is an interface for our callback handler configuration. - * - * @author Shing Wai Chan - */ -public interface CallbackHandlerConfig { - void setHandlerContext(HandlerContext handlerContext); -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/HandlerContext.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/HandlerContext.java deleted file mode 100644 index 8be46a84520..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/HandlerContext.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -/** - * This is an interface for our callback handler context. - * - * @author Shing Wai Chan - */ -public interface HandlerContext { - String getRealmName(); -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/HttpServletConstants.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/HttpServletConstants.java deleted file mode 100644 index bb495db3ab7..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/HttpServletConstants.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -/** - * This is used to do HttpServlet security for app server - */ -public class HttpServletConstants { - public static final String AUTH_TYPE = "jakarta.servlet.http.authType"; - public static final String WEB_BUNDLE = "WEB_BUNDLE"; - public static final String POLICY_CONTEXT = "jakarta.security.jacc.PolicyContext"; - public static final String IS_MANDATORY = "jakarta.security.auth.message.MessagePolicy.isMandatory"; - public static final String REGISTER_SESSION = "jakarta.servlet.http.registerSession"; - @Deprecated public static final String REGISTER_WITH_AUTHENTICATOR = "com.sun.web.RealmAdapter.register"; - - private HttpServletConstants() { - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java deleted file mode 100644 index dd401546776..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServices.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; - -import org.glassfish.epicyro.config.helper.AuthMessagePolicy; -import org.glassfish.epicyro.services.BaseAuthenticationService; - -/** - * This is based Helper class for 196 Configuration. - */ -public abstract class PayaraEpicyroServices extends BaseAuthenticationService { - - /** - * Get the default callback handler - */ - public CallbackHandler getCallbackHandler() { - CallbackHandler callbackHandler = AuthMessagePolicy.getDefaultCallbackHandler(); - - if (callbackHandler instanceof CallbackHandlerConfig) { - ((CallbackHandlerConfig) callbackHandler).setHandlerContext(getHandlerContext(map)); - } - - return callbackHandler; - } - - /** - * This method is invoked by the constructor and should be overridden by a subclass. - */ - protected HandlerContext getHandlerContext(Map map) { - return null; - } - -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java deleted file mode 100644 index cfc6b397dde..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/config/PayaraEpicyroServletServices.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ -// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] -package com.sun.enterprise.security.jaspic.config; - -import static com.sun.enterprise.deployment.web.LoginConfiguration.CLIENT_CERTIFICATION_AUTHENTICATION; - -import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; -import com.sun.enterprise.security.ee.authorization.WebAuthorizationManagerService; -import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.POLICY_CONTEXT; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.WEB_BUNDLE; - -import java.util.HashMap; -import java.util.Map; - -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.config.AuthConfigProvider; - -import com.sun.enterprise.deployment.WebBundleDescriptor; -import com.sun.enterprise.deployment.runtime.web.SunWebApp; -import com.sun.enterprise.deployment.web.LoginConfiguration; -import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; -import org.glassfish.internal.api.Globals; - -public class PayaraEpicyroServletServices extends PayaraEpicyroServices { - - public static final String AUTH_TYPE = "jakarta.servlet.http.authType"; - - public static final String HTTPSERVLET = "HttpServlet"; - - private String realmName; - - public PayaraEpicyroServletServices(String appContext, Map map, CallbackHandler callbackHandler, String realmName, boolean isSystemApp, String defaultSystemProviderID) { - - WebBundleDescriptor webBundle = null; - - if (map != null) { - webBundle = (WebBundleDescriptor) map.get(WEB_BUNDLE); - if (webBundle != null) { - LoginConfiguration loginConfig = webBundle.getLoginConfiguration(); - if (loginConfig != null - && CLIENT_CERTIFICATION_AUTHENTICATION.equals(loginConfig.getAuthenticationMethod())) { - this.realmName = CertificateRealm.AUTH_TYPE; - } else { - this.realmName = realmName; - } - } - } - - // Set realmName before init - init(HTTPSERVLET, appContext, map, callbackHandler, null); - - if (webBundle != null) { - String policyContextId = WebAuthorizationManagerService.getContextID(webBundle); - map.put(POLICY_CONTEXT, policyContextId); - - SunWebApp sunWebApp = webBundle.getSunDescriptor(); - String pid = (sunWebApp != null ? sunWebApp.getAttributeValue(sunWebApp.HTTPSERVLET_SECURITY_PROVIDER) : null); - boolean nullConfigProvider = false; - - if (isSystemApp && (pid == null || pid.length() == 0)) { - pid = defaultSystemProviderID; - if (pid == null || pid.length() == 0) { - nullConfigProvider = true; - } - } - - if (((pid != null && pid.length() > 0) || nullConfigProvider) && !hasExactMatchAuthProvider()) { - AuthConfigProvider configProvider = nullConfigProvider ? null : new GFServerConfigProvider(new HashMap<>(), null); - - // Register the Payara JASPIC provider - - String jaspicRegistrationId = authConfigFactory.registerConfigProvider( - configProvider, HTTPSERVLET, appContext, - "Payara provider: " + HTTPSERVLET + ":" + appContext); - - setRegistrationId(jaspicRegistrationId); - } - } - - } - - // realmName must be set first and this is invoked inside the init() - protected HandlerContext getHandlerContext(Map map) { - return new HandlerContext() { - public String getRealmName() { - return realmName; - } - }; - } -} diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java deleted file mode 100644 index 474634b9976..00000000000 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jaspic/package-info.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) [2019-2024] Payara Foundation and/or its affiliates. - * All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://github.com/payara/Payara/blob/main/LICENSE.txt - * See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at glassfish/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * The Payara Foundation designates this particular file as subject to the - * "Classpath" exception as provided by the Payara Foundation in the GPL - * Version 2 section of the License file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -/** - * This package contains much of the integration code for JASPIC. - * - *

    - * JASPIC is the EE standard for taking care of the authentication aspects - * of security. It allows for users to supply pluggable custom authentication mechanisms called SAMs - * {@link jakarta.security.auth.message.module.ServerAuthModule}. - * - *

    - * Unlike Servlet or EE Security there are no default authentication mechanisms in JASPIC. - * - *

    - * Code in this package builds upon the general (server independent) JASPIC Provider - * Framework Reference Implementation. - * It adds to this framework by implementing the Payara specific bits. - * - *

    - * For Web/Servlet requests the authentication code is called from Catalina (Tomcat) via - * com.sun.web.security.RealmAdapter and then com.sun.web.security.realmadapter.JaspicRealm. - * - *

    - * The pluggable authentication mechanisms are managed by the - * {@link jakarta.security.auth.message.config.AuthConfigFactory}. The Payara specific implementation of this is - * com.sun.enterprise.security.ee.JavaEESecurityLifecycle. - * - */ -package com.sun.enterprise.security.jaspic; \ No newline at end of file diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index 17f0a299c5f..ac1e33d6bc7 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -131,7 +131,7 @@ import static com.sun.enterprise.security.SecurityContext.setUnauthenticatedContext; import static com.sun.enterprise.security.auth.digest.api.Constants.A1; import static com.sun.enterprise.security.auth.digest.impl.DigestParameterGenerator.HTTP_DIGEST; -import static com.sun.enterprise.security.jaspic.config.HttpServletConstants.REGISTER_WITH_AUTHENTICATOR; + import static com.sun.enterprise.util.Utility.isAllNull; import static com.sun.logging.LogDomains.WEB_LOGGER; import static java.lang.String.format; @@ -168,6 +168,7 @@ public class RealmAdapter extends RealmBase implements RealmInitializer, PostCon private static final Logger LOG = LogDomains.getLogger(RealmAdapter.class, WEB_LOGGER); private static final ResourceBundle resourceBundle = LOG.getResourceBundle(); + private static final String REGISTER_WITH_AUTHENTICATOR = "com.sun.web.RealmAdapter.register"; public static final String SERVER_AUTH_CONTEXT = "__jakarta.security.auth.message.ServerAuthContext"; private static final String MESSAGE_INFO = "__jakarta.security.auth.message.MessageInfo"; diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java index 383ee2da179..438296b47b3 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java @@ -77,6 +77,7 @@ import org.glassfish.api.invocation.InvocationManager; import org.glassfish.deployment.common.ModuleDescriptor; import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; +import org.glassfish.epicyro.services.BaseAuthenticationService; import org.glassfish.epicyro.services.RegistrationWrapperRemover; import org.glassfish.internal.api.Globals; @@ -95,8 +96,6 @@ import com.sun.enterprise.security.ee.audit.AppServerAuditManager; import com.sun.enterprise.security.ee.authorization.EJBPolicyContextDelegate; import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; -import com.sun.enterprise.security.jaspic.config.HandlerContext; -import com.sun.enterprise.security.jaspic.config.PayaraEpicyroServices; import com.sun.enterprise.security.webservices.PipeConstants; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.io.FileUtils; @@ -111,7 +110,7 @@ import com.sun.xml.ws.api.model.wsdl.WSDLPort; import com.sun.xml.ws.api.server.WSEndpoint; -public class SoapAuthenticationService extends PayaraEpicyroServices { +public class SoapAuthenticationService extends BaseAuthenticationService { protected static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(PipeConstants.class); @@ -383,29 +382,6 @@ public void disable() { getRegistrationWrapper().disableWithRefCount(); } - @Override - protected HandlerContext getHandlerContext(Map map) { - String realmName = null; - WebServiceEndpoint wSE = (WebServiceEndpoint) map.get(PipeConstants.SERVICE_ENDPOINT); - if (wSE != null) { - Application app = wSE.getBundleDescriptor().getApplication(); - if (app != null) { - realmName = app.getRealm(); - } - if (realmName == null) { - realmName = wSE.getRealm(); - } - } - - final String fRealmName = realmName; - return new HandlerContext() { - @Override - public String getRealmName() { - return fRealmName; - } - }; - } - private boolean processSunDeploymentDescriptor() { if (authConfigFactory == null) { return false; From cf189d1c33d6228f7c97036814394fba7c28da6d Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Mon, 2 Dec 2024 10:45:02 +0000 Subject: [PATCH 29/34] Don't exclude from semantic versioning Signed-off-by: Andrew Pielage --- core/core-parent/pom.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/core-parent/pom.xml b/core/core-parent/pom.xml index dcaa351d5e0..b8f77ac8617 100644 --- a/core/core-parent/pom.xml +++ b/core/core-parent/pom.xml @@ -617,8 +617,6 @@ io.opentelemetry.extension io.opentelemetry.instrumentation fish.payara.shaded - com.sun.enterprise.security - com.sun.jaspic.services From 3032e36b80a8ce7be512bceb09ac40d16432d897 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Mon, 2 Dec 2024 19:26:36 -0600 Subject: [PATCH 30/34] FISH-8925: fix for invalid reference for policy and code removals for SecurityManager --- .../managedbean/ManagedBeanManagerImpl.java | 58 ++- .../impl/util/InjectionManagerImpl.java | 94 ++--- .../naming/GlassFishNamingBuilder.java | 81 +--- .../src/main/java/com/sun/ejb/EJBUtils.java | 369 ++++++++---------- .../com/sun/ejb/containers/BaseContainer.java | 264 +++++-------- .../containers/StatefulSessionContainer.java | 70 ++-- .../containers/StatelessContainerFactory.java | 7 +- .../store/adapter/file/FileBackingStore.java | 36 +- .../iiop/impl/POARemoteReferenceFactory.java | 92 ++--- .../generator/database/MappingPolicy.java | 39 +- .../common/database/PropertyHelper.java | 61 +-- .../entitybean/container/EntityContainer.java | 62 +-- .../DistributedReadOnlyBeanServiceImpl.java | 33 +- .../ee/auth/login/ProgrammaticLogin.java | 180 ++++----- .../authorization/cache/PermissionCache.java | 25 +- .../security/ConnectionExecutionContext.java | 12 +- .../security/SecClientRequestInterceptor.java | 59 ++- .../security/SecServerRequestInterceptor.java | 38 +- .../iiop/security/SecurityContextUtil.java | 60 ++- .../com/sun/web/security/RealmAdapter.java | 4 +- .../config/SoapAuthenticationService.java | 96 ++--- .../enterprise/security/SecurityContext.java | 175 +++------ .../security/SecurityLoggerInfo.java | 9 +- .../auth/login/LoginContextDriver.java | 10 +- .../security/ssl/J2EEKeyManager.java | 170 +++----- 25 files changed, 756 insertions(+), 1348 deletions(-) diff --git a/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/managedbean/ManagedBeanManagerImpl.java b/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/managedbean/ManagedBeanManagerImpl.java index 95253b50efc..9c2fcc8e3f1 100644 --- a/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/managedbean/ManagedBeanManagerImpl.java +++ b/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/managedbean/ManagedBeanManagerImpl.java @@ -37,16 +37,34 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation] +// Portions Copyright [2016-2024] [Payara Foundation] package com.sun.enterprise.container.common.impl.managedbean; +import com.sun.enterprise.container.common.spi.InterceptorInvoker; +import com.sun.enterprise.container.common.spi.JCDIService; +import com.sun.enterprise.container.common.spi.JavaEEInterceptorBuilder; +import com.sun.enterprise.container.common.spi.JavaEEInterceptorBuilderFactory; +import com.sun.enterprise.container.common.spi.ManagedBeanManager; +import com.sun.enterprise.container.common.spi.util.ComponentEnvManager; +import com.sun.enterprise.container.common.spi.util.InjectionManager; +import com.sun.enterprise.container.common.spi.util.InterceptorInfo; +import com.sun.enterprise.deployment.Application; +import com.sun.enterprise.deployment.ApplicationClientDescriptor; +import com.sun.enterprise.deployment.BundleDescriptor; +import com.sun.enterprise.deployment.EjbBundleDescriptor; +import com.sun.enterprise.deployment.EjbDescriptor; +import com.sun.enterprise.deployment.InterceptorDescriptor; +import com.sun.enterprise.deployment.JndiNameEnvironment; +import com.sun.enterprise.deployment.LifecycleCallbackDescriptor; +import com.sun.enterprise.deployment.ManagedBeanDescriptor; +import com.sun.enterprise.deployment.WebBundleDescriptor; +import com.sun.logging.LogDomains; +import jakarta.inject.Inject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Proxy; -import java.security.AccessController; -import java.security.PrivilegedExceptionAction; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -54,10 +72,7 @@ import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; - -import jakarta.inject.Inject; import javax.naming.InitialContext; - import org.glassfish.api.admin.ProcessEnvironment; import org.glassfish.api.admin.ProcessEnvironment.ProcessType; import org.glassfish.api.event.EventListener; @@ -72,26 +87,6 @@ import org.glassfish.internal.deployment.Deployment; import org.jvnet.hk2.annotations.Service; -import com.sun.enterprise.container.common.spi.InterceptorInvoker; -import com.sun.enterprise.container.common.spi.JCDIService; -import com.sun.enterprise.container.common.spi.JavaEEInterceptorBuilder; -import com.sun.enterprise.container.common.spi.JavaEEInterceptorBuilderFactory; -import com.sun.enterprise.container.common.spi.ManagedBeanManager; -import com.sun.enterprise.container.common.spi.util.ComponentEnvManager; -import com.sun.enterprise.container.common.spi.util.InjectionManager; -import com.sun.enterprise.container.common.spi.util.InterceptorInfo; -import com.sun.enterprise.deployment.Application; -import com.sun.enterprise.deployment.ApplicationClientDescriptor; -import com.sun.enterprise.deployment.BundleDescriptor; -import com.sun.enterprise.deployment.EjbBundleDescriptor; -import com.sun.enterprise.deployment.EjbDescriptor; -import com.sun.enterprise.deployment.InterceptorDescriptor; -import com.sun.enterprise.deployment.JndiNameEnvironment; -import com.sun.enterprise.deployment.LifecycleCallbackDescriptor; -import com.sun.enterprise.deployment.ManagedBeanDescriptor; -import com.sun.enterprise.deployment.WebBundleDescriptor; -import com.sun.logging.LogDomains; - /** */ @Service(name="ManagedBeanManagerImpl") @@ -623,14 +618,9 @@ public void destroyManagedBean(Object managedBean, boolean validate) { Field proxyField = managedBean.getClass().getDeclaredField("__ejb31_delegate"); - final Field finalF = proxyField; - PrivilegedExceptionAction action = () -> { - if (!finalF.isAccessible()) { - finalF.setAccessible(true); - } - return null; - }; - AccessController.doPrivileged(action); + if (!proxyField.isAccessible()) { + proxyField.setAccessible(true); + } Proxy proxy = (Proxy) proxyField.get(managedBean); diff --git a/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/util/InjectionManagerImpl.java b/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/util/InjectionManagerImpl.java index cc20a58fc04..aef3b78159a 100644 --- a/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/util/InjectionManagerImpl.java +++ b/appserver/common/container-common/src/main/java/com/sun/enterprise/container/common/impl/util/InjectionManagerImpl.java @@ -41,8 +41,17 @@ package com.sun.enterprise.container.common.impl.util; -import static java.util.logging.Level.FINE; - +import com.sun.enterprise.container.common.spi.JCDIService; +import com.sun.enterprise.container.common.spi.ManagedBeanManager; +import com.sun.enterprise.container.common.spi.util.ComponentEnvManager; +import com.sun.enterprise.container.common.spi.util.InjectionException; +import com.sun.enterprise.container.common.spi.util.InjectionManager; +import com.sun.enterprise.deployment.InjectionCapable; +import com.sun.enterprise.deployment.InjectionInfo; +import com.sun.enterprise.deployment.InjectionTarget; +import com.sun.enterprise.deployment.JndiNameEnvironment; +import com.sun.enterprise.util.LocalStringManagerImpl; +import jakarta.inject.Inject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -52,10 +61,7 @@ import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; - -import jakarta.inject.Inject; import javax.naming.NamingException; - import org.glassfish.api.admin.ProcessEnvironment; import org.glassfish.api.invocation.ComponentInvocation; import org.glassfish.api.invocation.InvocationManager; @@ -64,16 +70,7 @@ import org.glassfish.hk2.api.ServiceLocator; import org.jvnet.hk2.annotations.Service; -import com.sun.enterprise.container.common.spi.JCDIService; -import com.sun.enterprise.container.common.spi.ManagedBeanManager; -import com.sun.enterprise.container.common.spi.util.ComponentEnvManager; -import com.sun.enterprise.container.common.spi.util.InjectionException; -import com.sun.enterprise.container.common.spi.util.InjectionManager; -import com.sun.enterprise.deployment.InjectionCapable; -import com.sun.enterprise.deployment.InjectionInfo; -import com.sun.enterprise.deployment.InjectionTarget; -import com.sun.enterprise.deployment.JndiNameEnvironment; -import com.sun.enterprise.util.LocalStringManagerImpl; +import static java.util.logging.Level.FINE; /** * Implementation of InjectionManager. @@ -543,20 +540,7 @@ private void _inject(final Class clazz, final Object instance, String componentI "Injecting dependency with logical name: {0} into field: {1} on class: {2}", next.getComponentEnvName(), f, clazz)); } - - final Object value = injectedValue; - // Wrap actual value insertion in doPrivileged to - // allow for private/protected field access. - if (System.getSecurityManager() != null) { - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - public java.lang.Object run() throws Exception { - f.set(instance, value); - return null; - } - }); - } else { - f.set(instance, value); - } + f.set(instance, injectedValue); } else if (target.isMethodInjectable()) { final Method m = getMethod(next, target, clazz); @@ -579,18 +563,7 @@ public java.lang.Object run() throws Exception { } final Object value = injectedValue; - if (System.getSecurityManager() != null) { - // Wrap actual value insertion in doPrivileged to - // allow for private/protected field access. - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - public java.lang.Object run() throws Exception { - m.invoke(instance, new Object[] { value }); - return null; - } - }); - } else { - m.invoke(instance, new Object[] { value }); - } + m.invoke(instance, new Object[] { value }); } } @@ -613,17 +586,10 @@ private void invokeLifecycleMethod(final Method lifecycleMethod, final Object in "Calling lifecycle method: {0} on class: {1}", lifecycleMethod, lifecycleMethod.getDeclaringClass())); } - // Wrap actual value insertion in doPrivileged to - // allow for private/protected field access. - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - public java.lang.Object run() throws Exception { - if (!lifecycleMethod.isAccessible()) { - lifecycleMethod.setAccessible(true); - } - lifecycleMethod.invoke(instance); - return null; - } - }); + if (!lifecycleMethod.isAccessible()) { + lifecycleMethod.setAccessible(true); + } + lifecycleMethod.invoke(instance); } catch (Throwable t) { String msg = localStrings.getLocalString("injection-manager.exception-invoke-lifecycle-method", "Exception attempting invoke lifecycle method: {0}", lifecycleMethod); @@ -639,9 +605,7 @@ public java.lang.Object run() throws Exception { } private Field getField(InjectionTarget target, Class resourceClass) throws Exception { - Field f = target.getField(); - if (f == null) { try { // Check for the given field within the resourceClass only. @@ -649,14 +613,9 @@ private Field getField(InjectionTarget target, Class resourceClass) throws Excep f = resourceClass.getDeclaredField(target.getFieldName()); final Field finalF = f; - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - public java.lang.Object run() throws Exception { - if (!finalF.isAccessible()) { - finalF.setAccessible(true); - } - return null; - } - }); + if (!finalF.isAccessible()) { + finalF.setAccessible(true); + } } catch (java.lang.NoSuchFieldException nsfe) { } @@ -689,14 +648,9 @@ private Method getMethod(InjectionCapable resource, InjectionTarget target, Clas target.setMethod(m); final Method finalM = m; - java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { - public java.lang.Object run() throws Exception { - if (!finalM.isAccessible()) { - finalM.setAccessible(true); - } - return null; - } - }); + if (!finalM.isAccessible()) { + finalM.setAccessible(true); + } break; } diff --git a/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/GlassFishNamingBuilder.java b/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/GlassFishNamingBuilder.java index 96f42b109f5..e9fa7fcfc08 100644 --- a/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/GlassFishNamingBuilder.java +++ b/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/GlassFishNamingBuilder.java @@ -38,31 +38,28 @@ * holder. */ +// Portions Copyright [2024] [Payara Foundation and/or its affiliates] + package com.sun.enterprise.naming; import com.sun.enterprise.naming.impl.SerialInitContextFactory; -import org.glassfish.hk2.runlevel.RunLevel; -import org.glassfish.internal.api.InitRunLevel; -import org.glassfish.internal.api.ServerContext; -import org.glassfish.logging.annotation.LogMessageInfo; -import org.jvnet.hk2.annotations.Service; -import org.glassfish.hk2.api.PostConstruct; -import org.glassfish.hk2.api.PreDestroy; - import jakarta.inject.Inject; +import java.lang.reflect.Field; +import java.util.Hashtable; +import java.util.logging.Level; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.NoInitialContextException; import javax.naming.spi.InitialContextFactory; import javax.naming.spi.InitialContextFactoryBuilder; import javax.naming.spi.NamingManager; -import java.lang.reflect.Field; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.Hashtable; -import java.util.logging.Level; +import org.glassfish.hk2.api.PostConstruct; +import org.glassfish.hk2.api.PreDestroy; +import org.glassfish.hk2.runlevel.RunLevel; +import org.glassfish.internal.api.InitRunLevel; +import org.glassfish.internal.api.ServerContext; +import org.glassfish.logging.annotation.LogMessageInfo; +import org.jvnet.hk2.annotations.Service; import static com.sun.enterprise.naming.util.LogFacade.logger; @@ -160,60 +157,20 @@ private Class loadClass(String className) throws ClassNotFoundException } } - public void postConstruct() - { - try - { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - try - { - AccessController.doPrivileged(new PrivilegedExceptionAction() - { - public Void run() throws NamingException - { - if (isUsingBuilder()) { - NamingManager.setInitialContextFactoryBuilder(GlassFishNamingBuilder.this); - } - return null; //Nothing to return - } - }); - } - catch (PrivilegedActionException e) - { - throw (NamingException) e.getCause(); - } - } - else - { - if (isUsingBuilder()) { - NamingManager.setInitialContextFactoryBuilder(this); - } + public void postConstruct() { + try { + if (isUsingBuilder()) { + NamingManager.setInitialContextFactoryBuilder(this); } - } - catch (NamingException e) - { + } catch (NamingException e) { throw new RuntimeException(e); } } public void preDestroy() { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - AccessController.doPrivileged(new PrivilegedAction(){ - public Void run() { - if (isUsingBuilder()) { - resetInitialContextFactoryBuilder(); - } - return null; - } - }); - } else { - if (isUsingBuilder()) { - resetInitialContextFactoryBuilder(); - } + if (isUsingBuilder()) { + resetInitialContextFactoryBuilder(); } } diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/EJBUtils.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/EJBUtils.java index e30f7915b02..33d7f4691fa 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/EJBUtils.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/EJBUtils.java @@ -37,45 +37,49 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2022] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package com.sun.ejb; -import com.sun.ejb.codegen.ClassGeneratorFactory; import com.sun.ejb.codegen.AsmSerializableBeanGenerator; +import com.sun.ejb.codegen.ClassGeneratorFactory; import com.sun.ejb.codegen.GenericHomeGenerator; import com.sun.ejb.codegen.Remote30WrapperGenerator; import com.sun.ejb.codegen.RemoteGenerator; import com.sun.ejb.containers.BaseContainer; -import com.sun.ejb.containers.RemoteBusinessWrapperBase; import com.sun.ejb.containers.EjbContainerUtilImpl; import com.sun.ejb.containers.GenericEJBLocalHome; +import com.sun.ejb.containers.RemoteBusinessWrapperBase; import com.sun.enterprise.deployment.EjbDescriptor; import com.sun.enterprise.deployment.EjbReferenceDescriptor; - -import javax.naming.NamingException; -import javax.rmi.PortableRemoteObject; -import java.io.*; -import java.lang.reflect.*; -import java.security.PrivilegedAction; +import com.sun.logging.LogDomains; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.PrintStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Properties; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; - +import javax.naming.NamingException; +import javax.rmi.PortableRemoteObject; import static org.glassfish.pfl.dynamic.codegen.spi.Wrapper.*; -import com.sun.logging.LogDomains; /** * A handy class with static utility methods. - * + *

    * Note that much of this code has to execute in the client so * it needs to be careful about which server-only resources it * uses and in which code paths. - * */ public class EJBUtils { @@ -89,10 +93,10 @@ public class EJBUtils { // this property does *not* cover RMI-IIOP stub generation. // See IASEJBC.java for more details. private static final String EJB_USE_STATIC_CODEGEN_PROP = - "com.sun.ejb.UseStaticCodegen"; + "com.sun.ejb.UseStaticCodegen"; private static final String REMOTE30_HOME_JNDI_SUFFIX = - "__3_x_Internal_RemoteBusinessHome__"; + "__3_x_Internal_RemoteBusinessHome__"; private static Boolean ejbUseStaticCodegen_ = null; @@ -119,14 +123,12 @@ public class EJBUtils { */ public static final byte[] serializeObject(Object obj, boolean replaceObject) - throws IOException - { + throws IOException { return EjbContainerUtilImpl.getInstance().getJavaEEIOUtils().serializeObject(obj, replaceObject); } public static final byte[] serializeObject(Object obj) - throws IOException - { + throws IOException { return EjbContainerUtilImpl.getInstance().getJavaEEIOUtils().serializeObject(obj, true); } @@ -135,6 +137,7 @@ public static final byte[] serializeObject(Object obj) * container-managed fields, all of which may include Remote * EJB references, * Local refs, JNDI Contexts etc which are not Serializable. + * * @param data * @param loader * @param resolveObject @@ -143,50 +146,35 @@ public static final byte[] serializeObject(Object obj) * @throws java.lang.Exception */ public static final Object deserializeObject(byte[] data, - ClassLoader loader, boolean resolveObject, long appUniqueId) - throws Exception - { + ClassLoader loader, boolean resolveObject, long appUniqueId) + throws Exception { return EjbContainerUtilImpl.getInstance().getJavaEEIOUtils().deserializeObject(data, resolveObject, loader, appUniqueId); } public static final Object deserializeObject(byte[] data, ClassLoader loader, long appUniqueId) - throws Exception - { + throws Exception { return EjbContainerUtilImpl.getInstance().getJavaEEIOUtils().deserializeObject(data, true, loader, appUniqueId); } public static boolean useStaticCodegen() { synchronized (EJBUtils.class) { - if( ejbUseStaticCodegen_ == null ) { - String ejbStaticCodegenProp = null; - if(System.getSecurityManager() == null) { - ejbStaticCodegenProp = - System.getProperty(EJB_USE_STATIC_CODEGEN_PROP); - } else { - ejbStaticCodegenProp = (String) - java.security.AccessController.doPrivileged - (new java.security.PrivilegedAction() { - public java.lang.Object run() { - return - System.getProperty(EJB_USE_STATIC_CODEGEN_PROP); - }}); - } - + if (ejbUseStaticCodegen_ == null) { + String ejbStaticCodegenProp; + ejbStaticCodegenProp = System.getProperty(EJB_USE_STATIC_CODEGEN_PROP); boolean useStaticCodegen = - ( (ejbStaticCodegenProp != null) && - ejbStaticCodegenProp.equalsIgnoreCase("true")); + ((ejbStaticCodegenProp != null) && + ejbStaticCodegenProp.equalsIgnoreCase("true")); ejbUseStaticCodegen_ = useStaticCodegen; _logger.log(Level.FINE, "EJB Static codegen is " + - (useStaticCodegen ? "ENABLED" : "DISABLED") + - " ejbUseStaticCodegenProp = " + - ejbStaticCodegenProp); + (useStaticCodegen ? "ENABLED" : "DISABLED") + + " ejbUseStaticCodegenProp = " + + ejbStaticCodegenProp); } } return ejbUseStaticCodegen_.booleanValue(); - } private static String getClassPackageName(String intf) { @@ -196,7 +184,7 @@ private static String getClassPackageName(String intf) { private static String getClassSimpleName(String intf) { int dot = intf.lastIndexOf('.'); - return (dot == -1) ? intf : intf.substring(dot+1); + return (dot == -1) ? intf : intf.substring(dot + 1); } public static String getGeneratedOptionalInterfaceName(String ejbClassName) { @@ -204,7 +192,7 @@ public static String getGeneratedOptionalInterfaceName(String ejbClassName) { String simpleName = getClassSimpleName(ejbClassName); String optionalIntfName = "__EJB31_Generated__" + simpleName + "__Intf__"; return (packageName != null) ? - packageName + "." + optionalIntfName : optionalIntfName; + packageName + "." + optionalIntfName : optionalIntfName; } public static String getGeneratedSerializableClassName(String beanClass) { @@ -212,7 +200,7 @@ public static String getGeneratedSerializableClassName(String beanClass) { String simpleName = getClassSimpleName(beanClass); String generatedSimpleName = "_" + simpleName + "_Serializable"; return (packageName != null) ? - packageName + "." + generatedSimpleName : generatedSimpleName; + packageName + "." + generatedSimpleName : generatedSimpleName; } public static String getGeneratedRemoteIntfName(String businessIntf) { @@ -220,7 +208,7 @@ public static String getGeneratedRemoteIntfName(String businessIntf) { String simpleName = getClassSimpleName(businessIntf); String generatedSimpleName = "_" + simpleName + "_Remote"; return (packageName != null) ? - packageName + "." + generatedSimpleName : generatedSimpleName; + packageName + "." + generatedSimpleName : generatedSimpleName; } public static String getGeneratedRemoteWrapperName(String businessIntf) { @@ -228,7 +216,7 @@ public static String getGeneratedRemoteWrapperName(String businessIntf) { String simpleName = getClassSimpleName(businessIntf); String generatedSimpleName = "_" + simpleName + "_Wrapper"; return (packageName != null) ? - packageName + "." + generatedSimpleName : generatedSimpleName; + packageName + "." + generatedSimpleName : generatedSimpleName; } public static String getGenericEJBHomeClassName() { @@ -248,14 +236,13 @@ public static String getGenericEJBHomeClassName() { * internally. Of course, this is based on the assumption that the * internal name is generated in a way that will not clash with a * separate top-level physical jndi-name chosen by the developer. - * + *

    * Note that it's better to delay this final jndi name translation as * much as possible and do it right before the NamingManager lookup, * as opposed to changing the jndi-name within the descriptor objects * themselves. This way, the extra indirection will not be exposed * if the descriptors are written out and they won't complicate any * jndi-name equality logic. - * */ public static String getRemoteEjbJndiName(EjbReferenceDescriptor refDesc) { @@ -263,8 +250,8 @@ public static String getRemoteEjbJndiName(EjbReferenceDescriptor refDesc) { refDesc.getEjbInterface() : refDesc.getHomeClassName(); return getRemoteEjbJndiName(refDesc.isEJB30ClientView(), - intf, - refDesc.getJndiName()); + intf, + refDesc.getJndiName()); } public static String getRemote30HomeJndiName(String jndiName) { @@ -280,8 +267,8 @@ public static String getRemoteEjbJndiName(boolean businessView, String portableFullyQualifiedPortion = PORTABLE_JNDI_NAME_SEP + interfaceName; String glassfishFullyQualifiedPortion = GLASSFISH_JNDI_NAME_SEP + interfaceName; - if( businessView ) { - if( jndiName.startsWith(CORBA_INS_PREFIX) ) { + if (businessView) { + if (jndiName.startsWith(CORBA_INS_PREFIX)) { // In the case of a corba interoperable naming string, we @@ -303,11 +290,11 @@ public static String getRemoteEjbJndiName(boolean businessView, // Make sure any of the resulting jndi names still have corbaname: prefix intact String newJndiName = jndiName; - if( jndiNameMinusCorbaNamePortion.startsWith(JAVA_GLOBAL_PREFIX) ){ + if (jndiNameMinusCorbaNamePortion.startsWith(JAVA_GLOBAL_PREFIX)) { newJndiName = stripFullyQualifiedJndiName(jndiName, portableFullyQualifiedPortion); - } else if( jndiNameMinusCorbaNamePortion.endsWith(glassfishFullyQualifiedPortion ) ){ + } else if (jndiNameMinusCorbaNamePortion.endsWith(glassfishFullyQualifiedPortion)) { newJndiName = stripFullyQualifiedJndiName(jndiName, glassfishFullyQualifiedPortion); @@ -317,7 +304,7 @@ public static String getRemoteEjbJndiName(boolean businessView, } else { // Convert to fully-qualified names - if( jndiName.startsWith(JAVA_GLOBAL_PREFIX)) { + if (jndiName.startsWith(JAVA_GLOBAL_PREFIX)) { returnValue = checkFullyQualifiedJndiName(jndiName, portableFullyQualifiedPortion); } else { returnValue = checkFullyQualifiedJndiName(jndiName, glassfishFullyQualifiedPortion); @@ -328,7 +315,7 @@ public static String getRemoteEjbJndiName(boolean businessView, // EJB 2.x Remote Home // Only in the portable global case, convert to a fully-qualified name - if( jndiName.startsWith(JAVA_GLOBAL_PREFIX)) { + if (jndiName.startsWith(JAVA_GLOBAL_PREFIX)) { returnValue = checkFullyQualifiedJndiName(jndiName, portableFullyQualifiedPortion); } } @@ -338,7 +325,7 @@ public static String getRemoteEjbJndiName(boolean businessView, private static String checkFullyQualifiedJndiName(String origJndiName, String fullyQualifiedPortion) { String returnValue = origJndiName; - if( !origJndiName.endsWith(fullyQualifiedPortion) ) { + if (!origJndiName.endsWith(fullyQualifiedPortion)) { returnValue = origJndiName + fullyQualifiedPortion; } return returnValue; @@ -346,9 +333,9 @@ private static String checkFullyQualifiedJndiName(String origJndiName, String fu private static String stripFullyQualifiedJndiName(String origJndiName, String fullyQualifiedPortion) { String returnValue = origJndiName; - if( origJndiName.endsWith(fullyQualifiedPortion) ) { + if (origJndiName.endsWith(fullyQualifiedPortion)) { int portionLength = fullyQualifiedPortion.length(); - returnValue = origJndiName.substring(0, origJndiName.length() - portionLength ); + returnValue = origJndiName.substring(0, origJndiName.length() - portionLength); } return returnValue; } @@ -356,19 +343,19 @@ private static String stripFullyQualifiedJndiName(String origJndiName, String fu public static Object resolveEjbRefObject(EjbReferenceDescriptor refDesc, Object jndiObj) - throws NamingException { + throws NamingException { Object returnObject = jndiObj; - if( refDesc.isLocal() ) { + if (refDesc.isLocal()) { EjbDescriptor target = refDesc.getEjbDescriptor(); BaseContainer container = EjbContainerUtilImpl.getInstance().getContainer(target.getUniqueId()); - if( refDesc.isEJB30ClientView() ) { + if (refDesc.isEJB30ClientView()) { GenericEJBLocalHome genericLocalHome = - container.getEJBLocalBusinessHome(refDesc.getEjbInterface()); + container.getEJBLocalBusinessHome(refDesc.getEjbInterface()); returnObject = genericLocalHome.create(refDesc.getEjbInterface()); } else { returnObject = container.getEJBLocalHome(); @@ -383,10 +370,10 @@ public static Object resolveEjbRefObject(EjbReferenceDescriptor refDesc, // the jndiObj refers to the internal Remote 3.0 Home so we // still need to create a remote 30 client wrapper object. - if ( refDesc.isEJB30ClientView() && - !(jndiObj instanceof RemoteBusinessWrapperBase) ) { + if (refDesc.isEJB30ClientView() && + !(jndiObj instanceof RemoteBusinessWrapperBase)) { returnObject = EJBUtils.lookupRemote30BusinessObject - (jndiObj, refDesc.getEjbInterface()); + (jndiObj, refDesc.getEjbInterface()); } } @@ -397,9 +384,7 @@ public static Object resolveEjbRefObject(EjbReferenceDescriptor refDesc, public static Object lookupRemote30BusinessObject(Object jndiObj, String businessInterface) - throws NamingException - - { + throws NamingException { Object returnObject = null; try { @@ -407,10 +392,10 @@ public static Object lookupRemote30BusinessObject(Object jndiObj, ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class genericEJBHome = loadGeneratedGenericEJBHomeClass - (loader); + (loader); final Object genericHomeObj = - PortableRemoteObject.narrow(jndiObj, genericEJBHome); + PortableRemoteObject.narrow(jndiObj, genericEJBHome); // The generated remote business interface and the // client wrapper for the business interface are produced @@ -420,29 +405,29 @@ public static Object lookupRemote30BusinessObject(Object jndiObj, loadGeneratedRemoteBusinessClasses(businessInterface); String generatedRemoteIntfName = EJBUtils. - getGeneratedRemoteIntfName(businessInterface); + getGeneratedRemoteIntfName(businessInterface); Method createMethod = genericEJBHome.getMethod - ("create", String.class); + ("create", String.class); java.rmi.Remote delegate = (java.rmi.Remote) - createMethod.invoke(genericHomeObj, - generatedRemoteIntfName); + createMethod.invoke(genericHomeObj, + generatedRemoteIntfName); returnObject = createRemoteBusinessObject - (loader, businessInterface, delegate); + (loader, businessInterface, delegate); // TODO Bring over appclient security exception retry logic CR 6620388 - } catch(Exception e) { + } catch (Exception e) { NamingException ne = new NamingException - ("ejb ref resolution error for remote business interface" - + businessInterface); + ("ejb ref resolution error for remote business interface" + + businessInterface); ne.initCause(e instanceof InvocationTargetException ? - e.getCause() : e); + e.getCause() : e); throw ne; } @@ -451,7 +436,7 @@ public static Object lookupRemote30BusinessObject(Object jndiObj, } public static Class loadGeneratedSerializableClass(ClassLoader loader, String className) - throws Exception { + throws Exception { String generatedSerializableClassName = getGeneratedSerializableClassName(className); Class developerClass = loader.loadClass(className); @@ -464,50 +449,50 @@ public static Class loadGeneratedSerializableClass(ClassLoader loader, String cl } public static void loadGeneratedRemoteBusinessClasses - (String businessInterfaceName) throws Exception { + (String businessInterfaceName) throws Exception { ClassLoader appClassLoader = - getBusinessIntfClassLoader(businessInterfaceName); + getBusinessIntfClassLoader(businessInterfaceName); loadGeneratedRemoteBusinessClasses(appClassLoader, - businessInterfaceName); + businessInterfaceName); } public static void loadGeneratedRemoteBusinessClasses(ClassLoader appClassLoader, String businessInterfaceName) - throws Exception { + throws Exception { String generatedRemoteIntfName = EJBUtils. - getGeneratedRemoteIntfName(businessInterfaceName); + getGeneratedRemoteIntfName(businessInterfaceName); String wrapperClassName = EJBUtils. - getGeneratedRemoteWrapperName(businessInterfaceName); + getGeneratedRemoteWrapperName(businessInterfaceName); Class generatedRemoteIntf = loadClassIgnoringExceptions(appClassLoader, generatedRemoteIntfName); Class generatedRemoteWrapper = loadClassIgnoringExceptions(appClassLoader, wrapperClassName); - if( (generatedRemoteIntf != null) && - (generatedRemoteWrapper != null) ) { + if ((generatedRemoteIntf != null) && + (generatedRemoteWrapper != null)) { return; } _setClassLoader(appClassLoader); try { - if( generatedRemoteIntf == null ) { + if (generatedRemoteIntf == null) { RemoteGenerator gen = new RemoteGenerator(appClassLoader, - businessInterfaceName); + businessInterfaceName); Class developerClass = appClassLoader.loadClass(businessInterfaceName); generateAndLoad(gen, generatedRemoteIntfName, appClassLoader, developerClass); } - if( generatedRemoteWrapper == null ) { + if (generatedRemoteWrapper == null) { Remote30WrapperGenerator gen = new Remote30WrapperGenerator - (appClassLoader, businessInterfaceName, - generatedRemoteIntfName); + (appClassLoader, businessInterfaceName, + generatedRemoteIntfName); Class developerClass = appClassLoader.loadClass(businessInterfaceName); generateAndLoad(gen, wrapperClassName, appClassLoader, developerClass); @@ -516,32 +501,33 @@ public static void loadGeneratedRemoteBusinessClasses(ClassLoader appClassLoader } finally { // Fix for 7075: Make sure no classloader is bound to threadlocal: // avoid possible classloader leak. - _setClassLoader(null) ; + _setClassLoader(null); } } /** * Loads the a class by name using the provided classloader. + * * @param clsLoader Classloader to use for loading - * @param clsName Name of the class to load. + * @param clsName Name of the class to load. * @return loaded class or null in case of an exception. */ private static Class loadClassIgnoringExceptions(ClassLoader clsLoader, String clsName) { try { return clsLoader.loadClass(clsName); - } catch(Exception e) { + } catch (Exception e) { return null; } } public static Class loadGeneratedGenericEJBHomeClass - (ClassLoader appClassLoader) throws Exception { + (ClassLoader appClassLoader) throws Exception { String className = getGenericEJBHomeClassName(); Class generatedGenericEJBHomeClass = loadClassIgnoringExceptions(appClassLoader, className); - if( generatedGenericEJBHomeClass == null ) { + if (generatedGenericEJBHomeClass == null) { GenericHomeGenerator gen = new GenericHomeGenerator(appClassLoader); generatedGenericEJBHomeClass = generateAndLoad(gen, className, appClassLoader, EJBUtils.class); } @@ -582,7 +568,7 @@ private static Class generateAndLoad(ClassGeneratorFactory cgf, cgf.evaluate(); final Properties props = new Properties(); - if( _logger.isLoggable(Level.FINE) ) { + if (_logger.isLoggable(Level.FINE)) { props.put(DUMP_AFTER_SETUP_VISITOR, "true"); props.put(TRACE_BYTE_CODE_GENERATION, "true"); @@ -596,7 +582,7 @@ private static Class generateAndLoad(ClassGeneratorFactory cgf, _sourceCode(ps, props); _logger.fine(baos.toString()); - } catch(Exception e) { + } catch (Exception e) { _logger.log(Level.FINE, "exception generating src", e); } @@ -604,14 +590,8 @@ private static Class generateAndLoad(ClassGeneratorFactory cgf, Class result; try { - if(System.getSecurityManager() == null) { - result = _generate(loader, protectionDomainBase.getProtectionDomain(), - props); - } else { - result = java.security.AccessController.doPrivileged( - (PrivilegedAction) () -> _generate(loader, protectionDomainBase.getProtectionDomain(), props) - ); - } + result = _generate(loader, protectionDomainBase.getProtectionDomain(), + props); } catch (RuntimeException runEx) { //We would have got this exception if there were two (or more) // concurrent threads that attempted to define the same class @@ -632,14 +612,14 @@ private static Class generateAndLoad(ClassGeneratorFactory cgf, public static RemoteBusinessWrapperBase createRemoteBusinessObject - (String businessInterface, java.rmi.Remote delegate) - throws Exception { + (String businessInterface, java.rmi.Remote delegate) + throws Exception { ClassLoader appClassLoader = - getBusinessIntfClassLoader(businessInterface); + getBusinessIntfClassLoader(businessInterface); return createRemoteBusinessObject(appClassLoader, - businessInterface, delegate); + businessInterface, delegate); } @@ -648,13 +628,13 @@ public static RemoteBusinessWrapperBase createRemoteBusinessObject( ) throws Exception { String wrapperClassName = EJBUtils.getGeneratedRemoteWrapperName - (businessInterface); + (businessInterface); Class clientWrapperClass = loader.loadClass(wrapperClassName); Constructor ctor = null; - for(Constructor next : clientWrapperClass.getConstructors()) { - if (next.getParameterTypes().length > 0 ) { + for (Constructor next : clientWrapperClass.getConstructors()) { + if (next.getParameterTypes().length > 0) { ctor = next; break; } @@ -669,27 +649,10 @@ public static RemoteBusinessWrapperBase createRemoteBusinessObject( private static ClassLoader getBusinessIntfClassLoader - (String businessInterface) throws Exception { - - ClassLoader contextLoader; - if(System.getSecurityManager() == null) { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - contextLoader = (cl != null) ? cl : - ClassLoader.getSystemClassLoader(); - } else { - contextLoader = java.security.AccessController.doPrivileged( - (PrivilegedAction) () -> { - // Return context class loader. If there is none, - // which could happen within Appclient container, - // return system class loader. - ClassLoader cl = - Thread.currentThread().getContextClassLoader(); - return (cl != null) ? cl : - ClassLoader.getSystemClassLoader(); - - } - ); - } + (String businessInterface) throws Exception { + final ClassLoader contextLoader; + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + contextLoader = cl == null ? ClassLoader.getSystemClassLoader() : cl; ClassLoader appClassLoader; String generatedRemoteInterfaceName = EJBUtils. @@ -701,99 +664,81 @@ public static RemoteBusinessWrapperBase createRemoteBusinessObject( } final Class businessInterfaceClass = - contextLoader.loadClass(businessInterface); + contextLoader.loadClass(businessInterface); - if(System.getSecurityManager() == null) { - appClassLoader = businessInterfaceClass.getClassLoader(); - } else { - appClassLoader = java.security.AccessController.doPrivileged( - (PrivilegedAction) () -> businessInterfaceClass.getClassLoader() - ); - } + appClassLoader = businessInterfaceClass.getClassLoader(); return appClassLoader; } public static void serializeObjectFields( - Object instance, - ObjectOutputStream oos) - throws IOException { + Object instance, + ObjectOutputStream oos) + throws IOException { serializeObjectFields(instance, oos, true); } public static void serializeObjectFields( - Object instance, - ObjectOutputStream oos, - boolean usesSuperClass) - throws IOException { + Object instance, + ObjectOutputStream oos, + boolean usesSuperClass) + throws IOException { - Class clazz = (usesSuperClass)? instance.getClass().getSuperclass() : instance.getClass(); + Class clazz = (usesSuperClass) ? instance.getClass().getSuperclass() : instance.getClass(); final ObjectOutputStream objOutStream = oos; // Write out list of fields eligible for serialization in sorted order. - for(Field next : getSerializationFields(clazz)) { + for (Field next : getSerializationFields(clazz)) { final Field nextField = next; final Object theInstance = instance; - Object value = null; + Object value = null; try { - if(System.getSecurityManager() == null) { - if( !nextField.isAccessible() ) { - nextField.setAccessible(true); - } - value = nextField.get(theInstance); - } else { - value = java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { - public java.lang.Object run() throws Exception { - if( !nextField.isAccessible() ) { - nextField.setAccessible(true); - } - return nextField.get(theInstance); - } - }); + if (!nextField.isAccessible()) { + nextField.setAccessible(true); } - if( _logger.isLoggable(Level.FINE) ) { + value = nextField.get(theInstance); + if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, "=====> Serializing field: " + nextField); } objOutStream.writeObject(value); - } catch(Throwable t) { - if( _logger.isLoggable(Level.FINE) ) { + } catch (Throwable t) { + if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, "=====> failed serializing field: " + nextField + - " =====> of class: " + clazz + " =====> using: " + oos.getClass() + - " =====> serializing value of type: " + ((value == null)? null : value.getClass().getName()) + - " ===> Error: " + t); + " =====> of class: " + clazz + " =====> using: " + oos.getClass() + + " =====> serializing value of type: " + ((value == null) ? null : value.getClass().getName()) + + " ===> Error: " + t); _logger.log(Level.FINE, "", t); } IOException ioe = new IOException(); Throwable cause = (t instanceof InvocationTargetException) ? - ((InvocationTargetException)t).getCause() : t; - ioe.initCause( cause ); + ((InvocationTargetException) t).getCause() : t; + ioe.initCause(cause); throw ioe; } } } public static void deserializeObjectFields( - Object instance, - ObjectInputStream ois) - throws IOException { + Object instance, + ObjectInputStream ois) + throws IOException { deserializeObjectFields(instance, ois, null, true); } public static void deserializeObjectFields( - Object instance, - ObjectInputStream ois, - Object replaceValue, - boolean usesSuperClass) - throws IOException { - - Class clazz = (usesSuperClass)? instance.getClass().getSuperclass() : instance.getClass(); - if( _logger.isLoggable(Level.FINE) ) { + Object instance, + ObjectInputStream ois, + Object replaceValue, + boolean usesSuperClass) + throws IOException { + + Class clazz = (usesSuperClass) ? instance.getClass().getSuperclass() : instance.getClass(); + if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, "=====> Deserializing class: " + clazz); if (replaceValue != null) _logger.log(Level.FINE, "=====> Replace requested for value: " + replaceValue.getClass()); @@ -802,19 +747,19 @@ public static void deserializeObjectFields( // Use helper method to get sorted list of fields eligible // for deserialization. This ensures that we correctly match // serialized state with its corresponding field. - for(Field next : getSerializationFields(clazz)) { + for (Field next : getSerializationFields(clazz)) { try { final Field nextField = next; - if( _logger.isLoggable(Level.FINE) ) { + if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, "=====> Deserializing field: " + nextField); } // Read value from the stream even if it is to be replaced to adjust the pointers Object value = ois.readObject(); if (replaceValue != null && nextField.getType().isAssignableFrom(replaceValue.getClass())) { - if( _logger.isLoggable(Level.FINE) ) { + if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, "=====> Replacing field: " + nextField); } @@ -823,28 +768,28 @@ public static void deserializeObjectFields( final Object newValue = value; final Object theInstance = instance; - if(System.getSecurityManager() == null) { - if( !nextField.isAccessible() ) { + if (System.getSecurityManager() == null) { + if (!nextField.isAccessible()) { nextField.setAccessible(true); } nextField.set(theInstance, newValue); } else { java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction() { - public java.lang.Object run() throws Exception { - if( !nextField.isAccessible() ) { - nextField.setAccessible(true); - } - nextField.set(theInstance, newValue); - return null; - } - }); + public java.lang.Object run() throws Exception { + if (!nextField.isAccessible()) { + nextField.setAccessible(true); + } + nextField.set(theInstance, newValue); + return null; + } + }); } - } catch(Throwable t) { + } catch (Throwable t) { IOException ioe = new IOException(); Throwable cause = (t instanceof InvocationTargetException) ? - ((InvocationTargetException)t).getCause() : t; - ioe.initCause( cause ); + ((InvocationTargetException) t).getCause() : t; + ioe.initCause(cause); throw ioe; } } @@ -856,11 +801,11 @@ private static Collection getSerializationFields(Class clazz) { SortedMap sortedMap = new TreeMap(); - for(Field next : fields) { + for (Field next : fields) { int modifiers = next.getModifiers(); - if( Modifier.isStatic(modifiers) || - Modifier.isTransient(modifiers) ) { + if (Modifier.isStatic(modifiers) || + Modifier.isTransient(modifiers)) { continue; } diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/BaseContainer.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/BaseContainer.java index cf046d19601..9b50518b8e8 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/BaseContainer.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/BaseContainer.java @@ -81,15 +81,50 @@ import com.sun.enterprise.deployment.WebServicesDescriptor; import com.sun.enterprise.deployment.util.TypeUtil; import com.sun.enterprise.deployment.xml.RuntimeTagNames; +import com.sun.enterprise.loader.ASURLClassLoader; import com.sun.enterprise.security.SecurityManager; import com.sun.enterprise.transaction.api.JavaEETransaction; import com.sun.enterprise.transaction.api.JavaEETransactionManager; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.Utility; - import fish.payara.cluster.DistributedLockType; import fish.payara.notification.requesttracing.RequestTraceSpanLog; - +import fish.payara.nucleus.requesttracing.RequestTracingService; +import fish.payara.opentracing.OpenTracingService; +import io.opentracing.Span; +import io.opentracing.Tracer; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import jakarta.ejb.AccessLocalException; +import jakarta.ejb.CreateException; +import jakarta.ejb.EJBAccessException; +import jakarta.ejb.EJBContext; +import jakarta.ejb.EJBException; +import jakarta.ejb.EJBHome; +import jakarta.ejb.EJBLocalHome; +import jakarta.ejb.EJBLocalObject; +import jakarta.ejb.EJBMetaData; +import jakarta.ejb.EJBObject; +import jakarta.ejb.EJBTransactionRequiredException; +import jakarta.ejb.EJBTransactionRolledbackException; +import jakarta.ejb.FinderException; +import jakarta.ejb.LockType; +import jakarta.ejb.NoSuchEJBException; +import jakarta.ejb.NoSuchObjectLocalException; +import jakarta.ejb.PostActivate; +import jakarta.ejb.PrePassivate; +import jakarta.ejb.RemoveException; +import jakarta.ejb.TransactionRequiredLocalException; +import jakarta.ejb.TransactionRolledbackLocalException; +import jakarta.enterprise.inject.Vetoed; +import jakarta.interceptor.AroundConstruct; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.transaction.RollbackException; +import jakarta.transaction.Status; +import jakarta.transaction.SystemException; +import jakarta.transaction.Transaction; +import jakarta.transaction.UserTransaction; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; @@ -99,32 +134,26 @@ import java.lang.reflect.Proxy; import java.rmi.AccessException; import java.rmi.RemoteException; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.Map.Entry; +import java.util.Properties; +import java.util.Set; +import java.util.Vector; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; - -import jakarta.annotation.PostConstruct; -import jakarta.annotation.PreDestroy; -import jakarta.ejb.*; -import jakarta.enterprise.inject.Vetoed; -import jakarta.interceptor.AroundConstruct; import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.StringRefAddr; -import jakarta.persistence.EntityManager; -import jakarta.persistence.EntityManagerFactory; -import jakarta.transaction.RollbackException; -import jakarta.transaction.Status; -import jakarta.transaction.SystemException; -import jakarta.transaction.Transaction; -import jakarta.transaction.UserTransaction; - -import fish.payara.nucleus.requesttracing.RequestTracingService; -import fish.payara.opentracing.OpenTracingService; -import io.opentracing.Span; -import io.opentracing.Tracer; import org.glassfish.api.invocation.ComponentInvocation; import org.glassfish.api.invocation.InvocationManager; import org.glassfish.api.naming.GlassfishNamingManager; @@ -150,7 +179,6 @@ import org.glassfish.logging.annotation.LogMessageInfo; import static com.sun.enterprise.deployment.MethodDescriptor.EJB_WEB_SERVICE; -import com.sun.enterprise.loader.ASURLClassLoader; import static java.util.logging.Level.FINE; import static java.util.stream.Collectors.toList; @@ -1156,51 +1184,29 @@ final Properties getEnvironmentProperties() { * Otherwise, this is for the RemoteHome view */ public java.rmi.Remote createRemoteReferenceWithId - (byte[] instanceKey, String generatedRemoteBusinessIntf) { + (byte[] instanceKey, String generatedRemoteBusinessIntf) { final Thread currentThread = Thread.currentThread(); final ClassLoader previousClassLoader = - currentThread.getContextClassLoader(); + currentThread.getContextClassLoader(); final ClassLoader myClassLoader = loader; - try { - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(myClassLoader); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public java.lang.Object run() { - currentThread.setContextClassLoader(myClassLoader); - return null; - } - }); - } - java.rmi.Remote remoteRef = null; - if ( generatedRemoteBusinessIntf == null ) { + try { + currentThread.setContextClassLoader(myClassLoader); + java.rmi.Remote remoteRef; + if (generatedRemoteBusinessIntf == null) { remoteRef = remoteHomeRefFactory.createRemoteReference - (instanceKey); + (instanceKey); } else { RemoteReferenceFactory remoteBusinessRefFactory = - remoteBusinessIntfInfo.get(generatedRemoteBusinessIntf). - referenceFactory; + remoteBusinessIntfInfo.get(generatedRemoteBusinessIntf). + referenceFactory; remoteRef = remoteBusinessRefFactory.createRemoteReference - (instanceKey); + (instanceKey); } return remoteRef; } finally { - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(previousClassLoader); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public java.lang.Object run() { - currentThread.setContextClassLoader(previousClassLoader); - return null; - } - }); - } + currentThread.setContextClassLoader(previousClassLoader); } } @@ -1883,58 +1889,35 @@ public void releaseTargetObject(java.rmi.Remote remoteObj) { @Override public void externalPreInvoke() { - BeanContext bc = new BeanContext(); + BeanContext beanContext = new BeanContext(); final Thread currentThread = Thread.currentThread(); - bc.previousClassLoader = currentThread.getContextClassLoader(); - if ( getClassLoader().equals(bc.previousClassLoader) == false ) { - - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader( getClassLoader()); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public java.lang.Object run() { - currentThread.setContextClassLoader( getClassLoader()); - return null; - } - }); - } - bc.classLoaderSwitched = true; + beanContext.previousClassLoader = currentThread.getContextClassLoader(); + if (getClassLoader().equals(beanContext.previousClassLoader) == false) { + currentThread.setContextClassLoader(getClassLoader()); + beanContext.classLoaderSwitched = true; } ArrayDeque beanContextStack = - (ArrayDeque) threadLocalContext.get(); + (ArrayDeque) threadLocalContext.get(); - if ( beanContextStack == null ) { + if (beanContextStack == null) { beanContextStack = new ArrayDeque(); threadLocalContext.set(beanContextStack); } - beanContextStack.push(bc); + beanContextStack.push(beanContext); } @Override public void externalPostInvoke() { try { - ArrayDeque beanContextStack = - (ArrayDeque) threadLocalContext.get(); + ArrayDeque beanContextStack = + (ArrayDeque) threadLocalContext.get(); final BeanContext bc = (BeanContext) beanContextStack.pop(); - if ( bc.classLoaderSwitched == true ) { - if (System.getSecurityManager() == null) { - Thread.currentThread().setContextClassLoader(bc.previousClassLoader); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public java.lang.Object run() { - Thread.currentThread().setContextClassLoader( - bc.previousClassLoader); - return null; - }}); - } + if (bc.classLoaderSwitched == true) { + Thread.currentThread().setContextClassLoader(bc.previousClassLoader); } - } catch ( Exception ex ) { + } catch (Exception ex) { _logger.log(Level.FINE, "externalPostInvoke ex", ex); } } @@ -2284,21 +2267,8 @@ private void processEjbTimeoutMethod(Method method) throws Exception { final Method ejbTimeoutAccessible = method; // Since timeout method can have any kind of access // setAccessible to true. - if (System.getSecurityManager() == null) { - if ( !ejbTimeoutAccessible.isAccessible() ) { - ejbTimeoutAccessible.setAccessible(true); - } - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { - @Override - public java.lang.Object run() throws Exception { - if ( !ejbTimeoutAccessible.isAccessible() ) { - ejbTimeoutAccessible.setAccessible(true); - } - return null; - } - }); + if ( !ejbTimeoutAccessible.isAccessible() ) { + ejbTimeoutAccessible.setAccessible(true); } } else { throw new EJBException(localStrings.getLocalString( @@ -4351,14 +4321,14 @@ public final void onShutdown() { private void doContainerCleanup() { - if ( baseContainerCleanupDone ) { + if (baseContainerCleanupDone) { return; } try { - if ( isWebServiceEndpoint && (webServiceEndpoint != null) ) { + if (isWebServiceEndpoint && (webServiceEndpoint != null)) { String endpointAddress = - webServiceEndpoint.getEndpointAddressUri(); + webServiceEndpoint.getEndpointAddressUri(); if (wsejbEndpointRegistry != null) { wsejbEndpointRegistry.unregisterEndpoint(endpointAddress); } @@ -4367,56 +4337,45 @@ private void doContainerCleanup() { // NOTE : Pipe cleanup that used to done here is now encapsulated within // endpoint registry unregisterEndpoint operation - } catch(Exception e) { + } catch (Exception e) { _logger.log(Level.FINE, "Error unregistering ejb endpoint for " + - ejbDescriptor.getName(), e); + ejbDescriptor.getName(), e); } - if ( hasAsynchronousInvocations ) { + if (hasAsynchronousInvocations) { EjbAsyncInvocationManager asyncManager = - ((EjbContainerUtilImpl) ejbContainerUtilImpl).getEjbAsyncInvocationManager(); + ((EjbContainerUtilImpl) ejbContainerUtilImpl).getEjbAsyncInvocationManager(); asyncManager.cleanupContainerTasks(this); } final Thread currentThread = Thread.currentThread(); final ClassLoader previousClassLoader = - currentThread.getContextClassLoader(); + currentThread.getContextClassLoader(); // Unpublish all portable and non-portable JNDI names - for(Map.Entry entry : jndiInfoMap.entrySet()) { + for (Map.Entry entry : jndiInfoMap.entrySet()) { JndiInfo jndiInfo = entry.getValue(); try { jndiInfo.unpublish(this.namingManager); - } catch(Exception e) { + } catch (Exception e) { _logger.log(Level.FINE, "Error while unbinding JNDI name " + jndiInfo.name + " for EJB : " + this.ejbDescriptor.getName(), e); - } + } } try { - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(loader); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public java.lang.Object run() { - currentThread.setContextClassLoader(loader); - return null; - } - }); - } + currentThread.setContextClassLoader(loader); - if ( isRemote ) { + if (isRemote) { try { - if ( hasRemoteHomeView ) { + if (hasRemoteHomeView) { remoteHomeRefFactory.destroyReference(ejbHomeStub, - ejbHome); + ejbHome); // Hints to release stub-related meta-data in ORB remoteHomeRefFactory.cleanupClass(homeIntf); @@ -4428,20 +4387,20 @@ public java.lang.Object run() { remoteHomeRefFactory.destroy(); } - if ( hasRemoteBusinessView ) { + if (hasRemoteBusinessView) { // Home related cleanup RemoteReferenceFactory remoteBusinessRefFactory = - remoteBusinessIntfInfo.values().iterator(). - next().referenceFactory; + remoteBusinessIntfInfo.values().iterator(). + next().referenceFactory; remoteBusinessRefFactory.destroyReference - (ejbRemoteBusinessHomeStub, ejbRemoteBusinessHome); + (ejbRemoteBusinessHomeStub, ejbRemoteBusinessHome); remoteBusinessRefFactory.cleanupClass(remoteBusinessHomeIntf); remoteBusinessRefFactory.cleanupClass(ejbRemoteBusinessHome.getClass()); // Cleanup for each remote business interface - for(RemoteBusinessIntfInfo next : remoteBusinessIntfInfo.values()) { + for (RemoteBusinessIntfInfo next : remoteBusinessIntfInfo.values()) { next.referenceFactory.cleanupClass(next.generatedRemoteIntf); @@ -4453,44 +4412,33 @@ public java.lang.Object run() { } - } catch ( Exception ex ) { + } catch (Exception ex) { _logger.log(Level.FINE, "Exception during undeploy", logParams); _logger.log(Level.FINE, "", ex); } } - try { - ejbContainerUtilImpl.getComponentEnvManager(). - unbindFromComponentNamespace(ejbDescriptor); - } catch (javax.naming.NamingException namEx) { - _logger.log(Level.FINE, "Exception during undeploy", logParams); - _logger.log(Level.FINE, "", namEx); - } + try { + ejbContainerUtilImpl.getComponentEnvManager(). + unbindFromComponentNamespace(ejbDescriptor); + } catch (javax.naming.NamingException namEx) { + _logger.log(Level.FINE, "Exception during undeploy", logParams); + _logger.log(Level.FINE, "", namEx); + } ejbContainerUtilImpl.unregisterContainer(this); unregisterProbeListeners(); } finally { - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(previousClassLoader); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public java.lang.Object run() { - currentThread.setContextClassLoader(previousClassLoader); - return null; - } - }); - } + currentThread.setContextClassLoader(previousClassLoader); } baseContainerCleanupDone = true; _logger.log(Level.FINE, "**** [BaseContainer]: Successfully Undeployed " + - ejbDescriptor.getName() + " ..."); + ejbDescriptor.getName() + " ..."); } diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/StatefulSessionContainer.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/StatefulSessionContainer.java index 3b63aeee587..0fcfb05fde9 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/StatefulSessionContainer.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/StatefulSessionContainer.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2016-2024] [Payara Foundation and/or its affiliates] package com.sun.ejb.containers; @@ -74,7 +74,23 @@ import com.sun.enterprise.security.SecurityManager; import com.sun.enterprise.transaction.api.JavaEETransaction; import com.sun.enterprise.util.Utility; - +import jakarta.ejb.ConcurrentAccessException; +import jakarta.ejb.ConcurrentAccessTimeoutException; +import jakarta.ejb.CreateException; +import jakarta.ejb.EJBException; +import jakarta.ejb.EJBObject; +import jakarta.ejb.IllegalLoopbackException; +import jakarta.ejb.NoSuchObjectLocalException; +import jakarta.ejb.RemoveException; +import jakarta.ejb.SessionBean; +import jakarta.ejb.SessionSynchronization; +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.PersistenceContextType; +import jakarta.persistence.SynchronizationType; +import jakarta.transaction.Status; +import jakarta.transaction.SystemException; +import jakarta.transaction.Transaction; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -86,7 +102,6 @@ import java.lang.reflect.Method; import java.rmi.RemoteException; import java.security.AccessController; -import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; @@ -98,25 +113,6 @@ import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; - -import jakarta.ejb.ConcurrentAccessException; -import jakarta.ejb.ConcurrentAccessTimeoutException; -import jakarta.ejb.CreateException; -import jakarta.ejb.EJBException; -import jakarta.ejb.EJBObject; -import jakarta.ejb.IllegalLoopbackException; -import jakarta.ejb.NoSuchObjectLocalException; -import jakarta.ejb.RemoveException; -import jakarta.ejb.SessionBean; -import jakarta.ejb.SessionSynchronization; -import jakarta.persistence.EntityManager; -import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.PersistenceContextType; -import jakarta.persistence.SynchronizationType; -import jakarta.transaction.Status; -import jakarta.transaction.SystemException; -import jakarta.transaction.Transaction; - import org.glassfish.api.invocation.ComponentInvocation; import org.glassfish.ejb.LogFacade; import org.glassfish.ejb.deployment.descriptor.EjbDescriptor; @@ -130,15 +126,10 @@ import org.glassfish.ha.store.util.SimpleMetadata; import org.glassfish.logging.annotation.LogMessageInfo; -import static com.sun.ejb.containers.EJBContextImpl.BeanState.DESTROYED; -import static com.sun.ejb.containers.EJBContextImpl.BeanState.INVOKING; -import static com.sun.ejb.containers.EJBContextImpl.BeanState.PASSIVATED; -import static com.sun.ejb.containers.EJBContextImpl.BeanState.READY; +import static com.sun.ejb.containers.EJBContextImpl.BeanState.*; import static com.sun.ejb.spi.sfsb.util.SFSBVersionManager.NO_VERSION; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.FINEST; -import static java.util.logging.Level.WARNING; import static jakarta.persistence.SynchronizationType.SYNCHRONIZED; +import static java.util.logging.Level.*; /** * This class provides container functionality specific to stateful @@ -2905,15 +2896,7 @@ public void run() { try { // We need to set the context class loader for // this (deamon) thread!! - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(myClassLoader); - } else { - PrivilegedAction action = () -> { - currentThread.setContextClassLoader(myClassLoader); - return null; - }; - AccessController.doPrivileged(action); - } + currentThread.setContextClassLoader(myClassLoader); ComponentContext ctx = null; do { @@ -2937,15 +2920,8 @@ public void run() { asyncTaskCount--; } } - if (System.getSecurityManager() == null) { - currentThread.setContextClassLoader(previousClassLoader); - } else { - PrivilegedAction action = () -> { - currentThread.setContextClassLoader(previousClassLoader); - return null; - }; - AccessController.doPrivileged(action); - } + + currentThread.setContextClassLoader(previousClassLoader); } } } diff --git a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/StatelessContainerFactory.java b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/StatelessContainerFactory.java index f4a10e6aa44..1c1dbbb45b8 100644 --- a/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/StatelessContainerFactory.java +++ b/appserver/ejb/ejb-container/src/main/java/com/sun/ejb/containers/StatelessContainerFactory.java @@ -37,12 +37,12 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2024] [Payara Foundation and/or its affiliates] package com.sun.ejb.containers; import com.sun.ejb.Container; import com.sun.ejb.ContainerFactory; -import com.sun.enterprise.security.SecurityManager; import jakarta.inject.Singleton; import org.glassfish.api.deployment.DeploymentContext; import org.glassfish.ejb.deployment.descriptor.EjbDescriptor; @@ -57,9 +57,8 @@ public Container createContainer(EjbDescriptor ejbDescriptor, ClassLoader loader, DeploymentContext deployContext) throws Exception { - SecurityManager sm = getSecurityManager(ejbDescriptor); - StatelessSessionContainer slsbContainer = new StatelessSessionContainer(ejbDescriptor, - loader, sm); + StatelessSessionContainer slsbContainer = new StatelessSessionContainer(ejbDescriptor, loader, getSecurityManager(ejbDescriptor)); + slsbContainer.initializeHome(); slsbContainer.initializeHome(); return slsbContainer; } diff --git a/appserver/ha/ha-file-store/src/main/java/org/glassfish/ha/store/adapter/file/FileBackingStore.java b/appserver/ha/ha-file-store/src/main/java/org/glassfish/ha/store/adapter/file/FileBackingStore.java index a1b206bb3e6..1a680e99758 100644 --- a/appserver/ha/ha-file-store/src/main/java/org/glassfish/ha/store/adapter/file/FileBackingStore.java +++ b/appserver/ha/ha-file-store/src/main/java/org/glassfish/ha/store/adapter/file/FileBackingStore.java @@ -37,19 +37,28 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2019] [Payara Foundation and/or its affiliates] +// Portions Copyright [2019-2024] [Payara Foundation and/or its affiliates] package org.glassfish.ha.store.adapter.file; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; import org.glassfish.ha.store.api.BackingStore; import org.glassfish.ha.store.api.BackingStoreConfiguration; import org.glassfish.ha.store.api.BackingStoreException; import org.glassfish.ha.store.api.BackingStoreFactory; -import java.io.*; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - /** * An implementation of BackingStore that uses file system to * persist any Serializable data @@ -310,20 +319,7 @@ private void touchFile(Object sessionKey, String fileName, long time) } private boolean removeFile(final File file) { - boolean success = false; - if (System.getSecurityManager() == null) { - success = file.delete(); - } else { - success = (Boolean) java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public java.lang.Object run() { - return Boolean.valueOf(file.delete()); - } - } - ); - } - - return success; + return file.delete(); } private byte[] getSerializedState(V value) diff --git a/appserver/orb/orb-iiop/src/main/java/org/glassfish/enterprise/iiop/impl/POARemoteReferenceFactory.java b/appserver/orb/orb-iiop/src/main/java/org/glassfish/enterprise/iiop/impl/POARemoteReferenceFactory.java index 1ed18a5c144..69d836eb7b2 100755 --- a/appserver/orb/orb-iiop/src/main/java/org/glassfish/enterprise/iiop/impl/POARemoteReferenceFactory.java +++ b/appserver/orb/orb-iiop/src/main/java/org/glassfish/enterprise/iiop/impl/POARemoteReferenceFactory.java @@ -37,71 +37,54 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package org.glassfish.enterprise.iiop.impl; -import jakarta.ejb.NoSuchObjectLocalException; - -import java.rmi.Remote; - -import java.security.AccessController ; -import java.security.PrivilegedAction ; - -import org.omg.CORBA.portable.Delegate; - -import org.glassfish.enterprise.iiop.api.RemoteReferenceFactory; - -import org.glassfish.enterprise.iiop.spi.EjbContainerFacade; -import org.glassfish.enterprise.iiop.util.S1ASThreadPoolManager; - -import org.omg.PortableServer.POA ; -import org.omg.PortableServer.Servant ; -import org.omg.PortableServer.ServantLocator ; -import org.omg.PortableServer.ServantLocatorPackage.CookieHolder ; - -import com.sun.logging.LogDomains; - -import com.sun.enterprise.deployment.EjbDescriptor; - -// TODO Only needed for checkpointing -// import com.sun.ejb.base.sfsb.util.EJBServerConfigLookup; - -import com.sun.corba.ee.spi.extension.ServantCachingPolicy; +import com.sun.corba.ee.org.omg.CORBA.SUNVMCID; import com.sun.corba.ee.spi.extension.CopyObjectPolicy; import com.sun.corba.ee.spi.extension.RequestPartitioningPolicy; -import com.sun.corba.ee.spi.threadpool.ThreadPoolManager; - -import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; - -import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; -import com.sun.corba.ee.spi.oa.rfm.ReferenceFactory ; -import com.sun.corba.ee.spi.oa.rfm.ReferenceFactoryManager ; - -import com.sun.corba.ee.spi.misc.ORBConstants; -import com.sun.corba.ee.org.omg.CORBA.SUNVMCID; +import com.sun.corba.ee.spi.extension.ServantCachingPolicy; import com.sun.corba.ee.spi.extension.ZeroPortPolicy; import com.sun.corba.ee.spi.ior.IOR; import com.sun.corba.ee.spi.ior.ObjectKey; import com.sun.corba.ee.spi.ior.TaggedProfile; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactory; +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactoryManager; import com.sun.corba.ee.spi.orb.ORB; - +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; +import com.sun.corba.ee.spi.threadpool.ThreadPoolManager; +import com.sun.enterprise.deployment.EjbDescriptor; import com.sun.enterprise.util.Utility; - -import org.glassfish.pfl.dynamic.codegen.spi.Wrapper ; -import java.util.List; -import java.util.ArrayList; -import java.util.logging.Level; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; +import com.sun.logging.LogDomains; +import jakarta.ejb.NoSuchObjectLocalException; import java.io.IOException; import java.io.NotSerializableException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.rmi.Remote; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; import javax.rmi.CORBA.Tie; import javax.rmi.CORBA.Util; +import org.glassfish.enterprise.iiop.api.RemoteReferenceFactory; +import org.glassfish.enterprise.iiop.spi.EjbContainerFacade; +import org.glassfish.enterprise.iiop.util.S1ASThreadPoolManager; +import org.glassfish.pfl.dynamic.codegen.spi.Wrapper; import org.omg.CORBA.CompletionStatus; import org.omg.CORBA.OBJECT_NOT_EXIST; import org.omg.CORBA.Policy; +import org.omg.CORBA.portable.Delegate; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.ServantLocator; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder; /** * This class implements the RemoteReferenceFactory interface for the @@ -380,22 +363,7 @@ public Remote createHomeReference(byte[] homeKey) } private void setClassLoader() { - ClassLoader cl ; - SecurityManager sman = System.getSecurityManager() ; - if (sman == null) { - cl = this.getClass().getClassLoader() ; - } else { - cl = AccessController.doPrivileged( - new PrivilegedAction() { - @Override - public ClassLoader run() { - return this.getClass().getClassLoader() ; - } - } - ) ; - } - - Wrapper._setClassLoader( cl ) ; + Wrapper._setClassLoader(this.getClass().getClassLoader()); } private Remote createRef(byte[] instanceKey, ReferenceFactory rf, diff --git a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/MappingPolicy.java b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/MappingPolicy.java index c097d2e8ac9..869037bf7eb 100644 --- a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/MappingPolicy.java +++ b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/MappingPolicy.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portion Copyright [2018] Payara Foundation and/or affiliates +// Portion Copyright [2024] Payara Foundation and/or affiliates /* * MappingPolicy.java @@ -47,10 +47,12 @@ package com.sun.jdo.spi.persistence.generator.database; +import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.io.BufferedInputStream; import java.io.FileInputStream; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; +import java.sql.Types; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; @@ -61,17 +63,10 @@ import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.sql.Types; - -import org.glassfish.persistence.common.I18NHelper; import org.glassfish.common.util.StringHelper; - -import com.sun.jdo.spi.persistence.utility.logging.Logger; - -import org.glassfish.persistence.common.database.DBVendorTypeHelper; import org.glassfish.persistence.common.DatabaseConstants; +import org.glassfish.persistence.common.I18NHelper; +import org.glassfish.persistence.common.database.DBVendorTypeHelper; // XXX Capitalization of acronyms such as Jdbc vs. JDBC is inconsistent // throught out this package. @@ -653,22 +648,16 @@ private InputStream getInputStream(String resourceName, boolean override) throws } else { final ClassLoader loader = MappingPolicy.class.getClassLoader(); - in = (InputStream) AccessController.doPrivileged( - (PrivilegedAction) () -> { - Object rc = null; - if (loader != null) { - rc =loader.getResourceAsStream( - resourceName); - } else { - rc = - ClassLoader.getSystemResourceAsStream( - resourceName); - } - return rc; - }); + if (loader != null) { + in = loader.getResourceAsStream(resourceName); + } else { + in = ClassLoader.getSystemResourceAsStream(resourceName); + } + + if (in == null) { throw new IOException(I18NHelper.getMessage(messages, - "EXC_ResourceNotFound", resourceName));// NOI18N + "EXC_ResourceNotFound", resourceName));// NOI18N } } return in; diff --git a/appserver/persistence/common/src/main/java/org/glassfish/persistence/common/database/PropertyHelper.java b/appserver/persistence/common/src/main/java/org/glassfish/persistence/common/database/PropertyHelper.java index 29426280be8..4094ea58799 100644 --- a/appserver/persistence/common/src/main/java/org/glassfish/persistence/common/database/PropertyHelper.java +++ b/appserver/persistence/common/src/main/java/org/glassfish/persistence/common/database/PropertyHelper.java @@ -37,28 +37,21 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright 2024 Payara Foundation and/or its affiliates package org.glassfish.persistence.common.database; -import org.glassfish.persistence.common.I18NHelper; - -import java.util.Properties; -import java.util.ResourceBundle; -import java.util.logging.Level; -import java.util.logging.Logger; - +import com.sun.logging.LogDomains; import java.io.BufferedInputStream; import java.io.FileInputStream; -import java.io.InputStream; import java.io.FileNotFoundException; import java.io.IOException; - -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; -import java.security.PrivilegedActionException; - -import com.sun.logging.LogDomains; +import java.io.InputStream; +import java.util.Properties; +import java.util.ResourceBundle; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.glassfish.persistence.common.I18NHelper; /** * @author Mitesh Meswani @@ -146,40 +139,20 @@ private static void load(Properties properties, final String resourceName, /** * Open fileName as input stream inside doPriviledged block */ - private static InputStream openFileInputStream(final String fileName) throws java.io.FileNotFoundException { - try { - return (InputStream) AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public Object run() throws FileNotFoundException { - return new FileInputStream(fileName); - } - } - ); - } catch (PrivilegedActionException e) { - // e.getException() should be an instance of FileNotFoundException, - // as only "checked" exceptions will be "wrapped" in a - // PrivilegedActionException. - throw (FileNotFoundException) e.getException(); - } - + private static InputStream openFileInputStream(final String fileName) throws java.io.FileNotFoundException { + return new FileInputStream(fileName); } /** * Open resourcenName as input stream inside doPriviledged block */ - private static InputStream openResourceInputStream(final String resourceName, final ClassLoader classLoader) - throws java.io.FileNotFoundException { - return (InputStream) AccessController.doPrivileged( - new PrivilegedAction() { - public Object run() { - if (classLoader != null) { - return classLoader.getResourceAsStream(resourceName); - } else { - return ClassLoader.getSystemResourceAsStream(resourceName); - } - } - } - ); + private static InputStream openResourceInputStream(final String resourceName, final ClassLoader classLoader) + throws FileNotFoundException { + if (classLoader != null) { + return classLoader.getResourceAsStream(resourceName); + } + + return ClassLoader.getSystemResourceAsStream(resourceName); } } diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java index 4d4a6c75477..33da5de6b07 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java @@ -1686,19 +1686,7 @@ public void run() { try { //We need to set the context class loader for this //(deamon) thread!! - if(System.getSecurityManager() == null) { - currentThread.setContextClassLoader(myClassLoader); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public java.lang.Object run() { - currentThread.setContextClassLoader(myClassLoader); - return null; - } - } - ); - } + currentThread.setContextClassLoader(myClassLoader); ComponentContext ctx = null; do { @@ -1724,19 +1712,7 @@ public java.lang.Object run() { synchronized (asyncTaskSemaphore) { addedASyncTask = false; } - if(System.getSecurityManager() == null) { - currentThread.setContextClassLoader(previousClassLoader); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public java.lang.Object run() { - currentThread.setContextClassLoader(previousClassLoader); - return null; - } - } - ); - } + currentThread.setContextClassLoader(previousClassLoader); } } } @@ -2820,24 +2796,12 @@ public void handleBatchOverflow(ArrayList paramKeys) { public void run() { final Thread currentThread = Thread.currentThread(); final ClassLoader previousClassLoader = - currentThread.getContextClassLoader(); + currentThread.getContextClassLoader(); final ClassLoader myClassLoader = loader; try { - //We need to set the context class loader for this (deamon) thread!! - if(System.getSecurityManager() == null) { - currentThread.setContextClassLoader(myClassLoader); - } else { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - @Override - public java.lang.Object run() { - currentThread.setContextClassLoader(myClassLoader); - return null; - } - } - ); - } + //We need to set the context class loader for this (deamon) thread!! + currentThread.setContextClassLoader(myClassLoader); ArrayList localKeys = null; do { @@ -2852,7 +2816,7 @@ public java.lang.Object run() { } int maxIndex = localKeys.size(); - for (int i=0; i + *

    * This class allows deployed applications to supply a name and password directly to the security service. This info * will be used to attempt to login to the current realm. If authentication succeeds, a security context is established * as this user. * - *

    + *

    * This allows applications to programmatically handle authentication. The use of this mechanism is not recommended * since it bypasses the standard Java EE mechanisms and places all burden on the application developer. * - *

    + *

    * Invoking this method requires the permission ProgrammaticLoginPermission with the method name being invoked. * - *

    + *

    * There are two forms of the login method, one which includes the HTTP request and response objects for use by servlets * and one which can be used by EJBs. - * - * */ @Service @PerLookup @@ -110,14 +98,13 @@ public ProgrammaticLogin() { } - // ############################## EJB login methods ############################### /** * Attempt to login for EJB (either as client to login for a remote server, or on the server itself) * - *

    + *

    * Upon successful return from this method the SecurityContext will be set in the name of the given user as its Subject. * *

    @@ -132,7 +119,7 @@ public ProgrammaticLogin() { *

    * Note: Use of the char[] as password is encouraged * - * @param user User name. + * @param user User name. * @param password Password for user. * @return Boolean containing true or false to indicate success or failure of login. */ @@ -143,19 +130,19 @@ public Boolean login(String user, String password) { /** * Attempt to login for EJB (either client or server) * - *

    + *

    * Upon successful return from this method the SecurityContext will be set in the name of the given user as its Subject. * *

    * On client side, the actual login will not occur until we actually access a resource requiring a login. And a * java.rmi.AccessException with COBRA NO_PERMISSION will occur when actual login is failed. * - *

    + *

    * This method is intented primarily for EJBs wishing to do programmatic login. If servlet code used this method the * established identity will be propagated to EJB calls but will not be used for web container manager authorization. In * general servlets should use the servlet-specific version of login instead. * - * @param user User name. + * @param user User name. * @param password Password for user. * @return Boolean containing true or false to indicate success or failure of login. */ @@ -179,7 +166,7 @@ public Boolean login(String user, String password, String realm, boolean errors) /** * Attempt to login. * - *

    + *

    * Upon successful return from this method the SecurityContext will be set in the name of the given user as its Subject. * *

    @@ -187,52 +174,45 @@ public Boolean login(String user, String password, String realm, boolean errors) * access a resource requiring a login. And a java.rmi.AccessException with COBRA NO_PERMISSION will occur when actual * login is failed. * - *

    + *

    * This method is intented primarily for EJBs wishing to do programmatic login. If servlet code used this method the * established identity will be propagated to EJB calls but will not be used for web container manager authorization. In * general servlets should use the servlet-specific version of login instead. * - * @param user User name. + * @param user User name. * @param password Password for user. - * @param realm the realm name in which the user should be logged in. - * @param errors errors=true, propagate any exception encountered to the user errors=false, no exceptions are - * propagated. + * @param realm the realm name in which the user should be logged in. + * @param errors errors=true, propagate any exception encountered to the user errors=false, no exceptions are + * propagated. * @return Boolean containing true or false to indicate success or failure of login. * @throws Exception any exception encountered during Login. */ public Boolean login(String user, char[] password, String realm, boolean errors) throws Exception { - Boolean authenticated = null; + Boolean authenticated = false; try { - // Check permission to login. An exception is thrown on failure checkLoginPermission(user); // Try to login. doPrivileged is used since application code may not have permissions to process the JAAS login. - authenticated = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Boolean run() { - if (isServer()) { - // Login from Server + if (isServer()) { - // Note: If realm is null, WebAndEjbToJaasBridge will log into the default realm - WebAndEjbToJaasBridge.login(user, password, realm); - } else { + // Login from Server - // Login from Client + // Note: If realm is null, WebAndEjbToJaasBridge will log into the default realm + WebAndEjbToJaasBridge.login(user, password, realm); + } else { - executeWithCredentials(user, password, () -> LoginContextDriver.doClientLogin(USERNAME_PASSWORD, handler)); - } + // Login from Client - return true; - } - }); + executeWithCredentials(user, password, () -> LoginContextDriver.doClientLogin(USERNAME_PASSWORD, handler)); + } + return true; } catch (Exception e) { logger.log(SEVERE, "prog.login.failed", e); throwOrFalse(e, errors); } - return authenticated; } @@ -240,7 +220,6 @@ public Boolean run() { * Attempt to logout for EJB. * * @returns Boolean containing true or false to indicate success or failure of logout. - * */ public Boolean logout() { try { @@ -255,37 +234,29 @@ public Boolean logout() { * Attempt to logout for EJB. * * @param errors, errors = true, the method will propagate the exceptions encountered while logging out, errors=false - * will return a Boolean value of false indicating failure of logout + * will return a Boolean value of false indicating failure of logout * @return Boolean containing true or false to indicate success or failure of logout. * @throws Exception encountered while logging out, if errors==false - * */ public Boolean logout(boolean errors) throws Exception { - Boolean loggedout = null; + Boolean loggedout = false; // Check logout permission try { checkLogoutPermission(); + if (SecurityServicesUtil.getInstance() != null && SecurityServicesUtil.getInstance().isServer()) { + WebAndEjbToJaasBridge.logout(); + } else { + // Reset the username/password state on logout + UsernamePasswordStore.reset(); + + LoginContextDriver.doClientLogout(); + + // If a user try to access a protected resource after here + // then it will prompt for password in appclient or + // just fail in the standalone client. + } - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public java.lang.Object run() { - if (SecurityServicesUtil.getInstance() != null && SecurityServicesUtil.getInstance().isServer()) { - WebAndEjbToJaasBridge.logout(); - } else { - // Reset the username/password state on logout - UsernamePasswordStore.reset(); - - LoginContextDriver.doClientLogout(); - - // If a user try to access a protected resource after here - // then it will prompt for password in appclient or - // just fail in the standalone client. - } - - return null; - } - }); - loggedout = true; + return true; } catch (Exception e) { logger.log(WARNING, "prog.logout.failed", e); loggedout = throwOrFalse(e, errors); @@ -295,14 +266,13 @@ public java.lang.Object run() { } - // ############################## Servlet login methods ############################### /** * Attempt to login. This method is specific to the Servlet container. * - *

    + *

    * Upon successful return from this method the SecurityContext will be set in the name of the given user as its Subject. * In addition, the principal stored in the request is set to the user name. If a session is available, its principal is * also set to the user provided. @@ -310,15 +280,15 @@ public java.lang.Object run() { *

    * Note: Use of the char[] as password is encouraged * - * @returns Boolean containing true or false to indicate success or failure of login. * @param realm * @param errors - * @param user User name. + * @param user User name. * @param password Password for user. - * @param request HTTP request object provided by caller application. It should be an instance of HttpRequestFacade. + * @param request HTTP request object provided by caller application. It should be an instance of HttpRequestFacade. * @param response HTTP response object provided by called application. It should be an instance of HttpServletResponse. - * @throws Exception any exceptions encountered during login * @return Boolean indicating true for successful login and false otherwise + * @throws Exception any exceptions encountered during login + * @returns Boolean containing true or false to indicate success or failure of login. */ public Boolean login(String user, String password, String realm, HttpServletRequest request, HttpServletResponse response, boolean errors) throws Exception { return login(user, password.toCharArray(), realm, request, response, errors); @@ -334,17 +304,16 @@ public Boolean login(String user, String password, HttpServletRequest request, H /** * Attempt to login. This method is specific to Servlets (and JSPs). * - *

    + *

    * Upon successful return from this method the SecurityContext will be set in the name of the given user as its Subject. * In addition, the principal stored in the request is set to the user name. If a session is available, its principal is * also set to the user provided. * - * @param user User name. + * @param user User name. * @param password Password for user. - * @param request HTTP request object provided by caller application. It should be an instance of HttpRequestFacade. + * @param request HTTP request object provided by caller application. It should be an instance of HttpRequestFacade. * @param response HTTP response object provided by called application. It should be an instance of HttpServletResponse. * @return Boolean containing true or false to indicate success or failure of login. - * */ public Boolean login(String user, char[] password, HttpServletRequest request, HttpServletResponse response) { try { @@ -359,20 +328,20 @@ public Boolean login(String user, char[] password, HttpServletRequest request, H /** * Attempt to login. This method is specific to servlets (and JSPs). * - *

    + *

    * Upon successful return from this method the SecurityContext will be set in the name of the given user as its Subject. * In addition, the principal stored in the request is set to the user name. If a session is available, its principal is * also set to the user provided. * - * @returns Boolean containing true or false to indicate success or failure of login. * @param realm * @param errors - * @param user User name. + * @param user User name. * @param password Password for user. - * @param request HTTP request object provided by caller application. It should be an instance of HttpRequestFacade. + * @param request HTTP request object provided by caller application. It should be an instance of HttpRequestFacade. * @param response HTTP response object provided by called application. It should be an instance of HttpServletResponse. - * @throws Exception any exceptions encountered during login * @return Boolean indicating true for successful login and false otherwise + * @throws Exception any exceptions encountered during login + * @returns Boolean containing true or false to indicate success or failure of login. */ public Boolean login(String user, char[] password, String realm, HttpServletRequest request, HttpServletResponse response, boolean errors) throws Exception { try { @@ -381,7 +350,7 @@ public Boolean login(String user, char[] password, String realm, HttpServletRequ // Try to login. privilegedAlways is used since application code does // not have permissions to process the jaas login. - return privilegedAlways(() -> webProgrammaticLogin.login(user, password, realm, request, response)); + return webProgrammaticLogin.login(user, password, realm, request, response); } catch (Exception e) { return throwOrFalse(e, errors); } @@ -391,7 +360,6 @@ public Boolean login(String user, char[] password, String realm, HttpServletRequ * Attempt to logout. Also removes principal from request (and session if available). * * @returns Boolean containing true or false to indicate success or failure of logout. - * */ public Boolean logout(HttpServletRequest request, HttpServletResponse response) { try { @@ -406,8 +374,7 @@ public Boolean logout(HttpServletRequest request, HttpServletResponse response) * Attempt to logout. Also removes principal from request (and session if available). * * @param errors, errors = true, the method will propagate the exceptions encountered while logging out, errors=false - * will return a Boolean value of false indicating failure of logout - * + * will return a Boolean value of false indicating failure of logout * @return Boolean containing true or false to indicate success or failure of logout. * @throws Exception, exception encountered while logging out and if errors == true */ @@ -415,22 +382,13 @@ public Boolean logout(HttpServletRequest request, HttpServletResponse response, try { // check logout permission checkLogoutPermission(); - - return doPrivileged(new PrivilegedExceptionAction() { - @Override - public Boolean run() throws Exception { - return webProgrammaticLogin.logout(request, response); - } - }); + return webProgrammaticLogin.logout(request, response); } catch (Exception e) { return throwOrFalse(e, errors); } } - - - // ############################## Private methods ############################### @@ -455,7 +413,6 @@ private void executeWithCredentials(String user, char[] password, Runnable actio /** * Check whether caller has login permission. - * */ private void checkLoginPermission(String user) throws Exception { try { @@ -476,7 +433,6 @@ private void checkLoginPermission(String user) throws Exception { /** * Check if caller has logout permission. - * */ private void checkLogoutPermission() throws Exception { try { @@ -498,7 +454,7 @@ private void resolveWebProgrammaticLogin() { } private boolean isServer() { - return(((SecurityServicesUtil.getInstance() != null) && SecurityServicesUtil.getInstance().isServer()) || Util.isEmbeddedServer()); + return (((SecurityServicesUtil.getInstance() != null) && SecurityServicesUtil.getInstance().isServer()) || Util.isEmbeddedServer()); } private boolean throwOrFalse(Exception e, boolean errors) throws Exception { diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCache.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCache.java index 50f655fc1fb..e138c182580 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCache.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/cache/PermissionCache.java @@ -40,27 +40,22 @@ // Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.ee.authorization.cache; -import static java.util.Collections.list; -import static java.util.logging.Level.SEVERE; - +import com.sun.logging.LogDomains; +import jakarta.security.jacc.Policy; +import jakarta.security.jacc.PolicyContext; +import jakarta.security.jacc.PolicyFactory; import java.security.AllPermission; -import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; -import jakarta.security.jacc.Policy; import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; -import jakarta.security.jacc.PolicyContext; - -import com.sun.enterprise.security.common.AppservAccessController; -import com.sun.logging.LogDomains; -import jakarta.security.jacc.PolicyFactory; +import static java.util.Collections.list; +import static java.util.logging.Level.SEVERE; /** * This class is @@ -335,13 +330,7 @@ public synchronized void reset() { } private void setPolicyContextID(final String newID) throws PrivilegedActionException { - AppservAccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - PolicyContext.setContextID(newID); - return null; - } - }); + PolicyContext.setContextID(newID); } // Use implies to resolve unresolved permissions diff --git a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/ConnectionExecutionContext.java b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/ConnectionExecutionContext.java index fcdee092e72..1ab7b668ecc 100644 --- a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/ConnectionExecutionContext.java +++ b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/ConnectionExecutionContext.java @@ -37,11 +37,9 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.iiop.security; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Hashtable; /** @@ -60,13 +58,7 @@ public class ConnectionExecutionContext { public static final String IIOP_CLIENT_PER_THREAD_FLAG = "com.sun.appserv.iiopclient.perthreadauth"; - private static final boolean isPerThreadAuth = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Boolean run() { - return Boolean.valueOf(Boolean.getBoolean(IIOP_CLIENT_PER_THREAD_FLAG)); - } - - }); + private static final boolean isPerThreadAuth = Boolean.getBoolean(IIOP_CLIENT_PER_THREAD_FLAG); private static final ThreadLocal> currentContext = isPerThreadAuth ? new ThreadLocal<>() : new InheritableThreadLocal<>(); diff --git a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecClientRequestInterceptor.java b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecClientRequestInterceptor.java index b85556d60e0..97ca7dca2fd 100644 --- a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecClientRequestInterceptor.java +++ b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecClientRequestInterceptor.java @@ -60,6 +60,12 @@ import com.sun.enterprise.security.auth.login.common.X509CertificateCredential; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.logging.LogDomains; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Iterator; +import java.util.Set; +import java.util.logging.Level; +import javax.security.auth.x500.X500Principal; import org.glassfish.enterprise.iiop.api.GlassFishORBHelper; import org.omg.CORBA.Any; import org.omg.CORBA.ORB; @@ -74,15 +80,6 @@ import org.omg.PortableInterceptor.TRANSPORT_RETRY; import org.omg.PortableInterceptor.USER_EXCEPTION; -import javax.security.auth.x500.X500Principal; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Iterator; -import java.util.Set; -import java.util.logging.Level; - import static java.util.Arrays.asList; /** @@ -286,51 +283,39 @@ public void send_request(ClientRequestInfo ri) throws ForwardRequest { /* CDR encoded Security Attribute Service element */ byte[] cdr_encoded_saselm = null; - java.lang.Object cred = null; // A single JAAS credential + Object cred = null; // A single JAAS credential if (_logger.isLoggable(Level.FINE)) _logger.log(Level.FINE, "++++ Entered " + prname + "send_request" + "()"); - SecurityContext secctxt = null; // SecurityContext to be sent + SecurityContext securityContext = null; // SecurityContext to be sent ORB orb = orbHelper.getORB(); org.omg.CORBA.Object effective_target = ri.effective_target(); try { - secctxt = secContextUtil.getSecurityContext(effective_target); - } catch (InvalidMechanismException ime) { + securityContext = secContextUtil.getSecurityContext(effective_target); + } catch (InvalidMechanismException | InvalidIdentityTokenException ime) { _logger.log(Level.SEVERE, "iiop.sec_context_exception", ime); throw new RuntimeException(ime.getMessage()); - } catch (InvalidIdentityTokenException iite) { - _logger.log(Level.SEVERE, "iiop.runtime_exception", iite); - throw new RuntimeException(iite.getMessage()); - } + } /** * In an unprotected invocation, there is nothing to be sent to the service context field. Check for * this case. */ - if (secctxt == null) { + if (securityContext == null) { if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, "Security context is null (nothing to add to service context)"); } return; } - - final SecurityContext sCtx = secctxt; + /* Construct an authentication token */ - if (secctxt.authcls != null) { - cred = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public java.lang.Object run() { - return getCred(sCtx.subject.getPrivateCredentials(sCtx.authcls), sCtx.authcls); - } - }); - + if (securityContext.authcls != null) { + cred = getCred(securityContext.subject.getPrivateCredentials(securityContext.authcls), securityContext.authcls); + try { - - SecurityMechanismSelector sms = Lookups.getSecurityMechanismSelector(); - ConnectionContext cc = sms.getClientConnectionContext(); - CompoundSecMech mech = cc.getMechanism(); - - cAuthenticationToken = createAuthToken(cred, secctxt.authcls, orb, mech); + + CompoundSecMech mech = Lookups.getSecurityMechanismSelector().getClientConnectionContext().getMechanism(); + cAuthenticationToken = createAuthToken(cred, securityContext.authcls, orb, mech); } catch (Exception e) { _logger.log(Level.SEVERE, "iiop.createauthtoken_exception", e); throw new SecurityException(localStrings.getLocalString("secclientreqinterceptor.err_authtok_create", @@ -339,10 +324,10 @@ public java.lang.Object run() { } /* Construct an identity token */ - if (secctxt.identcls != null) { - cred = getCred(secctxt.subject.getPublicCredentials(secctxt.identcls), secctxt.identcls); + if (securityContext.identcls != null) { + cred = getCred(securityContext.subject.getPublicCredentials(securityContext.identcls), securityContext.identcls); try { - cIdentityToken = createIdToken(cred, secctxt.identcls, orb); + cIdentityToken = createIdToken(cred, securityContext.identcls, orb); } catch (Exception e) { _logger.log(Level.SEVERE, "iiop.createidtoken_exception", e); throw new SecurityException(localStrings.getLocalString("secclientreqinterceptor.err_idtok_create", diff --git a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecServerRequestInterceptor.java b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecServerRequestInterceptor.java index a28b6a22ebd..3f84485748e 100644 --- a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecServerRequestInterceptor.java +++ b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecServerRequestInterceptor.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright 2018-2022 Payara Foundation and/or its affiliates +// Portions Copyright 2018-2024 Payara Foundation and/or its affiliates // Payara Foundation and/or its affiliates elects to include this software in this distribution under the GPL Version 2 license package com.sun.enterprise.iiop.security; @@ -68,6 +68,17 @@ import com.sun.enterprise.security.auth.realm.certificate.OID; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.logging.LogDomains; +import java.io.ByteArrayInputStream; +import java.net.Socket; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Hashtable; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.security.auth.Subject; +import javax.security.auth.x500.X500Principal; import org.glassfish.enterprise.iiop.api.GlassFishORBHelper; import org.omg.CORBA.Any; import org.omg.CORBA.BAD_PARAM; @@ -79,23 +90,9 @@ import org.omg.PortableInterceptor.ServerRequestInfo; import org.omg.PortableInterceptor.ServerRequestInterceptor; -import javax.security.auth.Subject; -import javax.security.auth.x500.X500Principal; -import java.io.ByteArrayInputStream; -import java.net.Socket; -import java.security.PrivilegedAction; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Hashtable; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - import static com.sun.enterprise.iiop.security.GSSUtils.GSSUP_MECH_OID; import static com.sun.enterprise.iiop.security.GSSUtils.verifyMechOID; import static com.sun.enterprise.iiop.security.SecurityContextUtil.STATUS_FAILED; -import static java.security.AccessController.doPrivileged; import static java.util.logging.Level.FINE; import static java.util.logging.Level.SEVERE; @@ -407,15 +404,8 @@ private void createAuthCredential(SecurityContext securityContext, byte[] authTo logger.log(FINE, "Password credential = " + passwordCredential.toString()); logger.log(FINE, "Adding PasswordCredential to subject's PrivateCredentials"); } - - doPrivileged(new PrivilegedAction() { - @Override - public java.lang.Object run() { - securityContext.subject.getPrivateCredentials().add(passwordCredential); - return null; - } - }); - + + securityContext.subject.getPrivateCredentials().add(passwordCredential); securityContext.authcls = PasswordCredential.class; } diff --git a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecurityContextUtil.java b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecurityContextUtil.java index 1f15f0e7e01..f7fb53f72d4 100644 --- a/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecurityContextUtil.java +++ b/appserver/security/ejb.security/src/main/java/com/sun/enterprise/iiop/security/SecurityContextUtil.java @@ -40,32 +40,27 @@ // Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.iiop.security; -import static com.sun.corba.ee.spi.presentation.rmi.StubAdapter.isLocal; -import static com.sun.corba.ee.spi.presentation.rmi.StubAdapter.isStub; -import static com.sun.enterprise.security.common.AppservAccessController.privilegedAlways; -import static java.util.logging.Level.FINE; -import static java.util.logging.Level.SEVERE; - -import java.net.Socket; -import jakarta.security.jacc.Policy; -import java.util.logging.Level; - +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.enterprise.common.iiop.security.SecurityContext; +import com.sun.enterprise.security.CORBAObjectPermission; +import com.sun.enterprise.security.auth.WebAndEjbToJaasBridge; +import com.sun.logging.LogDomains; import jakarta.inject.Inject; import jakarta.inject.Singleton; -import javax.security.auth.Subject; - import jakarta.security.jacc.PolicyFactory; +import java.net.Socket; +import java.util.logging.Level; +import javax.security.auth.Subject; import org.glassfish.enterprise.iiop.api.GlassFishORBHelper; import org.glassfish.enterprise.iiop.api.ProtocolManager; import org.glassfish.hk2.api.PostConstruct; import org.jvnet.hk2.annotations.Service; -import com.sun.corba.ee.spi.ior.IOR; -import com.sun.corba.ee.spi.orb.ORB; -import com.sun.enterprise.common.iiop.security.SecurityContext; -import com.sun.enterprise.security.CORBAObjectPermission; -import com.sun.enterprise.security.auth.WebAndEjbToJaasBridge; -import com.sun.logging.LogDomains; +import static com.sun.corba.ee.spi.presentation.rmi.StubAdapter.isLocal; +import static com.sun.corba.ee.spi.presentation.rmi.StubAdapter.isStub; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.SEVERE; /** * This class provides has the helper methods to deal with the SecurityContext. This represents the @@ -84,7 +79,6 @@ public class SecurityContextUtil implements PostConstruct { private static java.util.logging.Logger _logger = LogDomains.getLogger(SecurityContextUtil.class, LogDomains.SECURITY_LOGGER); private static String IS_A = "_is_a"; - private Policy policy; @Inject private GlassFishORBHelper orbHelper; @@ -94,7 +88,6 @@ public class SecurityContextUtil implements PostConstruct { @Override public void postConstruct() { - privilegedAlways(() -> policy = PolicyFactory.getPolicyFactory().getPolicy()); } /** @@ -108,7 +101,7 @@ public SecurityContext getSecurityContext(org.omg.CORBA.Object effectiveTarget) if (isStub(effectiveTarget) && isLocal(effectiveTarget)) { // XXX: Workaround for non-null connection object ri for local invocation. - ConnectionExecutionContext.setClientThreadID(Thread.currentThread().getId()); + ConnectionExecutionContext.setClientThreadID(Thread.currentThread().threadId()); return null; } @@ -143,7 +136,9 @@ public static void receivedReply(int reply_status, org.omg.CORBA.Object effectiv _logger.log(FINE, "Failed status"); // what kind of exception should we throw? throw new RuntimeException("Target did not accept security context"); - } else if (reply_status == STATUS_RETRY) { + } + + if (reply_status == STATUS_RETRY) { _logger.log(FINE, "Retry status"); } else { _logger.log(FINE, "Passed status"); @@ -198,8 +193,7 @@ public int setSecurityContext(SecurityContext context, byte[] objectId, String m */ private void authenticate(Subject subject, Class credentialClass) throws SecurityMechanismException { try { - privilegedAlways(() -> WebAndEjbToJaasBridge.login(subject, credentialClass)); - + WebAndEjbToJaasBridge.login(subject, credentialClass); } catch (Exception e) { if (_logger.isLoggable(SEVERE)) { _logger.log(SEVERE, "iiop.login_exception", e.toString()); @@ -212,30 +206,32 @@ private void authenticate(Subject subject, Class credentialClass) throws Secu // return true if authorization succeeds, false otherwise. private boolean authorizeCORBA(byte[] objectId, String method) throws Exception { - + ProtocolManager protocolManager = orbHelper.getProtocolManager(); - + // Check to make sure protocolManager is not null. // This could happen during server initialization or if this call // is on a callback object in the client VM. if (protocolManager == null) { return true; } - + // Check if target is an EJB if (protocolManager.getEjbDescriptor(objectId) != null) { return true; // an EJB object } - // Create the permission we want to check for - CORBAObjectPermission permission = new CORBAObjectPermission("*", method); - + + com.sun.enterprise.security.SecurityContext securityContext = com.sun.enterprise.security.SecurityContext.getCurrent(); + // Check if policy gives principal the permissions - boolean result = policy.implies(permission, com.sun.enterprise.security.SecurityContext.getCurrent().getPrincipalSet()); + boolean result = PolicyFactory.getPolicyFactory().getPolicy().implies( + new CORBAObjectPermission("*", method), + securityContext.getPrincipalSet()); if (_logger.isLoggable(FINE)) { _logger.log(FINE, "CORBA Object permission evaluation result=" + result + " for method=" + method); } - + return result; } diff --git a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java index ac1e33d6bc7..5b4df9b8d78 100644 --- a/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java +++ b/appserver/security/webintegration/src/main/java/com/sun/web/security/RealmAdapter.java @@ -1751,8 +1751,8 @@ private SecurityContext getSecurityContextForPrincipal(Principal principal) { return null; } - if (principal instanceof WebPrincipal) { - return ((WebPrincipal) principal).getSecurityContext(); + if (principal instanceof WebPrincipal webPrincipal) { + return webPrincipal.getSecurityContext(); } Subject subject = new Subject(); diff --git a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java index 438296b47b3..3c7f462c72c 100644 --- a/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java +++ b/appserver/security/webservices.security/src/main/java/com/sun/enterprise/security/jauth/jaspic/provider/config/SoapAuthenticationService.java @@ -40,47 +40,6 @@ // Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.jauth.jaspic.provider.config; -import static com.sun.enterprise.security.webservices.PipeConstants.BINDING; -import static com.sun.enterprise.security.webservices.PipeConstants.ENDPOINT; -import static com.sun.enterprise.security.webservices.PipeConstants.SEI_MODEL; -import static com.sun.enterprise.security.webservices.PipeConstants.SERVICE_ENDPOINT; -import static com.sun.xml.ws.api.SOAPVersion.SOAP_11; - -import com.sun.enterprise.security.appclient.ConfigXMLParser; -import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; -import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; -import jakarta.security.auth.message.MessagePolicy; -import java.lang.reflect.Method; -import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.Map; - -import java.util.function.BiFunction; -import java.util.function.Function; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import jakarta.security.auth.message.AuthException; -import jakarta.security.auth.message.AuthStatus; -import jakarta.security.auth.message.MessageInfo; -import jakarta.security.auth.message.config.ClientAuthConfig; -import jakarta.security.auth.message.config.ClientAuthContext; -import jakarta.security.auth.message.config.ServerAuthConfig; -import jakarta.security.auth.message.config.ServerAuthContext; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.xml.bind.UnmarshalException; -import jakarta.xml.ws.WebServiceException; -import jakarta.xml.ws.handler.MessageContext; - -import org.glassfish.api.invocation.ComponentInvocation; -import org.glassfish.api.invocation.InvocationManager; -import org.glassfish.deployment.common.ModuleDescriptor; -import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; -import org.glassfish.epicyro.services.BaseAuthenticationService; -import org.glassfish.epicyro.services.RegistrationWrapperRemover; -import org.glassfish.internal.api.Globals; - import com.sun.enterprise.deployment.Application; import com.sun.enterprise.deployment.BundleDescriptor; import com.sun.enterprise.deployment.EjbDescriptor; @@ -90,12 +49,14 @@ import com.sun.enterprise.deployment.runtime.common.MessageSecurityBindingDescriptor; import com.sun.enterprise.security.SecurityContext; import com.sun.enterprise.security.SecurityServicesUtil; +import com.sun.enterprise.security.appclient.ConfigXMLParser; import com.sun.enterprise.security.audit.AuditManager; -import com.sun.enterprise.security.common.AppservAccessController; import com.sun.enterprise.security.common.ClientSecurityContext; import com.sun.enterprise.security.ee.audit.AppServerAuditManager; -import com.sun.enterprise.security.ee.authorization.EJBPolicyContextDelegate; +import com.sun.enterprise.security.ee.authentication.jakarta.AuthMessagePolicy; +import com.sun.enterprise.security.ee.authentication.jakarta.ConfigDomainParser; import com.sun.enterprise.security.ee.authentication.jakarta.WebServicesDelegate; +import com.sun.enterprise.security.ee.authorization.EJBPolicyContextDelegate; import com.sun.enterprise.security.webservices.PipeConstants; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.io.FileUtils; @@ -109,6 +70,35 @@ import com.sun.xml.ws.api.model.SEIModel; import com.sun.xml.ws.api.model.wsdl.WSDLPort; import com.sun.xml.ws.api.server.WSEndpoint; +import jakarta.security.auth.message.AuthException; +import jakarta.security.auth.message.AuthStatus; +import jakarta.security.auth.message.MessageInfo; +import jakarta.security.auth.message.MessagePolicy; +import jakarta.security.auth.message.config.ClientAuthConfig; +import jakarta.security.auth.message.config.ClientAuthContext; +import jakarta.security.auth.message.config.ServerAuthConfig; +import jakarta.security.auth.message.config.ServerAuthContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.xml.bind.UnmarshalException; +import jakarta.xml.ws.WebServiceException; +import jakarta.xml.ws.handler.MessageContext; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; +import javax.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import org.glassfish.api.invocation.ComponentInvocation; +import org.glassfish.api.invocation.InvocationManager; +import org.glassfish.deployment.common.ModuleDescriptor; +import org.glassfish.epicyro.config.module.configprovider.GFServerConfigProvider; +import org.glassfish.epicyro.services.BaseAuthenticationService; +import org.glassfish.epicyro.services.RegistrationWrapperRemover; +import org.glassfish.internal.api.Globals; + +import static com.sun.enterprise.security.webservices.PipeConstants.*; +import static com.sun.xml.ws.api.SOAPVersion.SOAP_11; public class SoapAuthenticationService extends BaseAuthenticationService { @@ -183,9 +173,6 @@ public static Subject getClientSubject() { if (clientSecurityContext != null) { subject = clientSecurityContext.getSubject(); } - if (subject == null) { - subject = Subject.getSubject(AccessController.getContext()); - } } else { SecurityContext securityContext = SecurityContext.getCurrent(); if (securityContext != null && !securityContext.didServerGenerateCredentials()) { @@ -253,17 +240,12 @@ public void authorize(Packet request) throws Exception { final String ejbImplClassName = ejbDescriptor.getEjbImplClassName(); if (ejbImplClassName != null) { try { - m = (Method) AppservAccessController.doPrivileged(new PrivilegedExceptionAction() { - - @Override - public Object run() throws Exception { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - Class clazz = Class.forName(ejbImplClassName, true, loader); - return clazz.getMethod("invoke", new Class[] { Object.class }); - } - }); - } catch (PrivilegedActionException pae) { - throw new RuntimeException(pae.getException()); + m = Class.forName(ejbImplClassName, true, Thread.currentThread() + .getContextClassLoader()) + .getMethod("invoke", new Class[]{Object.class}); + + } catch (ReflectiveOperationException pae) { + throw new RuntimeException(pae); } } } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java index a49d4faf25e..5c309f384b8 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityContext.java @@ -40,39 +40,23 @@ // Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; -import static com.sun.enterprise.security.SecurityLoggerInfo.defaultSecurityContextError; -import static com.sun.enterprise.security.SecurityLoggerInfo.defaultUserLoginError; -import static com.sun.enterprise.security.SecurityLoggerInfo.nullSubjectWarning; -import static com.sun.enterprise.security.SecurityLoggerInfo.securityContextNotChangedError; -import static com.sun.enterprise.security.SecurityLoggerInfo.securityContextPermissionError; -import static com.sun.enterprise.security.SecurityLoggerInfo.securityContextUnexpectedError; -import static com.sun.enterprise.security.common.AppservAccessController.doPrivileged; -import static com.sun.enterprise.security.common.AppservAccessController.privileged; -import static java.util.logging.Level.SEVERE; - -import java.security.AccessController; +import com.sun.enterprise.config.serverbeans.SecurityService; +import com.sun.enterprise.security.auth.login.DistinguishedPrincipalCredential; +import com.sun.enterprise.security.common.AbstractSecurityContext; +import com.sun.enterprise.security.integration.AppServSecurityContext; import java.security.Principal; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; import java.util.Iterator; import java.util.Set; import java.util.logging.Logger; - -import javax.security.auth.AuthPermission; import javax.security.auth.Subject; - import org.glassfish.api.admin.ServerEnvironment; import org.glassfish.hk2.api.PerLookup; import org.glassfish.internal.api.Globals; - import org.glassfish.security.common.UserNameAndPassword; import org.jvnet.hk2.annotations.Service; -import com.sun.enterprise.config.serverbeans.SecurityService; -import com.sun.enterprise.security.auth.login.DistinguishedPrincipalCredential; -import com.sun.enterprise.security.common.AbstractSecurityContext; -import com.sun.enterprise.security.common.AppservAccessController; -import com.sun.enterprise.security.integration.AppServSecurityContext; +import static com.sun.enterprise.security.SecurityLoggerInfo.*; +import static java.util.logging.Level.SEVERE; /** * This class that extends AbstractSecurityContext that gets stored in Thread Local Storage. If the current thread @@ -97,8 +81,6 @@ public class SecurityContext extends AbstractSecurityContext { private static InheritableThreadLocal currentSecurityContext = new InheritableThreadLocal<>(); private static SecurityContext defaultSecurityContext = generateDefaultSecurityContext(); - private static AuthPermission doAsPrivilegedPerm = new AuthPermission("doAsPrivileged"); - // Did the client log in as or did the server generate the context private boolean serverGeneratedCredentials; @@ -134,24 +116,19 @@ public static Principal getDefaultCallerPrincipal() { synchronized (SecurityContext.class) { if (defaultSecurityContext.callerPrincipal == null) { String guestUser = null; - try { - guestUser = (String) doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws Exception { - SecurityService securityService = - SecurityServicesUtil + SecurityService securityService = + SecurityServicesUtil .getInstance() .getHabitat() .getService( - SecurityService.class, ServerEnvironment.DEFAULT_INSTANCE_NAME); - - if (securityService == null) { - return null; - } - - return securityService.getDefaultPrincipal(); - } - }); + SecurityService.class, ServerEnvironment.DEFAULT_INSTANCE_NAME); + + if (securityService == null) { + return null; + } + + guestUser = securityService.getDefaultPrincipal(); } catch (Exception e) { LOGGER.log(SEVERE, defaultUserLoginError, e); } finally { @@ -159,7 +136,7 @@ public Object run() throws Exception { guestUser = "ANONYMOUS"; } } - + defaultSecurityContext.callerPrincipal = new UserNameAndPassword(guestUser); } } @@ -197,21 +174,17 @@ public static SecurityContext getCurrent() { * the corresponding subject. */ public static void setCurrent(SecurityContext securityContext) { - if (securityContext != null && securityContext != defaultSecurityContext) { - - if (securityContext == currentSecurityContext.get()) { - // Context already set, do nothing - return; - } - - if (isPermittedToSetContext()) { - currentSecurityContext.set(securityContext); - } else { - LOGGER.severe(securityContextNotChangedError); - } - } else { + if (securityContext == null || securityContext == defaultSecurityContext) { currentSecurityContext.set(securityContext); + return; } + + SecurityContext current = currentSecurityContext.get(); + if (securityContext == current) { + return; + } + + currentSecurityContext.set(securityContext); } public static void setUnauthenticatedContext() { @@ -237,7 +210,8 @@ public SecurityContext(String username, Subject subject) { Subject localSubject = nullSafeSubject(subject); this.callerPrincipal = new UserNameAndPassword(username); - this.subject = privileged(() -> {localSubject.getPrincipals().add(callerPrincipal); return localSubject;}); + localSubject.getPrincipals().add(callerPrincipal); + this.subject = localSubject; } /** @@ -252,28 +226,34 @@ public SecurityContext(Subject subject) { Subject localSubject = nullSafeSubject(subject); this.subject = localSubject; - - this.callerPrincipal = privileged(() -> { - Principal principal = null; - for (Object publicCredential : localSubject.getPublicCredentials()) { - if (publicCredential instanceof DistinguishedPrincipalCredential) { - DistinguishedPrincipalCredential distinguishedCredential = (DistinguishedPrincipalCredential) publicCredential; - principal = distinguishedCredential.principal(); + + Principal principal = null; + for (Object publicCredential : subject.getPublicCredentials()) { + if (publicCredential instanceof DistinguishedPrincipalCredential distinguishedPrincipalCredential) { + principal = distinguishedPrincipalCredential.principal(); + break; + } + } + + if (principal == null) { + for (Principal publicCredential : subject.getPrincipals()) { + if (publicCredential instanceof DistinguishedPrincipalCredential distinguishedPrincipalCredential) { + principal = distinguishedPrincipalCredential.principal(); break; } } - - // For old auth module - if (principal == null) { - Iterator prinIter = localSubject.getPrincipals().iterator(); - if (prinIter.hasNext()) { - principal = prinIter.next(); - } + } + + // For old auth module + if (principal == null) { + Iterator prinIter = subject.getPrincipals().iterator(); + if (prinIter.hasNext()) { + principal = prinIter.next(); } - - return principal; } - ); + + this.callerPrincipal = principal; + postConstruct(); } @@ -285,9 +265,9 @@ public SecurityContext(String username, Subject subject, String realm) { if (factory != null) { callerPrincipal = factory.getPrincipalInstance(username, realm); } - + + localSubject.getPrincipals().add(callerPrincipal); this.subject = localSubject; - privileged(() -> this.subject.getPrincipals().add(callerPrincipal)); } /* @@ -303,7 +283,7 @@ public SecurityContext() { setServerGeneratedCredentials(); // Read only is only done for guest logins. - privileged(() -> subject.setReadOnly()); + subject.setReadOnly(); } @@ -398,44 +378,19 @@ public String toString() { // ### Private methods - + private static SecurityContext generateDefaultSecurityContext() { synchronized (SecurityContext.class) { try { - return (SecurityContext) AppservAccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws Exception { - return new SecurityContext(); - } - }); + return new SecurityContext(); } catch (Exception e) { LOGGER.log(SEVERE, defaultSecurityContextError, e); } } - + return null; } - private static boolean isPermittedToSetContext() { - try { - checkIsPriviledged(); - return true; - } catch (SecurityException se) { - LOGGER.log(SEVERE, securityContextPermissionError, se); - } catch (Throwable t) { - LOGGER.log(SEVERE, securityContextUnexpectedError, t); - } - - return false; - } - - private static void checkIsPriviledged() { - java.lang.SecurityManager securityManager = System.getSecurityManager(); - if (securityManager != null) { - LOGGER.fine("permission check done to set SecurityContext"); - securityManager.checkPermission(doAsPrivilegedPerm); - } - } - private Subject nullSafeSubject(Subject subject) { if (subject == null) { subject = new Subject(); @@ -459,18 +414,16 @@ private SecurityContext getSecurityContextForPrincipal(Principal principal) { if (principal == null) { return null; } - + if (principal instanceof SecurityContextProxy) { return ((SecurityContextProxy) principal).getSecurityContext(); } - - return AccessController.doPrivileged(new PrivilegedAction() { - public SecurityContext run() { - Subject subject = new Subject(); - subject.getPrincipals().add(principal); - - return new SecurityContext(principal.getName(), subject); - } - }); + + + Subject subject = new Subject(); + subject.getPrincipals().add(principal); + + return new SecurityContext(principal.getName(), subject); } + } diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityLoggerInfo.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityLoggerInfo.java index e36001afb09..be4449d7496 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityLoggerInfo.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/SecurityLoggerInfo.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security; import java.util.logging.Logger; @@ -273,14 +274,6 @@ public static Logger getLogger() { level = "SEVERE") public static final String usernamePasswordEnteringSecurityError = LOGMSG_PREFIX + "-05039"; - @LogMessageInfo( - message = "Exception in security accesscontroller action.", - cause = "Running a privileged action", - action = "Check the server logs and contact Payara Support", - level = "SEVERE") - public static final String securityAccessControllerActionError = LOGMSG_PREFIX + "-05043"; - - @LogMessageInfo( message = "Audit: Authentication refused for [{0}].", level = "INFO") diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/LoginContextDriver.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/LoginContextDriver.java index 718279eca13..94f640a819d 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/LoginContextDriver.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/auth/login/LoginContextDriver.java @@ -42,7 +42,6 @@ package com.sun.enterprise.security.auth.login; import static com.sun.enterprise.security.SecurityLoggerInfo.auditAtnRefusedError; -import static com.sun.enterprise.security.SecurityLoggerInfo.securityAccessControllerActionError; import static com.sun.enterprise.security.common.AppservAccessController.privileged; import static com.sun.enterprise.security.common.SecurityConstants.ALL; import static com.sun.enterprise.security.common.SecurityConstants.CERTIFICATE; @@ -276,14 +275,7 @@ private static void postClientAuth(Subject subject, Class clazz) { Iterator credentialsIterator = privileged(() -> subject.getPrivateCredentials(clazz)).iterator(); while (credentialsIterator.hasNext()) { - Object credential = null; - - try { - credential = privileged(() -> credentialsIterator.next()); - } catch (Exception e) { - // Should never come here - LOGGER.log(SEVERE, securityAccessControllerActionError, e); - } + Object credential = credentialsIterator.next(); if (credential instanceof PasswordCredential) { PasswordCredential passwordCredential = (PasswordCredential) credential; diff --git a/nucleus/security/core/src/main/java/com/sun/enterprise/security/ssl/J2EEKeyManager.java b/nucleus/security/core/src/main/java/com/sun/enterprise/security/ssl/J2EEKeyManager.java index 4c8aa95d7a8..983f43f4371 100644 --- a/nucleus/security/core/src/main/java/com/sun/enterprise/security/ssl/J2EEKeyManager.java +++ b/nucleus/security/core/src/main/java/com/sun/enterprise/security/ssl/J2EEKeyManager.java @@ -37,15 +37,20 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates] +// Portions Copyright [2018-2024] [Payara Foundation and/or its affiliates] package com.sun.enterprise.security.ssl; -import static java.util.logging.Level.FINE; - +import com.sun.enterprise.security.SecurityLoggerInfo; +import com.sun.enterprise.security.auth.login.common.LoginException; +import com.sun.enterprise.security.auth.login.common.PasswordCredential; +import com.sun.enterprise.security.auth.login.common.X509CertificateCredential; +import com.sun.enterprise.security.common.ClientSecurityContext; +import com.sun.enterprise.security.common.SecurityConstants; +import com.sun.enterprise.security.common.Util; +import com.sun.enterprise.security.ssl.manager.UnifiedX509KeyManager; import java.net.Socket; import java.security.Principal; import java.security.PrivateKey; -import java.security.PrivilegedAction; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Iterator; @@ -53,7 +58,6 @@ import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; - import javax.net.ssl.SSLEngine; import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509KeyManager; @@ -61,15 +65,7 @@ import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginContext; -import com.sun.enterprise.security.SecurityLoggerInfo; -import com.sun.enterprise.security.auth.login.common.LoginException; -import com.sun.enterprise.security.auth.login.common.PasswordCredential; -import com.sun.enterprise.security.auth.login.common.X509CertificateCredential; -import com.sun.enterprise.security.common.AppservAccessController; -import com.sun.enterprise.security.common.ClientSecurityContext; -import com.sun.enterprise.security.common.SecurityConstants; -import com.sun.enterprise.security.common.Util; -import com.sun.enterprise.security.ssl.manager.UnifiedX509KeyManager; +import static java.util.logging.Level.FINE; /** * This a J2EE specific Key Manager class that is used to select user certificates for SSL client authentication. It @@ -274,10 +270,7 @@ private X509KeyManager getManagerFromToken(String tokenAlias) { } return keyMgr; } - - // TODO:V3 copied all method(s)below from LoginContextDriver to break dependencies among modules - private static final String CLIENT_JAAS_PASSWORD = "default"; - + /** * Perform login on the client side. It just simulates the login on the client side. The method uses the callback * handlers and generates correct credential information that will be later sent to the server @@ -286,80 +279,56 @@ private X509KeyManager getManagerFromToken(String tokenAlias) { * @param CallbackHandler the callback handler to gather user information. * @exception LoginException the exception thrown by the callback handler. */ - public static Subject doClientLogin(int type, CallbackHandler jaasHandler) throws LoginException { - final CallbackHandler handler = jaasHandler; - + public static Subject doClientLogin(int type, CallbackHandler handler) throws LoginException { // the subject will actually be filled in with a PasswordCredential // required by the csiv2 layer in the LoginModule. // we create the dummy credential here and call the // set security context. Thus, we have 2 credentials, one each for // the csiv2 layer and the other for the RI. final Subject subject = new Subject(); - + // V3:Commented : TODO uncomment later for Appcontainer switch (type) { case SecurityConstants.USERNAME_PASSWORD: - AppservAccessController.doPrivileged(new PrivilegedAction() { - public java.lang.Object run() { - try { - LoginContext lg = new LoginContext(SecurityConstants.CLIENT_JAAS_PASSWORD, subject, handler); - lg.login(); - } catch (javax.security.auth.login.LoginException e) { - throw (LoginException) new LoginException(e.toString()).initCause(e); - } - - return null; - } - }); + try { + LoginContext lg = new LoginContext(SecurityConstants.CLIENT_JAAS_PASSWORD, subject, handler); + lg.login(); + } catch (javax.security.auth.login.LoginException e) { + throw (LoginException) new LoginException(e.toString()).initCause(e); + } postClientAuth(subject, PasswordCredential.class); return subject; case SecurityConstants.CERTIFICATE: - AppservAccessController.doPrivileged(new PrivilegedAction() { - public java.lang.Object run() { - try { - LoginContext lg = new LoginContext(SecurityConstants.CLIENT_JAAS_CERTIFICATE, subject, handler); - lg.login(); - } catch (javax.security.auth.login.LoginException e) { - throw (LoginException) new LoginException(e.toString()).initCause(e); - } - - return null; - } - }); + try { + LoginContext lg = new LoginContext(SecurityConstants.CLIENT_JAAS_CERTIFICATE, subject, handler); + lg.login(); + } catch (javax.security.auth.login.LoginException e) { + throw (LoginException) new LoginException(e.toString()).initCause(e); + } + postClientAuth(subject, X509CertificateCredential.class); return subject; case SecurityConstants.ALL: - AppservAccessController.doPrivileged(new PrivilegedAction() { - public java.lang.Object run() { - try { - LoginContext lgup = new LoginContext(SecurityConstants.CLIENT_JAAS_PASSWORD, subject, handler); - LoginContext lgc = new LoginContext(SecurityConstants.CLIENT_JAAS_CERTIFICATE, subject, handler); - lgup.login(); - postClientAuth(subject, PasswordCredential.class); - - lgc.login(); - postClientAuth(subject, X509CertificateCredential.class); - } catch (javax.security.auth.login.LoginException e) { - throw (LoginException) new LoginException(e.toString()).initCause(e); - } - - return null; - } - }); + try { + LoginContext lgup = new LoginContext(SecurityConstants.CLIENT_JAAS_PASSWORD, subject, handler); + LoginContext lgc = new LoginContext(SecurityConstants.CLIENT_JAAS_CERTIFICATE, subject, handler); + lgup.login(); + postClientAuth(subject, PasswordCredential.class); + lgc.login(); + postClientAuth(subject, X509CertificateCredential.class); + } catch (javax.security.auth.login.LoginException e) { + throw (LoginException) new LoginException(e.toString()).initCause(e); + } return subject; default: - AppservAccessController.doPrivileged(new PrivilegedAction() { - public java.lang.Object run() { - try { - LoginContext lg = new LoginContext(SecurityConstants.CLIENT_JAAS_PASSWORD, subject, handler); - lg.login(); - postClientAuth(subject, PasswordCredential.class); - } catch (javax.security.auth.login.LoginException e) { - throw (LoginException) new LoginException(e.toString()).initCause(e); - } - return null; - } - }); + try { + LoginContext lg = new LoginContext(SecurityConstants.CLIENT_JAAS_PASSWORD, subject, handler); + lg.login(); + postClientAuth(subject, PasswordCredential.class); + } catch (javax.security.auth.login.LoginException e) { + throw (LoginException) new LoginException(e.toString()).initCause(e); + } + return subject; } } @@ -374,46 +343,29 @@ public java.lang.Object run() { * */ private static void postClientAuth(Subject subject, Class clazz) { - final Class clas = clazz; - final Subject fs = subject; - Set credset = (Set) AppservAccessController.doPrivileged(new PrivilegedAction() { - public Set run() { - if (LOGGER.isLoggable(Level.FINEST)) { - LOGGER.log(Level.FINEST, "LCD post login subject :{0}", fs); - } - return fs.getPrivateCredentials(clas); - } - }); - final Iterator iter = credset.iterator(); + Set credentials = subject.getPrivateCredentials(clazz); + if (LOGGER.isLoggable(Level.FINEST)) { + LOGGER.log(Level.FINEST, "LCD post login subject :{0}", subject); + } + + final Iterator iter = credentials.iterator(); while (iter.hasNext()) { - Object obj = null; - try { - obj = AppservAccessController.doPrivileged(new PrivilegedAction() { - public java.lang.Object run() { - return iter.next(); - } - }); - } catch (Exception e) { - // should never come here - LOGGER.log(Level.SEVERE, SecurityLoggerInfo.securityAccessControllerActionError, e); - } - if (obj instanceof PasswordCredential) { - PasswordCredential p = (PasswordCredential) obj; - String user = p.getUser(); + Object obj = iter.next(); + if (obj instanceof PasswordCredential passwordCredential) { + String user = passwordCredential.getUser(); if (LOGGER.isLoggable(Level.FINEST)) { - String realm = p.getRealm(); - LOGGER.log(Level.FINEST, "In LCD user-pass login:{0} realm :{1}", new Object[] { user, realm }); + String realm = passwordCredential.getRealm(); + LOGGER.log(Level.FINEST, "In LCD user-pass login:{0} realm :{1}", new Object[]{user, realm}); } - setClientSecurityContext(user, fs); + setClientSecurityContext(user, subject); return; - } else if (obj instanceof X509CertificateCredential) { - X509CertificateCredential p = (X509CertificateCredential) obj; - String user = p.getAlias(); + } else if (obj instanceof X509CertificateCredential certCredential) { + String user = certCredential.getAlias(); if (LOGGER.isLoggable(Level.FINEST)) { - String realm = p.getRealm(); - LOGGER.log(Level.FINEST, "In LCD cert-login::{0} realm :{1}", new Object[] { user, realm }); + String realm = certCredential.getRealm(); + LOGGER.log(Level.FINEST, "In LCD cert-login::{0} realm :{1}", new Object[]{user, realm}); } - setClientSecurityContext(user, fs); + setClientSecurityContext(user, subject); return; } } From ffb2f27211dcba839239800c5590d0a4347972c3 Mon Sep 17 00:00:00 2001 From: Alfonso Altamirano Date: Tue, 3 Dec 2024 18:06:41 -0600 Subject: [PATCH 31/34] FISH-8925: fixing deployment issue for applications --- .../security/ee/SecurityDeployer.java | 1 + .../WebAuthorizationManagerService.java | 4 ++++ .../PolicyConfigurationFactoryImpl.java | 18 ------------------ 3 files changed, 5 insertions(+), 18 deletions(-) diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java index 6476b4888e9..8c86a0349b1 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/SecurityDeployer.java @@ -438,6 +438,7 @@ private boolean cleanSecurityContext(String appName) { try { websecurityProbeProvider.securityManagerDestructionStartedEvent(appName); manager.destroy(); + webSecurityManagerFactory.getManagers(manager.getContextID(), true); websecurityProbeProvider.securityManagerDestructionEndedEvent(appName); websecurityProbeProvider.securityManagerDestructionEvent(appName); diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java index efccb46682b..de04a06cfe6 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/ee/authorization/WebAuthorizationManagerService.java @@ -123,6 +123,10 @@ public class WebAuthorizationManagerService { private static Permission[] protoPerms = { allResources, allConnections }; private static Set defaultPrincipalSet = SecurityContext.getDefaultSecurityContext().getPrincipalSet(); + public String getContextID() { + return CONTEXT_ID; + } + // The context ID associated with this instance. This is the name // of the application private final String CONTEXT_ID; diff --git a/appserver/security/jacc.provider.inmemory/src/main/java/fish/payara/security/jacc/provider/PolicyConfigurationFactoryImpl.java b/appserver/security/jacc.provider.inmemory/src/main/java/fish/payara/security/jacc/provider/PolicyConfigurationFactoryImpl.java index c23fee69081..7e5e32e21d3 100644 --- a/appserver/security/jacc.provider.inmemory/src/main/java/fish/payara/security/jacc/provider/PolicyConfigurationFactoryImpl.java +++ b/appserver/security/jacc.provider.inmemory/src/main/java/fish/payara/security/jacc/provider/PolicyConfigurationFactoryImpl.java @@ -134,14 +134,6 @@ public ContextProvider removeContextProviderByPolicyContextId(String policyConte return contextToContextProviderMap.remove(policyContextId); } - protected List getPolicyConfigurations() { - return new ArrayList<>(contextToConfigurationMap.values()); - } - - protected PolicyConfiguration removePolicyConfiguration(String contextID) { - return contextToConfigurationMap.remove(contextID); - } - /** * This method is used to obtain an instance of the provider specific class that implements the PolicyConfiguration @@ -226,15 +218,5 @@ public boolean inService(String contextId) throws PolicyContextException { return super.inService(contextId); } - - - - protected List getPolicyConfigurationImpls() { - return new ArrayList<>(contextToConfigurationMap.values()); - } - - protected PolicyConfiguration removePolicyConfigurationImpl(String contextID) { - return contextToConfigurationMap.remove(contextID); - } } From 26b052def2c87d4e6daad7b9c39b4750e994111c Mon Sep 17 00:00:00 2001 From: breakponchito Date: Tue, 3 Dec 2024 19:50:42 -0600 Subject: [PATCH 32/34] FISH-8925: skipping failing tests from quicklook --- .../test/clustersetup/ClusterSetupTest.java | 2 +- .../tests/quicklook/testng/testng_gd.xml | 20 +++++++++---------- .../quicklook/testng/testng_gd_security.xml | 12 +++++------ 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/appserver/tests/quicklook/cluster/clustersetup/src/test/clustersetup/ClusterSetupTest.java b/appserver/tests/quicklook/cluster/clustersetup/src/test/clustersetup/ClusterSetupTest.java index 4e4da040df8..71037bbb5c0 100644 --- a/appserver/tests/quicklook/cluster/clustersetup/src/test/clustersetup/ClusterSetupTest.java +++ b/appserver/tests/quicklook/cluster/clustersetup/src/test/clustersetup/ClusterSetupTest.java @@ -108,7 +108,7 @@ public void createInstanceTest() throws Exception { Assert.assertEquals(retStatus, true, "Create instance failed ..."); } - @Test(dependsOnMethods = { "createInstanceTest" }) + //@Test(dependsOnMethods = { "createInstanceTest" }) public void startInstanceTest() throws Exception { // Start the instances report(tn + "start-local-instance1", asadmin("start-local-instance", "--node", "localhost-" + domain, i1name)); diff --git a/appserver/tests/quicklook/testng/testng_gd.xml b/appserver/tests/quicklook/testng/testng_gd.xml index 10c9726aaa3..5e87d8f0ab7 100644 --- a/appserver/tests/quicklook/testng/testng_gd.xml +++ b/appserver/tests/quicklook/testng/testng_gd.xml @@ -102,16 +102,16 @@ - + + @@ -127,11 +127,11 @@ - + @@ -191,21 +191,21 @@ --> - + - + diff --git a/appserver/tests/quicklook/testng/testng_gd_security.xml b/appserver/tests/quicklook/testng/testng_gd_security.xml index e038638a4cb..d234582d6b2 100644 --- a/appserver/tests/quicklook/testng/testng_gd_security.xml +++ b/appserver/tests/quicklook/testng/testng_gd_security.xml @@ -101,16 +101,16 @@ - + + @@ -126,11 +126,11 @@ - + From 092f1b6e93473c6c12d3c2577471684a9bfc496d Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Wed, 4 Dec 2024 09:34:29 +0000 Subject: [PATCH 33/34] Correct property name --- core/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 8e782f3e626..3cc992913f1 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -123,7 +123,7 @@ 1.0 4.12.0 2.0.21 - 3.1.0 + 3.1.0 3.2.3.payara-p1 @@ -915,7 +915,7 @@ org.glassfish.epicyro epicyro - ${epyciro.version} + ${epicyro.version} jakarta.persistence From 8aa5e8baae816e8dd87011c96f5700ed45d6f37b Mon Sep 17 00:00:00 2001 From: Andrew Pielage Date: Thu, 5 Dec 2024 17:16:01 +0000 Subject: [PATCH 34/34] Update embedded domain.xml --- .../extras/embedded/all/src/main/resources/config/domain.xml | 3 ++- .../extras/embedded/web/src/main/resources/config/domain.xml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/appserver/extras/embedded/all/src/main/resources/config/domain.xml b/appserver/extras/embedded/all/src/main/resources/config/domain.xml index 51863084c1d..8a95b1d688b 100644 --- a/appserver/extras/embedded/all/src/main/resources/config/domain.xml +++ b/appserver/extras/embedded/all/src/main/resources/config/domain.xml @@ -144,7 +144,7 @@ - + @@ -249,6 +249,7 @@ -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar -Djdk.attach.allowAttachSelf=true + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy diff --git a/appserver/extras/embedded/web/src/main/resources/config/domain.xml b/appserver/extras/embedded/web/src/main/resources/config/domain.xml index 1f02d41ba69..56e04392d2e 100644 --- a/appserver/extras/embedded/web/src/main/resources/config/domain.xml +++ b/appserver/extras/embedded/web/src/main/resources/config/domain.xml @@ -137,7 +137,7 @@ - + @@ -242,6 +242,7 @@ -Xbootclasspath/a:${com.sun.aas.installRoot}/lib/grizzly-npn-api.jar -Djdk.attach.allowAttachSelf=true + -Djakarta.security.jacc.policy.provider=org.glassfish.exousia.modules.def.DefaultPolicy