From 2522a08ebd2c08a21aa69142f585d85d8aa10b42 Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Mon, 27 Sep 2021 14:57:51 +0100 Subject: [PATCH 01/11] [WFLY-15730] / [WFLY-15356] Remove the use of security-plugins from webservices. --- .../org/jboss/as/webservices/main/module.xml | 1 - webservices/server-integration/pom.xml | 6 - .../as/webservices/logging/WSLogger.java | 4 + .../security/SecurityDomainContextImpl.java | 126 ------------------ .../webservices/service/EndpointService.java | 17 +-- 5 files changed, 8 insertions(+), 146 deletions(-) delete mode 100644 webservices/server-integration/src/main/java/org/jboss/as/webservices/security/SecurityDomainContextImpl.java diff --git a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/webservices/main/module.xml b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/webservices/main/module.xml index 080d3fb4e257..8aa88061d3e8 100644 --- a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/webservices/main/module.xml +++ b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/webservices/main/module.xml @@ -58,7 +58,6 @@ - diff --git a/webservices/server-integration/pom.xml b/webservices/server-integration/pom.xml index 24de71d7b97a..ff5ded11fc1a 100644 --- a/webservices/server-integration/pom.xml +++ b/webservices/server-integration/pom.xml @@ -98,12 +98,6 @@ wildfly-ejb3 - - ${project.groupId} - wildfly-security-plugins - provided - - ${project.groupId} wildfly-undertow diff --git a/webservices/server-integration/src/main/java/org/jboss/as/webservices/logging/WSLogger.java b/webservices/server-integration/src/main/java/org/jboss/as/webservices/logging/WSLogger.java index a0ae33f6a45c..15019d237ec3 100644 --- a/webservices/server-integration/src/main/java/org/jboss/as/webservices/logging/WSLogger.java +++ b/webservices/server-integration/src/main/java/org/jboss/as/webservices/logging/WSLogger.java @@ -317,4 +317,8 @@ public interface WSLogger extends BasicLogger { @LogMessage(level = WARN) @Message(id = 68, value = "A potentially problematic %s library (%s) detected in ws endpoint deployment; Check if this library can be replaced with container module") void warningLibraryInDeployment(String libraryName, String jar); + + @Message(id = 74, value = "The deployment is configured to use legacy security which is no longer supported." ) + IllegalStateException legacySecurityUnsupported(); + } diff --git a/webservices/server-integration/src/main/java/org/jboss/as/webservices/security/SecurityDomainContextImpl.java b/webservices/server-integration/src/main/java/org/jboss/as/webservices/security/SecurityDomainContextImpl.java deleted file mode 100644 index 0c818ade4eb2..000000000000 --- a/webservices/server-integration/src/main/java/org/jboss/as/webservices/security/SecurityDomainContextImpl.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2011, Red Hat Middleware LLC, and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.as.webservices.security; - -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.util.Set; -import java.util.concurrent.Callable; - -import javax.security.auth.Subject; - -import org.jboss.as.security.plugins.SecurityDomainContext; -import org.jboss.security.SecurityContext; -import org.jboss.security.SecurityContextAssociation; -import org.jboss.security.SecurityContextFactory; - -/** - * Adaptor of org.jboss.as.security.plugins.SecurityDomainContext to org.jboss.wsf.spi.security.SecurityDomainContext - * - * @author alessio.soldano@jboss.com - * @since 13-May-2011 - */ -public final class SecurityDomainContextImpl implements org.jboss.wsf.spi.security.SecurityDomainContext { - - private final SecurityDomainContext context; - - public SecurityDomainContextImpl(SecurityDomainContext context) { - this.context = context; - } - - @Override - public boolean isValid(Principal principal, Object credential, Subject activeSubject) { - return context.getAuthenticationManager().isValid(principal, credential, activeSubject); - } - - @Override - public boolean doesUserHaveRole(Principal principal, Set roles) { - return context.getAuthorizationManager().doesUserHaveRole(principal, roles); - } - - @Override - public String getSecurityDomain() { - return context.getAuthenticationManager().getSecurityDomain(); - } - - @Override - public Set getUserRoles(Principal principal) { - return context.getAuthorizationManager().getUserRoles(principal); - } - - @Override - public void pushSubjectContext(final Subject subject, final Principal principal, final Object credential) { - AccessController.doPrivileged(new PrivilegedAction() { - - public Void run() { - SecurityContext securityContext = SecurityContextAssociation.getSecurityContext(); - if (securityContext == null) { - securityContext = createSecurityContext(getSecurityDomain()); - setSecurityContextOnAssociation(securityContext); - } - securityContext.getUtil().createSubjectInfo(principal, credential, subject); - return null; - } - }); - } - - /** - * Create a JBoss Security Context with the given security domain name - * - * @param domain the security domain name (such as "other" ) - * @return an instanceof {@code SecurityContext} - */ - private static SecurityContext createSecurityContext(final String domain) { - return AccessController.doPrivileged(new PrivilegedAction() { - - @Override - public SecurityContext run() { - try { - return SecurityContextFactory.createSecurityContext(domain); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - - /** - * Set the {@code SecurityContext} on the {@code SecurityContextAssociation} - * - * @param sc the security context - */ - private static void setSecurityContextOnAssociation(final SecurityContext sc) { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - SecurityContextAssociation.setSecurityContext(sc); - return null; - } - }); - } - - //subject will be pushed in thread local context, so directly run this action - public void runAs(Callable action) throws Exception { - action.call(); - } -} \ No newline at end of file diff --git a/webservices/server-integration/src/main/java/org/jboss/as/webservices/service/EndpointService.java b/webservices/server-integration/src/main/java/org/jboss/as/webservices/service/EndpointService.java index 48dbdac68063..32bacd2aa2a9 100644 --- a/webservices/server-integration/src/main/java/org/jboss/as/webservices/service/EndpointService.java +++ b/webservices/server-integration/src/main/java/org/jboss/as/webservices/service/EndpointService.java @@ -21,6 +21,8 @@ */ package org.jboss.as.webservices.service; +import static org.jboss.as.webservices.logging.WSLogger.ROOT_LOGGER; + import java.security.AccessController; import java.util.ArrayList; import java.util.List; @@ -36,7 +38,6 @@ import org.jboss.as.ejb3.security.service.EJBViewMethodSecurityAttributesService; import org.jboss.as.ejb3.subsystem.ApplicationSecurityDomainService; import org.jboss.as.ejb3.subsystem.ApplicationSecurityDomainService.ApplicationSecurityDomain; -import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentUnit; @@ -44,7 +45,6 @@ import org.jboss.as.webservices.metadata.model.EJBEndpoint; import org.jboss.as.webservices.security.EJBMethodSecurityAttributesAdaptor; import org.jboss.as.webservices.security.ElytronSecurityDomainContextImpl; -import org.jboss.as.webservices.security.SecurityDomainContextImpl; import org.jboss.as.webservices.util.ASHelper; import org.jboss.as.webservices.util.ServiceContainerEndpointRegistry; import org.jboss.as.webservices.util.WSAttachmentKeys; @@ -101,14 +101,12 @@ public final class EndpointService implements Service { private final ServiceName name; private final ServiceName aliasName; private final Consumer endpointConsumer; - private final Supplier securityDomainContext; private final Supplier serverConfigService; private final Supplier ejbApplicationSecurityDomain; private final Supplier ejbMethodSecurityAttributeService; private final Supplier elytronSecurityDomain; private EndpointService(final Endpoint endpoint, final ServiceName name, final ServiceName aliasName, final Consumer endpointConsumer, - final Supplier securityDomainContext, Supplier serverConfigService, Supplier ejbApplicationSecurityDomain, Supplier ejbMethodSecurityAttributeService, @@ -118,7 +116,6 @@ private EndpointService(final Endpoint endpoint, final ServiceName name, final S this.name = name; this.aliasName = aliasName; this.endpointConsumer = endpointConsumer; - this.securityDomainContext = securityDomainContext; this.serverConfigService = serverConfigService; this.ejbApplicationSecurityDomain = ejbApplicationSecurityDomain; this.ejbMethodSecurityAttributeService = ejbMethodSecurityAttributeService; @@ -143,9 +140,6 @@ public void start(final StartContext context) { endpoint.setSecurityDomainContext(new ElytronSecurityDomainContextImpl(this.elytronSecurityDomain.get())); } } - if (this.securityDomainContext != null && this.securityDomainContext.get() != null) { - endpoint.setSecurityDomainContext(new SecurityDomainContextImpl(securityDomainContext.get())); - } if (EndpointType.JAXWS_EJB3.equals(endpoint.getType())) { final EJBViewMethodSecurityAttributesService ejbMethodSecurityAttributeService = this.ejbMethodSecurityAttributeService.get(); endpoint.addAttachment(EJBMethodSecurityAttributeProvider.class, new EJBMethodSecurityAttributesAdaptor(ejbMethodSecurityAttributeService)); @@ -243,7 +237,6 @@ public static void install(final ServiceTarget serviceTarget, final Endpoint end final String propEndpoint = endpoint.getName().getKeyProperty(Endpoint.SEPID_PROPERTY_ENDPOINT); final StringBuilder context = new StringBuilder(Endpoint.SEPID_PROPERTY_CONTEXT).append("=").append(propContext); final ServiceBuilder builder = serviceTarget.addService(serviceName); - Supplier securityDomainContext = null; Supplier ejbApplicationSecurityDomain = null; Supplier ejbMethodSecurityAttributeService = null; Supplier elytronSecurityDomain = null; @@ -252,7 +245,6 @@ public static void install(final ServiceTarget serviceTarget, final Endpoint end //builder.addAliases(alias); final String domainName = getDeploymentSecurityDomainName(endpoint, unit); endpoint.setProperty(SECURITY_DOMAIN_NAME, domainName); - CapabilityServiceSupport capabilitySupport = unit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); if (isElytronSecurityDomain(unit, endpoint, domainName)) { if (EndpointType.JAXWS_EJB3.equals(endpoint.getType())) { ServiceName ejbSecurityDomainServiceName = EJB_APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY @@ -268,14 +260,13 @@ public static void install(final ServiceTarget serviceTarget, final Endpoint end endpoint.setProperty(ELYTRON_SECURITY_DOMAIN, true); } else if (isLegacySecurityDomain(unit, endpoint, domainName)) { - // This is still picketbox jaas securityDomainContext - securityDomainContext = builder.requires(SECURITY_DOMAIN_SERVICE.append(domainName)); + throw ROOT_LOGGER.legacySecurityUnsupported(); } final Supplier serverConfigService = builder.requires(WSServices.CONFIG_SERVICE); if (EndpointType.JAXWS_EJB3.equals(endpoint.getType())) { ejbMethodSecurityAttributeService = builder.requires(getEJBViewMethodSecurityAttributesServiceName(unit, endpoint)); } - builder.setInstance(new EndpointService(endpoint, serviceName, alias, endpointConsumer, securityDomainContext, + builder.setInstance(new EndpointService(endpoint, serviceName, alias, endpointConsumer, serverConfigService, ejbApplicationSecurityDomain, ejbMethodSecurityAttributeService, elytronSecurityDomain)); builder.install(); //add a dependency on the endpoint service to web deployments, so that the From e772c9efbe6abe76d5f17412c57e605513894da0 Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Mon, 27 Sep 2021 17:13:37 +0100 Subject: [PATCH 02/11] [WFLY-15731] / [WFLY-15356] Remove use of security-plugins from the connector subsystem. --- connector/pom.xml | 5 ---- .../DsXmlDeploymentInstallProcessor.java | 11 +------ .../ParsedRaDeploymentProcessor.java | 9 +----- .../as/connector/logging/ConnectorLogger.java | 3 ++ ...rectConnectionFactoryActivatorService.java | 29 +++++++------------ ...tractResourceAdapterDeploymentService.java | 24 ++++----------- .../ResourceAdapterXmlDeploymentService.java | 21 -------------- .../datasources/AbstractDataSourceAdd.java | 14 +++------ .../AbstractDataSourceService.java | 6 ---- .../ConnectionDefinitionAdd.java | 10 +------ .../ConnectionDefinitionService.java | 23 +-------------- .../ModifiableResourceAdapter.java | 22 -------------- .../org/jboss/as/connector/main/module.xml | 1 - 13 files changed, 27 insertions(+), 151 deletions(-) diff --git a/connector/pom.xml b/connector/pom.xml index 767996c2cb15..b254f73d1bab 100644 --- a/connector/pom.xml +++ b/connector/pom.xml @@ -57,11 +57,6 @@ ${project.groupId} wildfly-naming - - ${project.groupId} - wildfly-security-plugins - provided - ${project.groupId} wildfly-transactions diff --git a/connector/src/main/java/org/jboss/as/connector/deployers/ds/processors/DsXmlDeploymentInstallProcessor.java b/connector/src/main/java/org/jboss/as/connector/deployers/ds/processors/DsXmlDeploymentInstallProcessor.java index 6ff058e3c31f..69c5e64fa58e 100644 --- a/connector/src/main/java/org/jboss/as/connector/deployers/ds/processors/DsXmlDeploymentInstallProcessor.java +++ b/connector/src/main/java/org/jboss/as/connector/deployers/ds/processors/DsXmlDeploymentInstallProcessor.java @@ -55,7 +55,6 @@ import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.naming.ServiceBasedNamingStore; import org.jboss.as.naming.deployment.ContextNames; @@ -88,7 +87,6 @@ import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; -import org.jboss.security.SubjectFactory; /** * Picks up -ds.xml deployments @@ -324,14 +322,7 @@ private void startDataSource(final AbstractDataSourceService dataSourceService, dataSourceServiceBuilder.requires(support.getCapabilityServiceName(NamingService.CAPABILITY_NAME)); if (requireLegacySecurity) { - if (support.hasCapability("org.wildfly.legacy-security")) { - dataSourceServiceBuilder.addDependency(support.getCapabilityServiceName("org.wildfly.legacy-security.server-security-manager"), ServerSecurityManager.class, - dataSourceService.getServerSecurityManager()); - dataSourceServiceBuilder.addDependency(support.getCapabilityServiceName("org.wildfly.legacy-security.subject-factory"), SubjectFactory.class, - dataSourceService.getSubjectFactoryInjector()); - } else { - throw ConnectorLogger.DS_DEPLOYER_LOGGER.legacySecurityNotAvailableForDsXml(managementName); - } + throw ConnectorLogger.DS_DEPLOYER_LOGGER.legacySecurityNotAvailableForDsXml(managementName); } //Register an empty override model regardless of we're enabled or not - the statistics listener will add the relevant childresources diff --git a/connector/src/main/java/org/jboss/as/connector/deployers/ra/processors/ParsedRaDeploymentProcessor.java b/connector/src/main/java/org/jboss/as/connector/deployers/ra/processors/ParsedRaDeploymentProcessor.java index 94e8373c81d7..f7ab1d7791f3 100644 --- a/connector/src/main/java/org/jboss/as/connector/deployers/ra/processors/ParsedRaDeploymentProcessor.java +++ b/connector/src/main/java/org/jboss/as/connector/deployers/ra/processors/ParsedRaDeploymentProcessor.java @@ -45,7 +45,6 @@ import org.jboss.as.controller.descriptions.OverrideDescriptionProvider; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.naming.service.NamingService; import org.jboss.as.server.Services; import org.jboss.as.server.deployment.Attachments; @@ -73,7 +72,6 @@ import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; -import org.jboss.security.SubjectFactory; /** * DeploymentUnitProcessor responsible for using IronJacamar metadata and create @@ -222,12 +220,7 @@ public static ServiceBuilder process(final ConnectorX builder.addDependency(ConnectorServices.CCM_SERVICE, CachedConnectionManager.class, raDeploymentService.getCcmInjector()); } if (activation != null && ActivationSecurityUtil.isLegacySecurityRequired(activation)) { - if (support.hasCapability("org.wildfly.legacy-security")) { - builder.addDependency(support.getCapabilityServiceName("org.wildfly.legacy-security.subject-factory"), SubjectFactory.class, raDeploymentService.getSubjectFactoryInjector()) - .addDependency(support.getCapabilityServiceName("org.wildfly.legacy-security.server-security-manager"), ServerSecurityManager.class, raDeploymentService.getServerSecurityManager()); - } else { - throw ConnectorLogger.DS_DEPLOYER_LOGGER.legacySecurityNotAvailableForRa(connectorXmlDescriptor.getDeploymentName()); - } + throw ConnectorLogger.DS_DEPLOYER_LOGGER.legacySecurityNotAvailableForRa(connectorXmlDescriptor.getDeploymentName()); } return builder; diff --git a/connector/src/main/java/org/jboss/as/connector/logging/ConnectorLogger.java b/connector/src/main/java/org/jboss/as/connector/logging/ConnectorLogger.java index 676a14f704ac..dd20eba8e48c 100644 --- a/connector/src/main/java/org/jboss/as/connector/logging/ConnectorLogger.java +++ b/connector/src/main/java/org/jboss/as/connector/logging/ConnectorLogger.java @@ -967,4 +967,7 @@ public interface ConnectorLogger extends BasicLogger { @Message(id = 127, value = "Connection factory %s is configured to require the legacy security subsystem, which is not present") IllegalStateException legacySecurityNotAvailableForConnectionFactory(String jndiName); + + @Message(id = 128, value = "Legacy security is not available") + IllegalStateException legacySecurityNotAvailable(); } diff --git a/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/DirectConnectionFactoryActivatorService.java b/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/DirectConnectionFactoryActivatorService.java index 7bd3e476cd05..1dfe20c72937 100644 --- a/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/DirectConnectionFactoryActivatorService.java +++ b/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/DirectConnectionFactoryActivatorService.java @@ -22,6 +22,15 @@ package org.jboss.as.connector.services.resourceadapters; +import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER; +import static org.jboss.as.connector.logging.ConnectorLogger.SUBSYSTEM_RA_LOGGER; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.resource.spi.TransactionSupport; + import org.jboss.as.connector.logging.ConnectorLogger; import org.jboss.as.connector.metadata.api.common.Security; import org.jboss.as.connector.metadata.api.resourceadapter.ActivationSecurityUtil; @@ -30,7 +39,6 @@ import org.jboss.as.connector.services.resourceadapters.deployment.registry.ResourceAdapterDeploymentRegistry; import org.jboss.as.connector.subsystems.jca.JcaSubsystemConfiguration; import org.jboss.as.connector.util.ConnectorServices; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.as.naming.service.NamingService; import org.jboss.jca.common.api.metadata.Defaults; @@ -52,15 +60,6 @@ import org.jboss.msc.inject.Injector; import org.jboss.msc.service.ServiceName; import org.jboss.msc.value.InjectedValue; -import org.jboss.security.SubjectFactory; - -import javax.resource.spi.TransactionSupport; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import static org.jboss.as.connector.logging.ConnectorLogger.ROOT_LOGGER; -import static org.jboss.as.connector.logging.ConnectorLogger.SUBSYSTEM_RA_LOGGER; public class DirectConnectionFactoryActivatorService implements org.jboss.msc.service.Service { @@ -258,15 +257,7 @@ public void start(org.jboss.msc.service.StartContext context) throws org.jboss.m connectionFactoryServiceBuilder.requires(ConnectorServices.BOOTSTRAP_CONTEXT_SERVICE.append("default")); if (ActivationSecurityUtil.isLegacySecurityRequired(security)) { - if (legacySecurityAvailable) { - connectionFactoryServiceBuilder - .addDependency(SUBJECT_FACTORY_SERVICE, SubjectFactory.class, - activator.getSubjectFactoryInjector()) - .addDependency(SECURITY_MANAGER_SERVICE, - ServerSecurityManager.class, activator.getServerSecurityManager()); - } else { - throw ConnectorLogger.DEPLOYMENT_CONNECTOR_LOGGER.legacySecurityNotAvailableForConnectionFactory(jndiName); - } + throw ConnectorLogger.DEPLOYMENT_CONNECTOR_LOGGER.legacySecurityNotAvailableForConnectionFactory(jndiName); } connectionFactoryServiceBuilder.setInitialMode(org.jboss.msc.service.ServiceController.Mode.ACTIVE).install(); diff --git a/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/AbstractResourceAdapterDeploymentService.java b/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/AbstractResourceAdapterDeploymentService.java index 5feb6fb672a6..2f19e6d67fd0 100644 --- a/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/AbstractResourceAdapterDeploymentService.java +++ b/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/AbstractResourceAdapterDeploymentService.java @@ -26,10 +26,6 @@ import static java.security.AccessController.doPrivileged; import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_LOGGER; -import javax.naming.InitialContext; -import javax.naming.Reference; -import javax.resource.spi.ResourceAdapter; -import javax.transaction.TransactionManager; import java.io.File; import java.io.PrintWriter; import java.net.URI; @@ -43,6 +39,11 @@ import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; +import javax.naming.InitialContext; +import javax.naming.Reference; +import javax.resource.spi.ResourceAdapter; +import javax.transaction.TransactionManager; + import org.jboss.as.connector.logging.ConnectorLogger; import org.jboss.as.connector.metadata.api.resourceadapter.WorkManagerSecurity; import org.jboss.as.connector.metadata.deployment.ResourceAdapterDeployment; @@ -59,7 +60,6 @@ import org.jboss.as.connector.util.ConnectorServices; import org.jboss.as.connector.util.Injection; import org.jboss.as.connector.util.JCAValidatorFactory; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.naming.ContextListAndJndiViewManagedReferenceFactory; import org.jboss.as.naming.ContextListManagedReferenceFactory; import org.jboss.as.naming.ManagedReference; @@ -78,7 +78,6 @@ import org.jboss.jca.core.api.management.ManagementRepository; import org.jboss.jca.core.bootstrapcontext.BootstrapContextCoordinator; import org.jboss.jca.core.connectionmanager.ConnectionManager; -import org.jboss.jca.core.security.picketbox.PicketBoxSubjectFactory; import org.jboss.jca.core.spi.mdr.AlreadyExistsException; import org.jboss.jca.core.spi.rar.ResourceAdapterRepository; import org.jboss.jca.core.spi.security.Callback; @@ -101,7 +100,6 @@ import org.jboss.msc.service.StopContext; import org.jboss.msc.value.ImmediateValue; import org.jboss.msc.value.InjectedValue; -import org.jboss.security.SubjectFactory; import org.jboss.threads.JBossThreadFactory; import org.wildfly.security.manager.WildFlySecurityManager; import org.wildfly.security.manager.action.ClearContextClassLoaderAction; @@ -127,10 +125,8 @@ public abstract class AbstractResourceAdapterDeploymentService { protected final InjectedValue config = new InjectedValue(); protected final InjectedValue txInt = new InjectedValue(); - protected final InjectedValue subjectFactory = new InjectedValue(); protected final InjectedValue ccmValue = new InjectedValue(); protected final InjectedValue executorServiceInjector = new InjectedValue(); - private final InjectedValue secManager = new InjectedValue(); protected String raRepositoryRegistrationId; protected String connectorServicesRegistrationName; @@ -278,14 +274,6 @@ public Injector getConfigInjector() { return config; } - public Injector getSubjectFactoryInjector() { - return subjectFactory; - } - - public Injector getServerSecurityManager() { - return secManager; - } - public Injector getCcmInjector() { return ccmValue; } @@ -682,7 +670,7 @@ protected org.jboss.jca.core.spi.security.SubjectFactory getSubjectFactory( } else if (securityDomain == null || securityDomain.trim().equals("")) { return null; } else { - return new PicketBoxSubjectFactory(subjectFactory.getValue()); + throw ConnectorLogger.ROOT_LOGGER.legacySecurityNotAvailable(); } } diff --git a/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/ResourceAdapterXmlDeploymentService.java b/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/ResourceAdapterXmlDeploymentService.java index 1c41f667a229..3a18784d9008 100644 --- a/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/ResourceAdapterXmlDeploymentService.java +++ b/connector/src/main/java/org/jboss/as/connector/services/resourceadapters/deployment/ResourceAdapterXmlDeploymentService.java @@ -24,7 +24,6 @@ import static org.jboss.as.connector.logging.ConnectorLogger.DEPLOYMENT_CONNECTOR_LOGGER; -import javax.security.auth.Subject; import java.io.File; import java.net.URI; import java.net.URISyntaxException; @@ -39,13 +38,11 @@ import org.jboss.as.connector.services.resourceadapters.ResourceAdapterService; import org.jboss.as.connector.subsystems.resourceadapters.ModifiableResourceAdapter; import org.jboss.as.connector.util.ConnectorServices; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.naming.WritableServiceBasedNamingStore; import org.jboss.jca.common.api.metadata.common.SecurityMetadata; import org.jboss.jca.common.api.metadata.resourceadapter.Activation; import org.jboss.jca.common.api.metadata.spec.Connector; import org.jboss.jca.common.metadata.merge.Merger; -import org.jboss.jca.core.security.picketbox.PicketBoxSubjectFactory; import org.jboss.jca.deployers.DeployersLogger; import org.jboss.jca.deployers.common.CommonDeployment; import org.jboss.jca.deployers.common.DeployException; @@ -226,24 +223,6 @@ protected org.jboss.jca.core.spi.security.SubjectFactory getSubjectFactory( } } else if (securityDomain == null || securityDomain.trim().equals("")) { return null; - } else if (((ModifiableResourceAdapter) raxml).getSubjectFactory() != null) { - return new PicketBoxSubjectFactory(((ModifiableResourceAdapter) raxml).getSubjectFactory()){ - - @Override - public Subject createSubject(final String sd) { - ServerSecurityManager sm = ((ModifiableResourceAdapter) raxml).getSecManager(); - if (sm != null) { - sm.push(sd); - } - try { - return super.createSubject(sd); - } finally { - if (sm != null) { - sm.pop(); - } - } - } - }; } return null; } diff --git a/connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceAdd.java b/connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceAdd.java index bc51b36e4824..3eb014d25a54 100644 --- a/connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceAdd.java +++ b/connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceAdd.java @@ -43,13 +43,14 @@ import static org.jboss.as.controller.security.CredentialReference.handleCredentialReferenceUpdate; import static org.jboss.as.controller.security.CredentialReference.rollbackCredentialStoreUpdate; -import javax.sql.DataSource; import java.sql.Driver; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; +import javax.sql.DataSource; + import org.jboss.as.connector._private.Capabilities; import org.jboss.as.connector.logging.ConnectorLogger; import org.jboss.as.connector.services.datasources.statistics.DataSourceStatisticsService; @@ -65,7 +66,6 @@ import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.controller.security.CredentialReference; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.naming.ServiceBasedNamingStore; import org.jboss.as.naming.deployment.ContextNames; @@ -90,7 +90,6 @@ import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.ValueInjectionService; -import org.jboss.security.SubjectFactory; import org.wildfly.common.function.ExceptionSupplier; import org.wildfly.security.auth.client.AuthenticationContext; import org.wildfly.security.credential.source.CredentialSource; @@ -256,13 +255,8 @@ void firstRuntimeStep(OperationContext context, ModelNode operation, ModelNode m } if (requireLegacySecurity) { - if (context.hasOptionalCapability("org.wildfly.legacy-security", null, null)) { - dataSourceServiceBuilder.addDependency(SUBJECT_FACTORY_SERVICE, SubjectFactory.class, dataSourceService.getSubjectFactoryInjector()) - .addDependency(SECURITY_MANAGER_SERVICE, ServerSecurityManager.class, dataSourceService.getServerSecurityManager()); - } else { - context.setRollbackOnly(); - throw SUBSYSTEM_RA_LOGGER.legacySecurityNotAvailable(dsName); - } + context.setRollbackOnly(); + throw SUBSYSTEM_RA_LOGGER.legacySecurityNotAvailable(dsName); } ModelNode credentialReference = Constants.CREDENTIAL_REFERENCE.resolveModelAttribute(context, model); diff --git a/connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceService.java b/connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceService.java index 161911a75774..f4d4f6a8196e 100644 --- a/connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceService.java +++ b/connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceService.java @@ -49,7 +49,6 @@ import org.jboss.as.connector.services.driver.registry.DriverRegistry; import org.jboss.as.connector.util.Injection; import org.jboss.as.controller.OperationFailedException; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.jca.adapters.jdbc.BaseWrapperManagedConnectionFactory; import org.jboss.jca.adapters.jdbc.JDBCResourceAdapter; @@ -129,7 +128,6 @@ public static ServiceName getServiceName(ContextNames.BindInfo bindInfo) { private final InjectedValue ccmValue = new InjectedValue(); private final InjectedValue executor = new InjectedValue(); private final InjectedValue mdr = new InjectedValue(); - private final InjectedValue secManager = new InjectedValue(); private final InjectedValue raRepository = new InjectedValue(); private final InjectedValue authenticationContext = new InjectedValue<>(); private final InjectedValue recoveryAuthenticationContext = new InjectedValue<>(); @@ -287,10 +285,6 @@ public Injector getRaRepositoryInjector() { return raRepository; } - public Injector getServerSecurityManager() { - return secManager; - } - Injector getAuthenticationContext() { return authenticationContext; } diff --git a/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ConnectionDefinitionAdd.java b/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ConnectionDefinitionAdd.java index 73bdcc173704..d153e4562b93 100644 --- a/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ConnectionDefinitionAdd.java +++ b/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ConnectionDefinitionAdd.java @@ -54,7 +54,6 @@ import org.jboss.as.controller.PathElement; import org.jboss.as.controller.registry.Resource; import org.jboss.as.controller.security.CredentialReference; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.dmr.ModelNode; import org.jboss.jca.common.api.metadata.common.TransactionSupportEnum; import org.jboss.jca.common.api.metadata.resourceadapter.Activation; @@ -63,7 +62,6 @@ import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; -import org.jboss.security.SubjectFactory; import org.wildfly.security.auth.client.AuthenticationContext; /** @@ -180,13 +178,7 @@ else if (hasRecoverySecurityDomain && elytronRecoveryEnabled) { } if (!elytronEnabled || !elytronRecoveryEnabled) { - // hasOptionalCapability javadoc says null dependent is not allowed, but it actually is. See WFCORE-900 - if (context.hasOptionalCapability("org.wildfly.legacy-security", null, null)) { - cdServiceBuilder.addDependency(SUBJECT_FACTORY_SERVICE, SubjectFactory.class, - service.getSubjectFactoryInjector()) - .addDependency(SECURITY_MANAGER_SERVICE, - ServerSecurityManager.class, service.getServerSecurityManager()); - } else if (hasSecurityDomain || hasSecurityDomainAndApp || hasRecoverySecurityDomain || RaAdd.requiresLegacySecurity(context, raModel)) { + if (hasSecurityDomain || hasSecurityDomainAndApp || hasRecoverySecurityDomain || RaAdd.requiresLegacySecurity(context, raModel)) { // We can't satisfy the config, so fail with a meaningful error context.setRollbackOnly(); throw SUBSYSTEM_RA_LOGGER.legacySecurityNotAvailable(path.getLastElement().getValue(), path.getParent().getLastElement().getValue()); diff --git a/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ConnectionDefinitionService.java b/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ConnectionDefinitionService.java index 2438ad18b913..65c4472ce7b5 100644 --- a/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ConnectionDefinitionService.java +++ b/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ConnectionDefinitionService.java @@ -24,15 +24,12 @@ import static org.jboss.as.connector.logging.ConnectorLogger.SUBSYSTEM_RA_LOGGER; -import org.jboss.as.connector.metadata.api.resourceadapter.ActivationSecurityUtil; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; -import org.jboss.security.SubjectFactory; import org.wildfly.common.function.ExceptionSupplier; import org.wildfly.security.credential.source.CredentialSource; @@ -48,10 +45,6 @@ final class ConnectionDefinitionService implements Service { private final InjectedValue ra = new InjectedValue(); private final InjectedValue> credentialSourceSupplier = new InjectedValue<>(); - protected final InjectedValue subjectFactory = new InjectedValue(); - private final InjectedValue secManager = new InjectedValue(); - - /** create an instance **/ public ConnectionDefinitionService() { } @@ -65,13 +58,7 @@ public ModifiableConnDef getValue() throws IllegalStateException { public void start(StartContext context) throws StartException { createConnectionDefinition(); ra.getValue().addConnectionDefinition(getValue()); - // If the WM or our own ConnectionDefinition requires legacy security, we'll have had relevant - // objects injected, so pass those into the ra - if (ActivationSecurityUtil.isWorkManagerLegacySecurityRequired(ra.getValue()) - || ActivationSecurityUtil.isConnectionDefinitionLegacySecurityRequired(getValue())) { - ra.getValue().setSubjectFactory(subjectFactory.getValue()); - ra.getValue().setSecManager(secManager.getValue()); - } + SUBSYSTEM_RA_LOGGER.debugf("Starting ResourceAdapters Service"); } @@ -92,14 +79,6 @@ public InjectedValue> getConnect return connectionDefinitionSupplier; } - public Injector getSubjectFactoryInjector() { - return subjectFactory; - } - - public Injector getServerSecurityManager() { - return secManager; - } - private void createConnectionDefinition() throws IllegalStateException { ExceptionSupplier connDefSupplier = connectionDefinitionSupplier.getValue(); diff --git a/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ModifiableResourceAdapter.java b/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ModifiableResourceAdapter.java index 8ffc93069c51..e952a375d3a7 100644 --- a/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ModifiableResourceAdapter.java +++ b/connector/src/main/java/org/jboss/as/connector/subsystems/resourceadapters/ModifiableResourceAdapter.java @@ -25,25 +25,18 @@ import java.util.List; import java.util.Map; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.jca.common.api.metadata.common.TransactionSupportEnum; import org.jboss.jca.common.api.metadata.resourceadapter.AdminObject; import org.jboss.jca.common.api.metadata.resourceadapter.ConnectionDefinition; import org.jboss.jca.common.api.metadata.resourceadapter.WorkManager; import org.jboss.jca.common.metadata.resourceadapter.ActivationImpl; import org.jboss.msc.service.ServiceName; -import org.jboss.security.SubjectFactory; public class ModifiableResourceAdapter extends ActivationImpl { private volatile ServiceName raXmlDeploymentServiceName = null; - private volatile SubjectFactory subjectFactory = null; - - private volatile ServerSecurityManager secManager = null; - - public ModifiableResourceAdapter(String id, String archive, TransactionSupportEnum transactionSupport, List connectionDefinitions, List adminObjects, Map configProperties, List beanValidationGroups, String bootstrapContext, WorkManager workmanager) { @@ -78,20 +71,5 @@ public void setRaXmlDeploymentServiceName(ServiceName raXmlDeploymentServiceName this.raXmlDeploymentServiceName = raXmlDeploymentServiceName; } - public SubjectFactory getSubjectFactory() { - return subjectFactory; - } - - public void setSubjectFactory(SubjectFactory subjectFactory) { - this.subjectFactory = subjectFactory; - } - - public ServerSecurityManager getSecManager() { - return secManager; - } - - public void setSecManager(ServerSecurityManager secManager) { - this.secManager = secManager; - } } diff --git a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/connector/main/module.xml b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/connector/main/module.xml index ebc51cb88548..26a0bda5595c 100644 --- a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/connector/main/module.xml +++ b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/connector/main/module.xml @@ -53,7 +53,6 @@ - From e5e9b1131a95872797aadde46c922228210d9e4b Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Tue, 23 Nov 2021 19:12:52 +0000 Subject: [PATCH 03/11] [WFLY-15732] / [WFLY-15356] Remove use of security-plugins from Undertow subsystem. --- undertow/pom.xml | 5 - .../undertow/UndertowRootDefinition.java | 3 +- .../extension/undertow/UndertowService.java | 18 +- .../deployment/LogoutSessionListener.java | 115 ------- .../undertow/deployment/SecurityActions.java | 73 ----- .../SecurityDomainResolvingProcessor.java | 11 +- .../UndertowDeploymentInfoService.java | 114 +------ .../UndertowDeploymentProcessor.java | 4 +- .../undertow/logging/UndertowLogger.java | 10 +- .../undertow/security/AccountImpl.java | 160 --------- .../security/AuditNotificationReceiver.java | 125 ------- .../security/JAASIdentityManagerImpl.java | 177 ---------- .../security/JbossAuthorizationManager.java | 231 ------------- .../security/LogoutNotificationReceiver.java | 72 ----- .../security/RunAsLifecycleInterceptor.java | 96 ------ .../undertow/security/SecurityActions.java | 257 --------------- .../SecurityContextAssociationHandler.java | 108 ------- .../SecurityContextThreadSetupAction.java | 116 ------- .../security/UndertowSecurityAttachments.java | 35 -- ...ttpServletRequestPolicyContextHandler.java | 59 ---- .../jaspi/JASPICAuthenticationMechanism.java | 304 ------------------ .../security/jaspi/JASPICContext.java | 59 ---- .../jaspi/JASPICSecureResponseHandler.java | 70 ---- .../security/jaspi/JASPICSecurityContext.java | 202 ------------ .../jaspi/JASPICSecurityContextFactory.java | 59 ---- .../security/jaspi/SecurityActions.java | 73 ----- .../modules/HTTPSchemeServerAuthModule.java | 132 -------- 27 files changed, 22 insertions(+), 2666 deletions(-) delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/deployment/LogoutSessionListener.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/deployment/SecurityActions.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/AccountImpl.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/AuditNotificationReceiver.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/JAASIdentityManagerImpl.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/JbossAuthorizationManager.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/LogoutNotificationReceiver.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/RunAsLifecycleInterceptor.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityActions.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityContextAssociationHandler.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityContextThreadSetupAction.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/UndertowSecurityAttachments.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/jacc/HttpServletRequestPolicyContextHandler.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICAuthenticationMechanism.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICContext.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecureResponseHandler.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecurityContext.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecurityContextFactory.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/SecurityActions.java delete mode 100644 undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/modules/HTTPSchemeServerAuthModule.java diff --git a/undertow/pom.xml b/undertow/pom.xml index fc35ceabe6c2..3cf011f72109 100644 --- a/undertow/pom.xml +++ b/undertow/pom.xml @@ -78,11 +78,6 @@ org.wildfly.common wildfly-common - - ${project.groupId} - wildfly-security-plugins - provided - ${project.groupId} wildfly-web-common diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/UndertowRootDefinition.java b/undertow/src/main/java/org/wildfly/extension/undertow/UndertowRootDefinition.java index 130904221c74..98998fb8294c 100644 --- a/undertow/src/main/java/org/wildfly/extension/undertow/UndertowRootDefinition.java +++ b/undertow/src/main/java/org/wildfly/extension/undertow/UndertowRootDefinition.java @@ -46,7 +46,6 @@ import org.jboss.dmr.ModelType; import org.jboss.dmr.ValueExpression; import org.jboss.msc.service.ServiceController; -import org.jboss.security.SecurityConstants; import org.wildfly.extension.undertow.filters.FilterDefinitions; import org.wildfly.extension.undertow.handlers.HandlerDefinitions; @@ -103,7 +102,7 @@ class UndertowRootDefinition extends PersistentResourceDefinition { protected static final SimpleAttributeDefinition DEFAULT_SECURITY_DOMAIN = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_SECURITY_DOMAIN, ModelType.STRING, true) .setAllowExpression(true) - .setDefaultValue(new ModelNode(SecurityConstants.DEFAULT_APPLICATION_POLICY)) + .setDefaultValue(new ModelNode("other")) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SECURITY_DOMAIN_REF) .setRestartAllServices() .build(); diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/UndertowService.java b/undertow/src/main/java/org/wildfly/extension/undertow/UndertowService.java index 7904e8c4929d..a694a2ebc79a 100644 --- a/undertow/src/main/java/org/wildfly/extension/undertow/UndertowService.java +++ b/undertow/src/main/java/org/wildfly/extension/undertow/UndertowService.java @@ -29,19 +29,16 @@ import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.function.Consumer; -import javax.security.jacc.PolicyContext; -import javax.security.jacc.PolicyContextException; -import io.undertow.Version; import org.jboss.as.controller.PathAddress; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; -import org.jboss.security.SecurityConstants; import org.wildfly.extension.undertow.logging.UndertowLogger; -import org.wildfly.extension.undertow.security.jacc.HttpServletRequestPolicyContextHandler; + +import io.undertow.Version; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. @@ -185,22 +182,13 @@ public static ServiceName listenerName(String listenerName) { @Override public void start(final StartContext context) throws StartException { UndertowLogger.ROOT_LOGGER.serverStarting(Version.getVersionString()); - // Register the active request PolicyContextHandler - try { - PolicyContext.registerHandler(SecurityConstants.WEB_REQUEST_KEY, - new HttpServletRequestPolicyContextHandler(), true); - } catch (PolicyContextException pce) { - UndertowLogger.ROOT_LOGGER.failedToRegisterPolicyContextHandler(SecurityConstants.WEB_REQUEST_KEY, pce); - } + serviceConsumer.accept(this); } @Override public void stop(final StopContext context) { serviceConsumer.accept(null); - // Remove PolicyContextHandler - Set handlerKeys = PolicyContext.getHandlerKeys(); - handlerKeys.remove(SecurityConstants.WEB_REQUEST_KEY); UndertowLogger.ROOT_LOGGER.serverStopping(Version.getVersionString()); diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/LogoutSessionListener.java b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/LogoutSessionListener.java deleted file mode 100644 index c2463d51feae..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/LogoutSessionListener.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.deployment; - -import io.undertow.security.api.AuthenticatedSessionManager; -import io.undertow.security.api.SecurityContext; -import io.undertow.security.idm.Account; -import io.undertow.server.session.Session; -import io.undertow.servlet.handlers.ServletRequestContext; -import io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler; -import io.undertow.servlet.spec.HttpSessionImpl; -import org.jboss.security.AuthenticationManager; -import org.wildfly.extension.undertow.security.AccountImpl; -import org.wildfly.security.manager.WildFlySecurityManager; - -import javax.security.auth.Subject; -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; - -/** - * Undertow session listener that performs logout on session invalidation. The {@code AuthenticationManager} logout - * takes care of flushing the principal from cache if a security cache is in use. - * - * - * @author Stuart Douglas - */ -class LogoutSessionListener implements HttpSessionListener { - - private final AuthenticationManager manager; - - LogoutSessionListener(AuthenticationManager manager) { - this.manager = manager; - } - - @Override - public void sessionCreated(HttpSessionEvent se) { - } - @Override - public void sessionDestroyed(HttpSessionEvent se) { - if(WildFlySecurityManager.isChecking()) { - //we don't use doUnchecked here as there is a chance the below method - //can run user supplied code - AccessController.doPrivileged((PrivilegedAction) () -> { - sessionDestroyedImpl(se); - return null; - }); - } else { - sessionDestroyedImpl(se); - } - } - - private void sessionDestroyedImpl(HttpSessionEvent se) { - //we need to get the current account - //there are two options here, we can look for the account in the current request - //or we can look for the account that has been saved in the session - //for maximum compatibility we do both - ServletRequestContext src = ServletRequestContext.current(); - Account requestAccount = null; - if (src != null) { - SecurityContext securityContext = src.getExchange().getSecurityContext(); - if(securityContext != null) { - requestAccount = securityContext.getAuthenticatedAccount(); - if (requestAccount != null) { - clearAccount(requestAccount); - } - } - } - if (se.getSession() instanceof HttpSessionImpl) { - final HttpSessionImpl impl = (HttpSessionImpl) se.getSession(); - Session session = impl.getSession(); - if (session != null) { - AuthenticatedSessionManager.AuthenticatedSession authenticatedSession = (AuthenticatedSessionManager.AuthenticatedSession) session.getAttribute(CachedAuthenticatedSessionHandler.class.getName() + ".AuthenticatedSession"); - if(authenticatedSession != null) { - Account sessionAccount = authenticatedSession.getAccount(); - if (sessionAccount != null && !sessionAccount.equals(requestAccount)) { - clearAccount(sessionAccount); - } - } - } - } - } - - private void clearAccount(Account account) { - Principal principal = (account instanceof AccountImpl) ? ((AccountImpl) account).getOriginalPrincipal() : - account.getPrincipal(); - if (principal != null) { - // perform the logout of the principal using the subject currently set in the security context. - Subject subject = SecurityActions.getSubject(); - this.manager.logout(principal, subject); - } - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/SecurityActions.java b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/SecurityActions.java deleted file mode 100644 index 0eec14223f25..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/SecurityActions.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.deployment; - -import java.security.PrivilegedAction; - -import org.jboss.security.SecurityContext; -import org.jboss.security.SecurityContextAssociation; -import org.wildfly.security.manager.WildFlySecurityManager; - -import static java.security.AccessController.doPrivileged; - -import javax.security.auth.Subject; - -/** - * Privileged blocks for this package - */ -class SecurityActions { - - static SecurityContext getSecurityContext() { - if (WildFlySecurityManager.isChecking()) { - return doPrivileged(new PrivilegedAction() { - public SecurityContext run() { - return SecurityContextAssociation.getSecurityContext(); - } - }); - } else { - return SecurityContextAssociation.getSecurityContext(); - } - } - - static Subject getSubject() { - if (WildFlySecurityManager.isChecking()) { - return doPrivileged(new PrivilegedAction() { - public Subject run() { - Subject subject = null; - SecurityContext sc = getSecurityContext(); - if (sc != null) { - subject = sc.getUtil().getSubject(); - } - return subject; - } - }); - } else { - Subject subject = null; - SecurityContext sc = getSecurityContext(); - if (sc != null) { - subject = sc.getUtil().getSubject(); - } - return subject; - } - } -} \ No newline at end of file diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/SecurityDomainResolvingProcessor.java b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/SecurityDomainResolvingProcessor.java index 007b79e520a4..0bd19325776c 100644 --- a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/SecurityDomainResolvingProcessor.java +++ b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/SecurityDomainResolvingProcessor.java @@ -34,7 +34,6 @@ import org.jboss.metadata.ear.spec.EarMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.msc.service.ServiceName; -import org.jboss.security.SecurityConstants; import org.wildfly.extension.undertow.Capabilities; import org.wildfly.extension.undertow.Constants; @@ -45,6 +44,8 @@ */ public class SecurityDomainResolvingProcessor implements DeploymentUnitProcessor { + private static final String JAAS_CONTEXT_ROOT = "java:jboss/jaas/"; + private static final String JASPI_CONTEXT_ROOT = "java:jboss/jbsx/"; private static final String LEGACY_JAAS_CONTEXT_ROOT = "java:/jaas/"; private final String defaultSecurityDomain; @@ -123,10 +124,10 @@ public static String unprefixSecurityDomain(String securityDomain) { String result = null; if (securityDomain != null) { - if (securityDomain.startsWith(SecurityConstants.JAAS_CONTEXT_ROOT)) - result = securityDomain.substring(SecurityConstants.JAAS_CONTEXT_ROOT.length()); - else if (securityDomain.startsWith(SecurityConstants.JASPI_CONTEXT_ROOT)) - result = securityDomain.substring(SecurityConstants.JASPI_CONTEXT_ROOT.length()); + if (securityDomain.startsWith(JAAS_CONTEXT_ROOT)) + result = securityDomain.substring(JAAS_CONTEXT_ROOT.length()); + else if (securityDomain.startsWith(JASPI_CONTEXT_ROOT)) + result = securityDomain.substring(JASPI_CONTEXT_ROOT.length()); else if (securityDomain.startsWith(LEGACY_JAAS_CONTEXT_ROOT)) result = securityDomain.substring(LEGACY_JAAS_CONTEXT_ROOT.length()); else diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java index ec5e0ee23da0..166c4ba86aee 100644 --- a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java +++ b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java @@ -72,7 +72,6 @@ import org.jboss.as.ee.component.ComponentRegistry; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ManagedReferenceFactory; -import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.as.server.deployment.SetupAction; import org.jboss.as.server.suspend.ServerActivity; import org.jboss.as.server.suspend.ServerActivityCallback; @@ -113,14 +112,6 @@ import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; -import org.jboss.security.AuthenticationManager; -import org.jboss.security.audit.AuditManager; -import org.jboss.security.auth.login.JASPIAuthenticationInfo; -import org.jboss.security.authorization.config.AuthorizationModuleEntry; -import org.jboss.security.authorization.modules.JACCAuthorizationModule; -import org.jboss.security.config.ApplicationPolicy; -import org.jboss.security.config.AuthorizationInfo; -import org.jboss.security.config.SecurityConfiguration; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.undertow.Host; @@ -131,18 +122,7 @@ import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.extension.undertow.UndertowService; import org.wildfly.extension.undertow.ApplicationSecurityDomainDefinition.Registration; -import org.wildfly.extension.undertow.security.AuditNotificationReceiver; -import org.wildfly.extension.undertow.security.JAASIdentityManagerImpl; -import org.wildfly.extension.undertow.security.JbossAuthorizationManager; -import org.wildfly.extension.undertow.security.LogoutNotificationReceiver; -import org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor; -import org.wildfly.extension.undertow.security.SecurityContextAssociationHandler; -import org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction; -import org.wildfly.extension.undertow.security.jacc.JACCAuthorizationManager; import org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler; -import org.wildfly.extension.undertow.security.jaspi.JASPICAuthenticationMechanism; -import org.wildfly.extension.undertow.security.jaspi.JASPICSecureResponseHandler; -import org.wildfly.extension.undertow.security.jaspi.JASPICSecurityContextFactory; import org.wildfly.extension.undertow.session.CodecSessionConfigWrapper; import org.wildfly.security.auth.server.HttpAuthenticationFactory; import org.wildfly.security.auth.server.MechanismConfiguration; @@ -187,7 +167,6 @@ import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.PERMIT; import org.jboss.as.server.ServerEnvironment; -import org.jboss.security.authentication.JBossCachedAuthenticationManager; /** * Service that builds up the undertow metadata. @@ -231,7 +210,6 @@ public class UndertowDeploymentInfoService implements Service { private final Supplier undertowService; private final Supplier sessionManagerFactory; private final Supplier sessionIdentifierCodec; - private final Supplier securityDomainContext; private final Supplier container; private final Supplier componentRegistry; private final Supplier host; @@ -252,7 +230,6 @@ private UndertowDeploymentInfoService( final Supplier undertowService, final Supplier sessionManagerFactory, final Supplier sessionIdentifierCodec, - final Supplier securityDomainContext, final Supplier container, final Supplier componentRegistry, final Supplier host, @@ -267,7 +244,6 @@ private UndertowDeploymentInfoService( this.undertowService = undertowService; this.sessionManagerFactory = sessionManagerFactory; this.sessionIdentifierCodec = sessionIdentifierCodec; - this.securityDomainContext = securityDomainContext; this.container = container; this.componentRegistry = componentRegistry; this.host = host; @@ -315,18 +291,11 @@ public synchronized void start(final StartContext startContext) throws StartExce handleDistributable(deploymentInfo); if (!isElytronActive()) { - if (securityDomain != null) { - handleIdentityManager(deploymentInfo); - handleJASPIMechanism(deploymentInfo); - handleJACCAuthorization(deploymentInfo); - handleAuthManagerLogout(deploymentInfo, mergedMetaData); + if (securityDomain != null || mergedMetaData.isUseJBossAuthorization()) { + throw UndertowLogger.ROOT_LOGGER.legacySecurityUnsupported(); } else { deploymentInfo.setSecurityDisabled(true); } - - if(mergedMetaData.isUseJBossAuthorization()) { - deploymentInfo.setAuthorizationManager(new JbossAuthorizationManager(deploymentInfo.getAuthorizationManager())); - } } handleAdditionalAuthenticationMechanisms(deploymentInfo); @@ -463,25 +432,10 @@ public synchronized void start(final StartContext startContext) throws StartExce } - private void handleAuthManagerLogout(DeploymentInfo deploymentInfo, JBossWebMetaData mergedMetaData) { - AuthenticationManager manager = securityDomainContext.get().getAuthenticationManager(); - deploymentInfo.addNotificationReceiver(new LogoutNotificationReceiver(manager, securityDomain)); - if(mergedMetaData.isFlushOnSessionInvalidation()) { - LogoutSessionListener listener = new LogoutSessionListener(manager); - deploymentInfo.addListener(Servlets.listener(LogoutSessionListener.class, new ImmediateInstanceFactory(listener))); - } - } - @Override public synchronized void stop(final StopContext stopContext) { deploymentInfoConsumer.accept(null); IoUtils.safeClose(this.deploymentInfo.getResourceManager()); - if (securityDomain != null && !isElytronActive()) { - AuthenticationManager authManager = securityDomainContext.get().getAuthenticationManager(); - if (authManager != null && authManager instanceof JBossCachedAuthenticationManager) { - ((JBossCachedAuthenticationManager) authManager).releaseModuleEntries(module.getClassLoader()); - } - } this.deploymentInfo.setConfidentialPortManager(null); this.deploymentInfo = null; if (registration != null) { @@ -494,66 +448,12 @@ public synchronized DeploymentInfo getValue() throws IllegalStateException, Ille return deploymentInfo; } - /** - *

Adds to the deployment the {@link org.wildfly.extension.undertow.security.jaspi.JASPICAuthenticationMechanism}, if necessary. The handler will be added if the security domain - * is configured with JASPI authentication.

- * - * @param deploymentInfo - */ - private void handleJASPIMechanism(final DeploymentInfo deploymentInfo) { - ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); - - if (applicationPolicy != null && JASPIAuthenticationInfo.class.isInstance(applicationPolicy.getAuthenticationInfo())) { - String authMethod = null; - LoginConfig loginConfig = deploymentInfo.getLoginConfig(); - if (loginConfig != null && !loginConfig.getAuthMethods().isEmpty()) { - authMethod = loginConfig.getAuthMethods().get(0).getName(); - } - deploymentInfo.setJaspiAuthenticationMechanism(new JASPICAuthenticationMechanism(securityDomain, authMethod)); - deploymentInfo.setSecurityContextFactory(new JASPICSecurityContextFactory(this.securityDomain)); - deploymentInfo.addOuterHandlerChainWrapper(next -> new JASPICSecureResponseHandler(next)); - } - } - - /** - *

- * Sets the {@link JACCAuthorizationManager} in the specified {@link DeploymentInfo} if the webapp security domain - * has defined a JACC authorization module. - *

- * - * @param deploymentInfo the {@link DeploymentInfo} instance. - */ - private void handleJACCAuthorization(final DeploymentInfo deploymentInfo) { - // TODO make the authorization manager implementation configurable in Undertow or jboss-web.xml - ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); - if (applicationPolicy != null) { - AuthorizationInfo authzInfo = applicationPolicy.getAuthorizationInfo(); - if (authzInfo != null) { - for (AuthorizationModuleEntry entry : authzInfo.getModuleEntries()) { - if (JACCAuthorizationModule.class.getName().equals(entry.getPolicyModuleName())) { - deploymentInfo.setAuthorizationManager(JACCAuthorizationManager.INSTANCE); - break; - } - } - } - } - } - private void handleAdditionalAuthenticationMechanisms(final DeploymentInfo deploymentInfo) { for (Map.Entry am : host.get().getAdditionalAuthenticationMechanisms().entrySet()) { deploymentInfo.addFirstAuthenticationMechanism(am.getKey(), am.getValue()); } } - private void handleIdentityManager(final DeploymentInfo deploymentInfo) { - SecurityDomainContext sdc = securityDomainContext.get(); - deploymentInfo.setIdentityManager(new JAASIdentityManagerImpl(sdc)); - AuditManager auditManager = sdc.getAuditManager(); - if (auditManager != null && !mergedMetaData.isDisableAudit()) { - deploymentInfo.addNotificationReceiver(new AuditNotificationReceiver(auditManager)); - } - } - private ConfidentialPortManager getConfidentialPortManager() { return new ConfidentialPortManager() { @@ -994,12 +894,7 @@ private DeploymentInfo createServletConfig() throws StartException { applyElytronSecurity(d, runAsIdentityMap::get); } else { if (securityDomain != null) { - d.addThreadSetupAction(new SecurityContextThreadSetupAction(securityDomain, securityDomainContext.get(), principalVersusRolesMap)); - - d.addInnerHandlerChainWrapper(SecurityContextAssociationHandler.wrapper(mergedMetaData.getRunAsIdentity())); - d.addOuterHandlerChainWrapper(JACCContextIdHandler.wrapper(jaccContextId)); - - d.addLifecycleInterceptor(new RunAsLifecycleInterceptor(mergedMetaData.getRunAsIdentity())); + throw UndertowLogger.ROOT_LOGGER.legacySecurityUnsupported(); } } @@ -1508,7 +1403,6 @@ public UndertowDeploymentInfoService createUndertowDeploymentInfoService( final Supplier undertowService, final Supplier sessionManagerFactory, final Supplier sessionIdentifierCodec, - final Supplier securityDomainContext, final Supplier container, final Supplier componentRegistry, final Supplier host, @@ -1520,7 +1414,7 @@ public UndertowDeploymentInfoService createUndertowDeploymentInfoService( final Supplier applySecurityFunction ) { return new UndertowDeploymentInfoService(deploymentInfoConsumer, undertowService, sessionManagerFactory, - sessionIdentifierCodec, securityDomainContext, container, componentRegistry, host, controlPoint, + sessionIdentifierCodec, container, componentRegistry, host, controlPoint, suspendController, serverEnvironment, rawSecurityDomain, rawMechanismFactory, applySecurityFunction, mergedMetaData, deploymentName, tldInfo, module, scisMetaData, deploymentRoot, jaccContextId, securityDomain, attributes, contextPath, setupActions, overlays, expressionFactoryWrappers, predicatedHandlers, initialHandlerChainWrappers, innerHandlerChainWrappers, outerHandlerChainWrappers, diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentProcessor.java b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentProcessor.java index fe04635e8273..3bb4d2d6895a 100644 --- a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentProcessor.java +++ b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentProcessor.java @@ -66,7 +66,6 @@ import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ee.component.deployers.StartupCountdown; import org.jboss.as.ee.security.JaccService; -import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.as.server.ServerEnvironment; import org.jboss.as.server.ServerEnvironmentService; import org.jboss.as.server.Services; @@ -322,7 +321,6 @@ private void processDeployment(final WarMetaData warMetaData, final DeploymentUn final Supplier usSupplier = udisBuilder.requires(UndertowService.UNDERTOW); final Supplier smfSupplier; final Supplier sicSupplier; - Supplier sdcSupplier = null; final Supplier scsSupplier = udisBuilder.requires(UndertowService.SERVLET_CONTAINER.append(servletContainerName)); final Supplier crSupplier = componentRegistryExists ? udisBuilder.requires(ComponentRegistry.serviceName(deploymentUnit)) : new Supplier() { @Override @@ -444,7 +442,7 @@ public Duration getDefaultSessionTimeout() { .setTempDir(warMetaData.getTempDir()) .setExternalResources(deploymentUnit.getAttachmentList(UndertowAttachments.EXTERNAL_RESOURCES)) .setAllowSuspendedRequests(deploymentUnit.getAttachmentList(UndertowAttachments.ALLOW_REQUEST_WHEN_SUSPENDED)) - .createUndertowDeploymentInfoService(diConsumer, usSupplier, smfSupplier, sicSupplier, sdcSupplier, + .createUndertowDeploymentInfoService(diConsumer, usSupplier, smfSupplier, sicSupplier, scsSupplier, crSupplier, hostSupplier, cpSupplier, scSupplier, serverEnvSupplier, sdSupplier, mechanismFactorySupplier, bfSupplier); udisBuilder.setInstance(undertowDeploymentInfoService); diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/logging/UndertowLogger.java b/undertow/src/main/java/org/wildfly/extension/undertow/logging/UndertowLogger.java index 039c8965c5bb..70bf7aa87e1e 100644 --- a/undertow/src/main/java/org/wildfly/extension/undertow/logging/UndertowLogger.java +++ b/undertow/src/main/java/org/wildfly/extension/undertow/logging/UndertowLogger.java @@ -168,9 +168,9 @@ public interface UndertowLogger extends BasicLogger { @Message(id = 24, value = "Failed to persist session attribute %s with value %s for session %s") void failedToPersistSessionAttribute(String attributeName, Object value, String sessionID, @Cause Exception e); - @LogMessage(level = ERROR) - @Message(id = 25, value = "Failed to register policy context handler for key %s") - void failedToRegisterPolicyContextHandler(String key, @Cause Exception e); + //@LogMessage(level = ERROR) + //@Message(id = 25, value = "Failed to register policy context handler for key %s") + //void failedToRegisterPolicyContextHandler(String key, @Cause Exception e); // @Message(id = 26, value = "Unknown handler '%s' encountered") // XMLStreamException unknownHandler(String name, @Param Location location); @@ -435,4 +435,8 @@ public interface UndertowLogger extends BasicLogger { @Message(id=108, value = "The deployment is configured to use legacy security which is no longer available.") DeploymentUnitProcessingException deploymentConfiguredForLegacySecurity(); + + @Message(id = 109, value = "The deployment is configured to use legacy security which is no longer supported.") + StartException legacySecurityUnsupported(); + } diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/AccountImpl.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/AccountImpl.java deleted file mode 100644 index 9c6ee970a798..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/AccountImpl.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import java.io.Serializable; -import java.security.Principal; -import java.util.Collections; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -import io.undertow.security.idm.Account; - -/** - * - * @author Stuart Douglas - * @author Darran Lofthouse - */ -public class AccountImpl implements Account, Serializable { - - private static final long serialVersionUID = 1L; - - private final String name; - private final Set roles = new CopyOnWriteArraySet<>(); - private final Principal principal; - private final Object credential; - - private final Principal originalPrincipal; - - public AccountImpl(final String name) { - this.name = name; - this.principal = new AccountPrincipal(name); - this.credential = null; - this.originalPrincipal = null; - } - - public AccountImpl(final Principal principal) { - this.principal = principal; - this.name = principal.getName(); - this.credential = null; - this.originalPrincipal = null; - } - public AccountImpl(final Principal principal, Set roles, final Object credential, Principal originalPrincipal) { - this.principal = principal; - this.credential = credential; - this.originalPrincipal = originalPrincipal; - this.name = principal.getName(); - this.roles.addAll(roles); - } - - public AccountImpl(final Principal principal, Set roles, final Object credential) { - this.principal = principal; - this.credential = credential; - this.originalPrincipal = null; - this.name = principal.getName(); - this.roles.addAll(roles); - } - - @Override - public boolean equals(final Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - - final AccountImpl account = (AccountImpl) o; - - if (name != null ? !name.equals(account.name) : account.name != null) - return false; - - return true; - } - - @Override - public int hashCode() { - return name != null ? name.hashCode() : 0; - } - - @Override - public Principal getPrincipal() { - return principal; - } - - @Override - public Set getRoles() { - return Collections.unmodifiableSet(roles); - } - - /** - * If the original principal was set then this will be returned, otherwise - * it will return the current principal. - * - * If principal mapping is used the principal for the verified account can be different - * to the principal that need to be used for authentication. When calling - * {@link io.undertow.security.idm.IdentityManager#verify(io.undertow.security.idm.Account)} - * for an existing account this is the principal that must be used. - * - * see UNDERTOW-273 - * @return The original principal - */ - public Principal getOriginalPrincipal() { - if (originalPrincipal != null) { - return originalPrincipal; - } - return principal; - } - - public Object getCredential() { - return credential; - } - - private static class AccountPrincipal implements Principal, Serializable { - - private static final long serialVersionUID = 1L; - private String name; - - public AccountPrincipal(String name) { - this.name = name; - } - - @Override - public String getName() { - return name; - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof AccountPrincipal ? equals((AccountPrincipal) obj) : false; - } - - private boolean equals(AccountPrincipal other) { - return name.equals(other.getName()); - } - - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/AuditNotificationReceiver.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/AuditNotificationReceiver.java deleted file mode 100644 index 470abb6ac9b7..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/AuditNotificationReceiver.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import java.util.Arrays; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; - -import io.undertow.security.api.NotificationReceiver; -import io.undertow.security.api.SecurityNotification; -import io.undertow.security.api.SecurityNotification.EventType; -import io.undertow.security.idm.Account; -import io.undertow.servlet.handlers.ServletRequestContext; -import org.jboss.security.audit.AuditEvent; -import org.jboss.security.audit.AuditLevel; -import org.jboss.security.audit.AuditManager; - -/** - * A {@link NotificationReceiver} implementation responsible for recording audit events for authentication attempts. - * - * @author Darran Lofthouse - */ -public class AuditNotificationReceiver implements NotificationReceiver { - - private final AuditManager auditManager; - - public AuditNotificationReceiver(final AuditManager auditManager) { - this.auditManager = auditManager; - } - - @Override - public void handleNotification(SecurityNotification notification) { - EventType event = notification.getEventType(); - if (event == EventType.AUTHENTICATED || event == EventType.FAILED_AUTHENTICATION) { - AuditEvent auditEvent = new AuditEvent(event == EventType.AUTHENTICATED ? AuditLevel.SUCCESS : AuditLevel.FAILURE); - Map ctxMap = new HashMap(); - Account account = notification.getAccount(); - if (account != null) { - ctxMap.put("principal", account.getPrincipal().getName()); - } - ctxMap.put("message", notification.getMessage()); - - ServletRequestContext src = notification.getExchange().getAttachment(ServletRequestContext.ATTACHMENT_KEY); - if(src != null) { - ServletRequest hsr = src.getServletRequest(); - if (hsr instanceof HttpServletRequest) { - ctxMap.put("request", deriveUsefulInfo((HttpServletRequest) hsr)); - } - } - ctxMap.put("Source", getClass().getCanonicalName()); - auditEvent.setContextMap(ctxMap); - auditManager.audit(auditEvent); - - } - } - - /** - * Obtain debug information from the servlet request object - * - * @param httpRequest - * @return - */ - private static String deriveUsefulInfo(HttpServletRequest httpRequest) { - StringBuilder sb = new StringBuilder(); - sb.append("[").append(httpRequest.getContextPath()); - sb.append(":cookies=").append(Arrays.toString(httpRequest.getCookies())).append(":headers="); - // Append Header information - Enumeration en = httpRequest.getHeaderNames(); - while (en.hasMoreElements()) { - String headerName = (String) en.nextElement(); - sb.append(headerName).append("="); - // Ensure HTTP Basic Password is not logged - if (!headerName.contains("authorization")) { sb.append(httpRequest.getHeader(headerName)).append(","); } - } - sb.append("]"); - // Append Request parameter information - sb.append("[parameters="); - Enumeration enparam = httpRequest.getParameterNames(); - while (enparam.hasMoreElements()) { - String paramName = (String) enparam.nextElement(); - final String[] paramValues; - if (paramName.equals("j_password")) { - paramValues = new String[] {"***"}; - } else { - paramValues = httpRequest.getParameterValues(paramName); - } - int len = paramValues != null ? paramValues.length : 0; - for (int i = 0; i < len; i++) { sb.append(paramValues[i]).append("::"); } - sb.append(","); - } - sb.append("][attributes="); - // Append Request attribute information - Enumeration enu = httpRequest.getAttributeNames(); - while (enu.hasMoreElements()) { - String attrName = (String) enu.nextElement(); - sb.append(attrName).append("="); - sb.append(httpRequest.getAttribute(attrName)).append(","); - } - sb.append("]"); - return sb.toString(); - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/JAASIdentityManagerImpl.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/JAASIdentityManagerImpl.java deleted file mode 100644 index fd900795d7b2..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/JAASIdentityManagerImpl.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import io.undertow.security.idm.Account; -import io.undertow.security.idm.Credential; - -import org.wildfly.extension.undertow.security.digest.DigestCredential; - -import io.undertow.security.idm.IdentityManager; -import io.undertow.security.idm.PasswordCredential; -import io.undertow.security.idm.X509CertificateCredential; - -import java.security.Principal; -import java.security.acl.Group; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; - -import javax.security.auth.Subject; - -import org.jboss.as.security.plugins.SecurityDomainContext; -import org.jboss.security.AuthenticationManager; -import org.jboss.security.AuthorizationManager; -import org.jboss.security.SecurityConstants; -import org.jboss.security.SecurityContext; -import org.jboss.security.auth.callback.CallbackHandlerPolicyContextHandler; -import org.jboss.security.auth.callback.DigestCallbackHandler; -import org.jboss.security.callbacks.SecurityContextCallbackHandler; -import org.jboss.security.identity.Role; -import org.jboss.security.identity.RoleGroup; -import org.wildfly.extension.undertow.logging.UndertowLogger; - -/** - * @author Stuart Douglas - * @author Darran Lofthouse - */ -public class JAASIdentityManagerImpl implements IdentityManager { - - private final SecurityDomainContext securityDomainContext; - - public JAASIdentityManagerImpl(final SecurityDomainContext securityDomainContext) { - this.securityDomainContext = securityDomainContext; - } - - @Override - public Account verify(Account account) { - // This method is called for previously verfified accounts so just accept it for the moment. - if (!(account instanceof AccountImpl)) { - UndertowLogger.ROOT_LOGGER.tracef("Account is not an AccountImpl", account); - return null; - } - AccountImpl accountImpl = (AccountImpl) account; - return verifyCredential(accountImpl, accountImpl.getCredential()); - } - - @Override - public Account verify(String id, Credential credential) { - AccountImpl account = getAccount(id); - if (credential instanceof DigestCredential) { - DigestCredential digestCredential = (DigestCredential) credential; - DigestCallbackHandler handler = new DigestCallbackHandler(id, digestCredential.getNonce(), digestCredential.getNonceCount(), - digestCredential.getClientNonce(), digestCredential.getQop(), digestCredential.getRealm(), - digestCredential.getHA2()); - CallbackHandlerPolicyContextHandler.setCallbackHandler(handler); - - return verifyCredential(account, digestCredential.getClientDigest()); - } else if(credential instanceof PasswordCredential) { - final char[] password = ((PasswordCredential) credential).getPassword(); - // The original array may be cleared, this integration relies on it being cached for use later. - final char[] duplicate = Arrays.copyOf(password, password.length); - return verifyCredential(account, duplicate); - } else { - return verifyCredential(account, credential); - } - } - - @Override - public Account verify(Credential credential) { - if (credential instanceof X509CertificateCredential) { - X509CertificateCredential certCredential = (X509CertificateCredential) credential; - X509Certificate certificate = certCredential.getCertificate(); - AccountImpl account = getAccount(certificate.getSubjectDN().getName()); - - return verifyCredential(account, certificate); - } - throw new IllegalArgumentException("Parameter must be a X509CertificateCredential"); - } - - private AccountImpl getAccount(final String id) { - return new AccountImpl(id); - } - - private Account verifyCredential(final AccountImpl account, final Object credential) { - final AuthenticationManager authenticationManager = securityDomainContext.getAuthenticationManager(); - final AuthorizationManager authorizationManager = securityDomainContext.getAuthorizationManager(); - final SecurityContext sc = SecurityActions.getSecurityContext(); - Principal incomingPrincipal = account.getOriginalPrincipal(); - Subject subject = new Subject(); - try { - boolean isValid = authenticationManager.isValid(incomingPrincipal, credential, subject); - if (isValid) { - UndertowLogger.ROOT_LOGGER.tracef("User: %s is authenticated", incomingPrincipal); - if (sc == null) { - throw UndertowLogger.ROOT_LOGGER.noSecurityContext(); - } - Principal userPrincipal = getPrincipal(subject); - sc.getUtil().createSubjectInfo(incomingPrincipal, credential, subject); - SecurityContextCallbackHandler scb = new SecurityContextCallbackHandler(sc); - RoleGroup roles = authorizationManager.getSubjectRoles(subject, scb); - Set roleSet = new HashSet<>(); - for (Role role : roles.getRoles()) { - roleSet.add(role.getRoleName()); - } - return new AccountImpl(userPrincipal, roleSet, credential, account.getOriginalPrincipal()); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - return null; - } - - /** - * Get the Principal given the authenticated Subject. Currently the first principal that is not of type {@code Group} is - * considered or the single principal inside the CallerPrincipal group. - * - * @param subject - * @return the authenticated principal - */ - private Principal getPrincipal(Subject subject) { - Principal principal = null; - Principal callerPrincipal = null; - if (subject != null) { - Set principals = subject.getPrincipals(); - if (principals != null && !principals.isEmpty()) { - for (Principal p : principals) { - if (!(p instanceof Group) && principal == null) { - principal = p; - } - if (p instanceof Group) { - Group g = Group.class.cast(p); - if (g.getName().equals(SecurityConstants.CALLER_PRINCIPAL_GROUP) && callerPrincipal == null) { - Enumeration e = g.members(); - if (e.hasMoreElements()) - callerPrincipal = e.nextElement(); - } - } - } - } - } - return callerPrincipal == null ? principal : callerPrincipal; - } - - -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/JbossAuthorizationManager.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/JbossAuthorizationManager.java deleted file mode 100644 index 48c9a282ad02..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/JbossAuthorizationManager.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import io.undertow.security.idm.Account; -import io.undertow.server.HttpServerExchange; -import io.undertow.servlet.api.AuthorizationManager; -import io.undertow.servlet.api.Deployment; -import io.undertow.servlet.api.SecurityRoleRef; -import io.undertow.servlet.api.ServletInfo; -import io.undertow.servlet.api.SingleConstraintMatch; -import io.undertow.servlet.api.TransportGuaranteeType; -import io.undertow.servlet.handlers.ServletRequestContext; -import org.jboss.as.core.security.SimplePrincipal; -import org.jboss.security.SecurityContext; -import org.jboss.security.authorization.ResourceKeys; -import org.jboss.security.javaee.AbstractWebAuthorizationHelper; -import org.jboss.security.javaee.SecurityHelperFactory; -import org.wildfly.extension.undertow.logging.UndertowLogger; - -import javax.security.auth.Subject; -import javax.security.jacc.PolicyContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.security.Principal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * @author Stuart Douglas - */ -public class JbossAuthorizationManager implements AuthorizationManager { - - private final AuthorizationManager delegate; - - public JbossAuthorizationManager(AuthorizationManager delegate) { - this.delegate = delegate; - } - - @Override - public boolean isUserInRole(String role, Account account, ServletInfo servletInfo, HttpServletRequest request, Deployment deployment) { - boolean authzDecision = true; - boolean baseDecision = delegate.isUserInRole(role, account, servletInfo, request, deployment); - // if the RealmBase check has passed, then we can go to authz framework - if (baseDecision) { - String servletName = servletInfo.getName(); - String roleName = role; - List roleRefs = servletInfo.getSecurityRoleRefs(); - if (roleRefs != null) { - for (SecurityRoleRef ref : roleRefs) { - if (ref.getLinkedRole().equals(role)) { - roleName = ref.getRole(); - break; - } - } - } - - SecurityContext sc = SecurityActions.getSecurityContext(); - AbstractWebAuthorizationHelper helper = null; - try { - helper = SecurityHelperFactory.getWebAuthorizationHelper(sc); - } catch (Exception e) { - UndertowLogger.ROOT_LOGGER.noAuthorizationHelper(e); - return false; - - } - Subject callerSubject = sc.getUtil().getSubject(); - //if (callerSubject == null) { - // // During hasResourcePermission check, Catalina calls hasRole. But we have not established - // // a subject yet in the security context. So we will get the subject from the cached principal - // callerSubject = getSubjectFromRequestPrincipal(principal); - //} - - authzDecision = SecurityActions.hasRole(helper, roleName, account.getPrincipal(), servletName, getPrincipalRoles(account), - PolicyContext.getContextID(), callerSubject, new ArrayList(account.getRoles())); - } - boolean finalDecision = baseDecision && authzDecision; - UndertowLogger.ROOT_LOGGER.tracef("hasRole:RealmBase says: %s ::Authz framework says: %s :final= %s", baseDecision, authzDecision, finalDecision); - //TODO: do we need audit for this? - /* - if (finalDecision) { - if (!disableAudit) { - Map entries = new HashMap(); - entries.put("Step", "hasRole"); - successAudit(principal, entries); - } - } else { - if (!disableAudit) { - Map entries = new HashMap(); - entries.put("Step", "hasRole"); - failureAudit(principal, entries); - } - } - */ - - return finalDecision; - } - - private Set getPrincipalRoles(Account account) { - final Set roles = new HashSet<>(); - for (String role : account.getRoles()) { - roles.add(new SimplePrincipal(role)); - } - return roles; - } - - @Override - public boolean canAccessResource(List mappedConstraints, Account account, ServletInfo servletInfo, HttpServletRequest request, Deployment deployment) { - ServletRequestContext src = ServletRequestContext.current(); - boolean baseDecision = delegate.canAccessResource(mappedConstraints, account, servletInfo, request, deployment); - boolean authzDecision = false; - // if the RealmBase check has passed, then we can go to authz framework - if (baseDecision) { - SecurityContext sc = SecurityActions.getSecurityContext(); - Subject caller = sc.getUtil().getSubject(); - //if (caller == null) { - // caller = getSubjectFromRequestPrincipal(request.getPrincipal()); - //} - Map contextMap = new HashMap(); - contextMap.put(ResourceKeys.RESOURCE_PERM_CHECK, Boolean.TRUE); - contextMap.put("securityConstraints", mappedConstraints); //TODO? What should this be? - - AbstractWebAuthorizationHelper helper = null; - try { - helper = SecurityHelperFactory.getWebAuthorizationHelper(sc); - } catch (Exception e) { - UndertowLogger.ROOT_LOGGER.noAuthorizationHelper(e); - return false; - } - - ArrayList roles = new ArrayList(); - if(account != null) { - roles.addAll(account.getRoles()); - } - authzDecision = helper.checkResourcePermission(contextMap, request, src.getServletResponse(), caller, PolicyContext.getContextID(), - requestURI(src.getExchange()), roles); - } - boolean finalDecision = baseDecision && authzDecision && hasUserDataPermission(request, src.getOriginalResponse(), account, mappedConstraints); - - UndertowLogger.ROOT_LOGGER.tracef("hasResourcePermission:RealmBase says: %s ::Authz framework says: %s :final= %s", baseDecision, authzDecision, finalDecision); - //TODO: audit? - - return finalDecision; - - } - - - public boolean hasUserDataPermission(HttpServletRequest request, HttpServletResponse response, Account account, List constraints) { - Map map = new HashMap(); - map.put("securityConstraints", constraints); - map.put(ResourceKeys.USERDATA_PERM_CHECK, Boolean.TRUE); - - SecurityContext sc = SecurityActions.getSecurityContext(); - AbstractWebAuthorizationHelper helper = null; - try { - helper = SecurityHelperFactory.getWebAuthorizationHelper(sc); - } catch (Exception e) { - UndertowLogger.ROOT_LOGGER.noAuthorizationHelper(e); - return false; - } - - Subject callerSubject = sc.getUtil().getSubject(); - // JBAS-6419:CallerSubject has no bearing on the user data permission check - if (callerSubject == null) { - callerSubject = new Subject(); - } - - ArrayList roles = new ArrayList(); - if(account != null) { - roles.addAll(account.getRoles()); - } - boolean ok = helper.hasUserDataPermission(map, request, response, PolicyContext.getContextID(), callerSubject, - roles); - - //If the status of the response has already been changed (it is different from the default Response.SC_OK) we should not attempt to change it. - if (!ok && response.getStatus() == HttpServletResponse.SC_OK) { - try { - response.sendError(HttpServletResponse.SC_FORBIDDEN); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return ok; - } - - @Override - public TransportGuaranteeType transportGuarantee(TransportGuaranteeType currentConnectionGuarantee, TransportGuaranteeType configuredRequiredGuarantee, HttpServletRequest request) { - return delegate.transportGuarantee(currentConnectionGuarantee, configuredRequiredGuarantee, request); - } - - - /** - * Get the canonical request URI from the request mapping data requestPath - * - * @param request - * @return the request URI path - */ - protected String requestURI(HttpServerExchange request) { - String uri = request.getRelativePath(); - if (uri == null || uri.equals("/")) { - uri = ""; - } - return uri; - } - -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/LogoutNotificationReceiver.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/LogoutNotificationReceiver.java deleted file mode 100644 index db4dc882cc0c..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/LogoutNotificationReceiver.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import io.undertow.security.api.NotificationReceiver; -import io.undertow.security.api.SecurityNotification; -import io.undertow.security.idm.Account; -import org.jboss.security.AuthenticationManager; - -import javax.security.auth.Subject; -import java.security.Principal; - -/** - * Undertow security listener that invokes {@code AuthenticationManager.logout()} on logout, flushing the principal from - * the cache if a security cache is being used. - * - * @author Stuart Douglas - */ -public class LogoutNotificationReceiver implements NotificationReceiver { - - private final AuthenticationManager manager; - private final String securityDomain; - - public LogoutNotificationReceiver(AuthenticationManager manager, String securityDomain) { - this.manager = manager; - this.securityDomain = securityDomain; - } - - @Override - public void handleNotification(SecurityNotification notification) { - if (notification.getEventType() == SecurityNotification.EventType.LOGGED_OUT) { - Account account = notification.getAccount(); - Principal principal = (account instanceof AccountImpl) ? ((AccountImpl) account).getOriginalPrincipal() : - account.getPrincipal(); - if (principal != null) { - // perform the logout of the principal using the subject currently set in the security context. - Subject subject = SecurityActions.getSubject(); - this.manager.logout(principal, subject); - } - - // Clear old context - SecurityActions.clearSecurityContext(); - SecurityActions.setSecurityRoles(null); - - // Set a new one in case re-authentication is done within the same thread - org.jboss.security.SecurityContext securityContext = SecurityActions.createSecurityContext(securityDomain); - notification.getExchange().putAttachment(UndertowSecurityAttachments.SECURITY_CONTEXT_ATTACHMENT, securityContext); - - SecurityActions.setSecurityContextOnAssociation(securityContext); - } - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/RunAsLifecycleInterceptor.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/RunAsLifecycleInterceptor.java deleted file mode 100644 index c96bf4bad184..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/RunAsLifecycleInterceptor.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import io.undertow.servlet.api.FilterInfo; -import io.undertow.servlet.api.LifecycleInterceptor; -import io.undertow.servlet.api.ServletInfo; -import org.jboss.metadata.javaee.jboss.RunAsIdentityMetaData; -import org.jboss.security.RunAs; -import org.jboss.security.RunAsIdentity; -import org.jboss.security.SecurityContext; -import org.wildfly.extension.undertow.logging.UndertowLogger; - -import javax.servlet.Filter; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import java.util.Map; - -public class RunAsLifecycleInterceptor implements LifecycleInterceptor { - - private final Map runAsIdentityMetaDataMap; - - public RunAsLifecycleInterceptor(final Map runAsIdentityMetaDataMap) { - this.runAsIdentityMetaDataMap = runAsIdentityMetaDataMap; - } - - private void handle(ServletInfo servletInfo, LifecycleContext context) throws ServletException { - RunAsIdentityMetaData identity = null; - RunAs old = null; - SecurityContext sc = SecurityActions.getSecurityContext(); - if (sc == null) { - context.proceed(); - return; - } - try { - identity = runAsIdentityMetaDataMap.get(servletInfo.getName()); - RunAsIdentity runAsIdentity = null; - if (identity != null) { - UndertowLogger.ROOT_LOGGER.tracef("%s, runAs: %s", servletInfo.getName(), identity); - runAsIdentity = new RunAsIdentity(identity.getRoleName(), identity.getPrincipalName(), identity.getRunAsRoles()); - } - old = SecurityActions.setRunAsIdentity(runAsIdentity, sc); - - // Perform the request - context.proceed(); - } finally { - if (identity != null) { - SecurityActions.setRunAsIdentity(old, sc); - } - } - } - - @Override - public void init(ServletInfo servletInfo, Servlet servlet, LifecycleContext context) throws ServletException { - if (servletInfo.getRunAs() != null) { - handle(servletInfo, context); - } else { - context.proceed(); - } - } - - @Override - public void init(FilterInfo filterInfo, Filter filter, LifecycleContext context) throws ServletException { - context.proceed(); - } - - @Override - public void destroy(ServletInfo servletInfo, Servlet servlet, LifecycleContext context) throws ServletException { - handle(servletInfo, context); - } - - @Override - public void destroy(FilterInfo filterInfo, Filter filter, LifecycleContext context) throws ServletException { - context.proceed(); - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityActions.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityActions.java deleted file mode 100644 index 29f7e275b7e8..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityActions.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.jboss.security.RunAs; -import org.jboss.security.SecurityContext; -import org.jboss.security.SecurityContextAssociation; -import org.jboss.security.SecurityContextFactory; -import org.jboss.security.SecurityRolesAssociation; -import org.jboss.security.javaee.AbstractWebAuthorizationHelper; -import org.wildfly.extension.undertow.logging.UndertowLogger; -import org.wildfly.security.manager.WildFlySecurityManager; - -import javax.security.auth.Subject; - -import static java.security.AccessController.doPrivileged; - -/** - * Privileged Actions - * - * @author Anil.Saldhana@redhat.com - * @since Jan 12, 2011 - */ -class SecurityActions { - - public static final String AUTH_EXCEPTION_KEY = "org.jboss.security.exception"; - - /** - * Create a JBoss Security Context with the given security domain name - * - * @param domain the security domain name (such as "other" ) - * @return an instanceof {@code SecurityContext} - */ - static SecurityContext createSecurityContext(final String domain) { - if (WildFlySecurityManager.isChecking()) { - return WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - @Override - public SecurityContext run() { - try { - return SecurityContextFactory.createSecurityContext(domain); - } catch (Exception e) { - throw UndertowLogger.ROOT_LOGGER.failToCreateSecurityContext(e); - } - } - }); - } else { - try { - return SecurityContextFactory.createSecurityContext(domain); - } catch (Exception e) { - throw UndertowLogger.ROOT_LOGGER.failToCreateSecurityContext(e); - } - } - } - - /** - * Set the {@code SecurityContext} on the {@code SecurityContextAssociation} - * - * @param sc the security context - */ - static void setSecurityContextOnAssociation(final SecurityContext sc) { - if (WildFlySecurityManager.isChecking()) { - WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - @Override - public Void run() { - SecurityContextAssociation.setSecurityContext(sc); - return null; - } - }); - } else { - SecurityContextAssociation.setSecurityContext(sc); - } - } - - /** - * Get the current {@code SecurityContext} - * - * @return an instance of {@code SecurityContext} - */ - static SecurityContext getSecurityContext() { - if (WildFlySecurityManager.isChecking()) { - return WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - public SecurityContext run() { - return SecurityContextAssociation.getSecurityContext(); - } - }); - } else { - return SecurityContextAssociation.getSecurityContext(); - } - } - - /** - * Clears current {@code SecurityContext} - */ - static void clearSecurityContext() { - if (WildFlySecurityManager.isChecking()) { - WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - public Void run() { - SecurityContextAssociation.clearSecurityContext(); - return null; - } - }); - } else { - SecurityContextAssociation.clearSecurityContext(); - } - } - - static void setSecurityRoles(final Map> roles) { - if(WildFlySecurityManager.isChecking()) { - - WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - public Void run() { - SecurityRolesAssociation.setSecurityRoles(roles); - return null; - } - }); - } else { - SecurityRolesAssociation.setSecurityRoles(roles); - } - } - - /** - * Sets the run as identity - * - * @param principal the identity - */ - static RunAs setRunAsIdentity(final RunAs principal, final SecurityContext sc) { - if (WildFlySecurityManager.isChecking()) { - return WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - - @Override - public RunAs run() { - if (sc == null) { - throw UndertowLogger.ROOT_LOGGER.noSecurityContext(); - } - RunAs old = sc.getOutgoingRunAs(); - sc.setOutgoingRunAs(principal); - return old; - } - }); - } else { - if (sc == null) { - throw UndertowLogger.ROOT_LOGGER.noSecurityContext(); - } - RunAs old = sc.getOutgoingRunAs(); - sc.setOutgoingRunAs(principal); - return old; - } - } - - /** - * Removes the run as identity - * - * @return the identity removed - */ - static RunAs popRunAsIdentity(final SecurityContext sc) { - if (WildFlySecurityManager.isChecking()) { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public RunAs run() { - if (sc == null) { - throw UndertowLogger.ROOT_LOGGER.noSecurityContext(); - } - RunAs principal = sc.getOutgoingRunAs(); - sc.setOutgoingRunAs(null); - return principal; - } - }); - } else { - if (sc == null) { - throw UndertowLogger.ROOT_LOGGER.noSecurityContext(); - } - RunAs principal = sc.getOutgoingRunAs(); - sc.setOutgoingRunAs(null); - return principal; - } - } - - public static RunAs getRunAsIdentity(final SecurityContext sc) { - if (WildFlySecurityManager.isChecking()) { - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public RunAs run() { - if (sc == null) { - throw UndertowLogger.ROOT_LOGGER.noSecurityContext(); - } - return sc.getOutgoingRunAs(); - } - }); - } else { - if (sc == null) { - throw UndertowLogger.ROOT_LOGGER.noSecurityContext(); - } - return sc.getOutgoingRunAs(); - } - } - static Subject getSubject() { - if (WildFlySecurityManager.isChecking()) { - return doPrivileged(new PrivilegedAction() { - public Subject run() { - Subject subject = null; - SecurityContext sc = getSecurityContext(); - if (sc != null) { - subject = sc.getUtil().getSubject(); - } - return subject; - } - }); - } else { - Subject subject = null; - SecurityContext sc = getSecurityContext(); - if (sc != null) { - subject = sc.getUtil().getSubject(); - } - return subject; - } - } - - static boolean hasRole(AbstractWebAuthorizationHelper helper, String roleName, Principal principal, String servletName, Set principalRoles, String contextID, Subject callerSubject, List roles) { - if (WildFlySecurityManager.isChecking()) { - return doPrivileged(new PrivilegedAction() { - public Boolean run() { - return helper.hasRole(roleName, principal, servletName, principalRoles, contextID, callerSubject, roles); - } - }); - } else { - return helper.hasRole(roleName, principal, servletName, principalRoles, contextID, callerSubject, roles); - } - } - -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityContextAssociationHandler.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityContextAssociationHandler.java deleted file mode 100644 index abeb398601e6..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityContextAssociationHandler.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import io.undertow.predicate.Predicates; -import io.undertow.server.HandlerWrapper; -import io.undertow.server.HttpHandler; -import io.undertow.server.HttpServerExchange; -import io.undertow.server.handlers.PredicateHandler; -import io.undertow.servlet.handlers.ServletChain; -import io.undertow.servlet.handlers.ServletRequestContext; -import io.undertow.servlet.predicate.DispatcherTypePredicate; -import org.jboss.metadata.javaee.jboss.RunAsIdentityMetaData; -import org.jboss.security.RunAs; -import org.jboss.security.RunAsIdentity; -import org.jboss.security.SecurityContext; -import org.wildfly.extension.undertow.logging.UndertowLogger; - -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.Map; - -import javax.servlet.ServletRequest; - -public class SecurityContextAssociationHandler implements HttpHandler { - - private final Map runAsIdentityMetaDataMap; - private final HttpHandler next; - - private static final PrivilegedAction CURRENT_CONTEXT = new PrivilegedAction() { - @Override - public ServletRequestContext run() { - return ServletRequestContext.current(); - } - }; - - public SecurityContextAssociationHandler(final Map runAsIdentityMetaDataMap, final HttpHandler next) { - this.runAsIdentityMetaDataMap = runAsIdentityMetaDataMap; - this.next = next; - } - - @Override - public void handleRequest(final HttpServerExchange exchange) throws Exception { - SecurityContext sc = exchange.getAttachment(UndertowSecurityAttachments.SECURITY_CONTEXT_ATTACHMENT); - RunAsIdentityMetaData identity = null; - RunAs old = null; - try { - final ServletChain servlet = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getCurrentServlet(); - identity = runAsIdentityMetaDataMap.get(servlet.getManagedServlet().getServletInfo().getName()); - RunAsIdentity runAsIdentity = null; - if (identity != null) { - UndertowLogger.ROOT_LOGGER.tracef("%s, runAs: %s", servlet.getManagedServlet().getServletInfo().getName(), identity); - runAsIdentity = new RunAsIdentity(identity.getRoleName(), identity.getPrincipalName(), identity.getRunAsRoles()); - } - old = SecurityActions.setRunAsIdentity(runAsIdentity, sc); - - // Perform the request - next.handleRequest(exchange); - } finally { - if (identity != null) { - SecurityActions.setRunAsIdentity(old, sc); - } - } - } - - public static HandlerWrapper wrapper(final Map runAsIdentityMetaDataMap) { - return new HandlerWrapper() { - @Override - public HttpHandler wrap(final HttpHandler handler) { - //we only run this on REQUEST or ASYNC invocations - return new PredicateHandler(Predicates.or(DispatcherTypePredicate.REQUEST, DispatcherTypePredicate.ASYNC), new SecurityContextAssociationHandler(runAsIdentityMetaDataMap, handler), handler); - } - }; - } - - public static ServletRequest getActiveRequest() { - ServletRequestContext current; - if(System.getSecurityManager() == null) { - current = ServletRequestContext.current(); - } else { - current = AccessController.doPrivileged(CURRENT_CONTEXT); - } - if(current == null) { - return null; - } - return current.getServletRequest(); - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityContextThreadSetupAction.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityContextThreadSetupAction.java deleted file mode 100644 index 9e525018cce1..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/SecurityContextThreadSetupAction.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import java.security.PrivilegedAction; -import java.util.Map; -import java.util.Set; - -import org.jboss.as.security.plugins.SecurityDomainContext; -import org.jboss.security.SecurityContext; -import org.jboss.security.SecurityRolesAssociation; -import org.jboss.security.identity.RoleGroup; -import org.jboss.security.mapping.MappingContext; -import org.jboss.security.mapping.MappingManager; -import org.jboss.security.mapping.MappingType; -import org.wildfly.security.manager.WildFlySecurityManager; -import io.undertow.servlet.api.ThreadSetupHandler; - -/** - * Thread setup action that sets up the security context. If it already exists then it will be re-used, otherwise - * a new one is created. - * - * @author Stuart Douglas - */ -public class SecurityContextThreadSetupAction implements ThreadSetupHandler { - - private final String securityDomain; - private final SecurityDomainContext securityDomainContext; - private final Map> principleVsRoleMap; - - private static final PrivilegedAction TEAR_DOWN_PA = new PrivilegedAction() { - @Override - public Object run() { - SecurityActions.clearSecurityContext(); - SecurityRolesAssociation.setSecurityRoles(null); - return null; - } - }; - - public SecurityContextThreadSetupAction(final String securityDomain, SecurityDomainContext securityDomainContext, Map> principleVsRoleMap) { - this.securityDomain = securityDomain; - this.securityDomainContext = securityDomainContext; - this.principleVsRoleMap = principleVsRoleMap; - - } - - @Override - public Action create(Action action) { - return (exchange, context) -> { - SecurityContext sc = null; - if (exchange != null) { - sc = exchange.getAttachment(UndertowSecurityAttachments.SECURITY_CONTEXT_ATTACHMENT); - } - if (sc == null) { - sc = SecurityActions.createSecurityContext(securityDomain); - if (exchange != null) { - exchange.putAttachment(UndertowSecurityAttachments.SECURITY_CONTEXT_ATTACHMENT, sc); - } - } - SecurityActions.setSecurityContextOnAssociation(sc); - final MappingManager mappingManager = securityDomainContext.getMappingManager(); - - if (mappingManager != null) { - if (WildFlySecurityManager.isChecking()) { - WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - @Override - public Object run() { - // if there are mapping modules let them handle the role mapping - MappingContext mc = mappingManager.getMappingContext(MappingType.ROLE.name()); - if (mc != null && mc.hasModules()) { - SecurityRolesAssociation.setSecurityRoles(principleVsRoleMap); - } - return null; - } - }); - } else { - // if there are mapping modules let them handle the role mapping - MappingContext mc = mappingManager.getMappingContext(MappingType.ROLE.name()); - if (mc != null && mc.hasModules()) { - SecurityRolesAssociation.setSecurityRoles(principleVsRoleMap); - } - } - } - try { - return action.call(exchange, context); - } finally { - if (WildFlySecurityManager.isChecking()) { - WildFlySecurityManager.doUnchecked(TEAR_DOWN_PA); - } else { - SecurityActions.clearSecurityContext(); - SecurityRolesAssociation.setSecurityRoles(null); - } - } - }; - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/UndertowSecurityAttachments.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/UndertowSecurityAttachments.java deleted file mode 100644 index 1e1a88ab0495..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/UndertowSecurityAttachments.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security; - -import io.undertow.util.AttachmentKey; -import org.jboss.security.SecurityContext; - -/** - * @author Stuart Douglas - */ -public class UndertowSecurityAttachments { - - public static final AttachmentKey SECURITY_CONTEXT_ATTACHMENT = AttachmentKey.create(SecurityContext.class); - -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/jacc/HttpServletRequestPolicyContextHandler.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/jacc/HttpServletRequestPolicyContextHandler.java deleted file mode 100644 index 40132fc8bb29..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/jacc/HttpServletRequestPolicyContextHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security.jacc; - -import org.jboss.security.SecurityConstants; -import org.wildfly.extension.undertow.security.SecurityContextAssociationHandler; - -import javax.security.jacc.PolicyContextException; -import javax.security.jacc.PolicyContextHandler; - -/** - * A PolicyContextHandler for the active HttpServletRequest - * - * @author Scott.Stark@jboss.org - * @author Marcus Moyses - */ -public class HttpServletRequestPolicyContextHandler implements PolicyContextHandler { - - /** {@inheritDoc} */ - @Override - public Object getContext(String key, Object data) throws PolicyContextException { - if (!key.equalsIgnoreCase(SecurityConstants.WEB_REQUEST_KEY)) - return null; - return SecurityContextAssociationHandler.getActiveRequest(); - } - - /** {@inheritDoc} */ - @Override - public String[] getKeys() throws PolicyContextException { - String[] keys = { SecurityConstants.WEB_REQUEST_KEY }; - return keys; - } - - /** {@inheritDoc} */ - @Override - public boolean supports(String key) throws PolicyContextException { - return key.equalsIgnoreCase(SecurityConstants.WEB_REQUEST_KEY); - } -} \ No newline at end of file diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICAuthenticationMechanism.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICAuthenticationMechanism.java deleted file mode 100644 index 6a3b270fc9f2..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICAuthenticationMechanism.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.wildfly.extension.undertow.security.jaspi; - -import io.undertow.security.api.AuthenticatedSessionManager; -import io.undertow.security.api.AuthenticationMechanism; -import io.undertow.security.api.SecurityContext; -import io.undertow.security.idm.Account; -import io.undertow.server.HttpServerExchange; -import io.undertow.servlet.handlers.ServletRequestContext; -import io.undertow.servlet.handlers.security.ServletFormAuthenticationMechanism; -import io.undertow.util.AttachmentKey; - -import io.undertow.util.StatusCodes; -import org.jboss.security.SecurityConstants; -import org.jboss.security.SimpleGroup; -import org.jboss.security.SimplePrincipal; -import org.jboss.security.auth.callback.JBossCallbackHandler; -import org.jboss.security.auth.message.GenericMessageInfo; -import org.jboss.security.identity.plugins.SimpleRole; -import org.jboss.security.identity.plugins.SimpleRoleGroup; -import org.jboss.security.plugins.auth.JASPIServerAuthenticationManager; -import org.wildfly.extension.undertow.logging.UndertowLogger; -import org.wildfly.extension.undertow.security.AccountImpl; - -import javax.security.auth.Subject; -import javax.security.auth.message.AuthException; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import static org.jboss.security.SecurityConstants.ROLES_IDENTIFIER; - -import java.security.Principal; -import java.security.acl.Group; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.jboss.security.auth.callback.JASPICallbackHandler; -import org.jboss.security.identity.Role; -import org.jboss.security.identity.RoleGroup; -import org.wildfly.extension.undertow.security.UndertowSecurityAttachments; - -/** - *

- * {@link AuthenticationMechanism} implementation that enables JASPI-based authentication. - *

- * - * @author Pedro Igor - * @author Stefan Guilhen - */ -public class JASPICAuthenticationMechanism implements AuthenticationMechanism { - - - static final String JASPI_HTTP_SERVLET_LAYER = "HttpServlet"; - private static final String MECHANISM_NAME = "JASPIC"; - private static final String JASPI_AUTH_TYPE = "javax.servlet.http.authType"; - private static final String JASPI_REGISTER_SESSION = "javax.servlet.http.registerSession"; - - public static final AttachmentKey HTTP_SERVER_EXCHANGE_ATTACHMENT_KEY = AttachmentKey.create(HttpServerExchange.class); - public static final AttachmentKey SECURITY_CONTEXT_ATTACHMENT_KEY = AttachmentKey.create(SecurityContext.class); - - public static final AttachmentKey AUTH_RUN = AttachmentKey.create(Boolean.class); - public static final int DEFAULT_ERROR_CODE = StatusCodes.UNAUTHORIZED; - - private final String securityDomain; - private final String configuredAuthMethod; - - public JASPICAuthenticationMechanism(final String securityDomain, final String configuredAuthMethod) { - this.securityDomain = securityDomain; - this.configuredAuthMethod = configuredAuthMethod; - } - - @Override - public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext sc) { - exchange.putAttachment(AUTH_RUN, true); - final ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); - final JASPIServerAuthenticationManager sam = createJASPIAuthenticationManager(); - final GenericMessageInfo messageInfo = createMessageInfo(exchange, sc); - final String applicationIdentifier = buildApplicationIdentifier(requestContext); - final JASPICallbackHandler cbh = new JASPICallbackHandler(); - exchange.putAttachment(JASPICContext.ATTACHMENT_KEY, new JASPICContext(messageInfo, sam, cbh)); - UndertowLogger.ROOT_LOGGER.debugf("validateRequest for layer [%s] and applicationContextIdentifier [%s]", JASPI_HTTP_SERVLET_LAYER, applicationIdentifier); - - Account cachedAccount = null; - final JASPICSecurityContext jaspicSecurityContext = (JASPICSecurityContext) exchange.getSecurityContext(); - final AuthenticatedSessionManager sessionManager = exchange.getAttachment(AuthenticatedSessionManager.ATTACHMENT_KEY); - - if (sessionManager != null) { - AuthenticatedSessionManager.AuthenticatedSession authSession = sessionManager.lookupSession(exchange); - if(authSession != null) { - cachedAccount = authSession.getAccount(); - // if there is a cached account we set it in the security context so that the principal is available to - // SAM modules via request.getUserPrincipal(). - if (cachedAccount != null) { - jaspicSecurityContext.setCachedAuthenticatedAccount(cachedAccount); - } - } - } - - AuthenticationMechanismOutcome outcome = AuthenticationMechanismOutcome.NOT_AUTHENTICATED; - Account authenticatedAccount = null; - - boolean isValid = sam.isValid(messageInfo, new Subject(), JASPI_HTTP_SERVLET_LAYER, applicationIdentifier, cbh); - jaspicSecurityContext.setCachedAuthenticatedAccount(null); - - if (isValid) { - // The CBH filled in the JBOSS SecurityContext, we need to create an Undertow account based on that - org.jboss.security.SecurityContext jbossSct = SecurityActions.getSecurityContext(); - authenticatedAccount = createAccount(cachedAccount, jbossSct); - updateSubjectRoles(jbossSct); - } - - // authType resolution (check message info first, then check for the configured auth method, then use mech-specific name). - String authType = (String) messageInfo.getMap().get(JASPI_AUTH_TYPE); - if (authType == null) - authType = this.configuredAuthMethod != null ? this.configuredAuthMethod : MECHANISM_NAME; - - if (isValid && authenticatedAccount != null) { - outcome = AuthenticationMechanismOutcome.AUTHENTICATED; - - Object registerObj = messageInfo.getMap().get(JASPI_REGISTER_SESSION); - boolean cache = false; - if(registerObj != null && (registerObj instanceof String)) { - cache = Boolean.valueOf((String)registerObj); - } - sc.authenticationComplete(authenticatedAccount, authType, cache); - } else if (isValid && authenticatedAccount == null && !isMandatory(requestContext)) { - outcome = AuthenticationMechanismOutcome.NOT_ATTEMPTED; - } else { - outcome = AuthenticationMechanismOutcome.NOT_AUTHENTICATED; - sc.authenticationFailed("JASPIC authentication failed.", authType); - - // make sure we don't return status OK if the AuthException was thrown except for FORM authentication - if (wasAuthExceptionThrown(exchange) && !statusIndicatesError(exchange) && !isFormAuthentication(exchange)) { - exchange.setResponseCode(DEFAULT_ERROR_CODE); - } - } - - // A SAM can wrap the HTTP request/response objects - update the servlet request context with the values found in the message info. - ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); - servletRequestContext.setServletRequest((HttpServletRequest) messageInfo.getRequestMessage()); - servletRequestContext.setServletResponse((HttpServletResponse) messageInfo.getResponseMessage()); - - return outcome; - - } - - @Override - public ChallengeResult sendChallenge(final HttpServerExchange exchange, final SecurityContext securityContext) { - return new ChallengeResult(true); - } - - private JASPIServerAuthenticationManager createJASPIAuthenticationManager() { - return new JASPIServerAuthenticationManager(this.securityDomain, new JBossCallbackHandler()); - } - - static String buildApplicationIdentifier(final ServletRequestContext attachment) { - ServletRequest servletRequest = attachment.getServletRequest(); - return servletRequest.getServletContext().getVirtualServerName() + " " + servletRequest.getServletContext().getContextPath(); - } - - private GenericMessageInfo createMessageInfo(final HttpServerExchange exchange, final SecurityContext securityContext) { - ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); - - GenericMessageInfo messageInfo = new GenericMessageInfo(); - - messageInfo.setRequestMessage(servletRequestContext.getServletRequest()); - messageInfo.setResponseMessage(servletRequestContext.getServletResponse()); - - messageInfo.getMap().put("javax.security.auth.message.MessagePolicy.isMandatory", isMandatory(servletRequestContext).toString()); - - // additional context data, useful to provide access to Undertow resources during the modules processing - messageInfo.getMap().put(SECURITY_CONTEXT_ATTACHMENT_KEY, securityContext); - messageInfo.getMap().put(HTTP_SERVER_EXCHANGE_ATTACHMENT_KEY, exchange); - - return messageInfo; - } - - private void updateSubjectRoles(final org.jboss.security.SecurityContext jbossSct){ - if (jbossSct == null) { - throw UndertowLogger.ROOT_LOGGER.nullParamter("org.jboss.security.SecurityContext"); - } - - RoleGroup contextRoleGroup = jbossSct.getUtil().getRoles(); - - if(contextRoleGroup == null){ - return; - } - - Collection contextRoles = contextRoleGroup.getRoles(); - - if(contextRoles.isEmpty()){ - return; - } - - Subject subject = jbossSct.getUtil().getSubject(); - Set groupPrincipals = subject.getPrincipals(Group.class); - Group subjectRoleGroup = null; - - for (Group candidate : groupPrincipals) { - if (candidate.getName().equals(ROLES_IDENTIFIER)) { - subjectRoleGroup = candidate; - break; - } - } - if (subjectRoleGroup == null) { - subjectRoleGroup = new SimpleGroup(ROLES_IDENTIFIER); - subject.getPrincipals().add(subjectRoleGroup); - } - for (Role role : contextRoles) { - Principal rolePrincipal = new SimplePrincipal(role.getRoleName()); - subjectRoleGroup.addMember(rolePrincipal); - } - } - - private Account createAccount(final Account cachedAccount, final org.jboss.security.SecurityContext jbossSct) { - if (jbossSct == null) { - throw UndertowLogger.ROOT_LOGGER.nullParamter("org.jboss.security.SecurityContext"); - } - - // null principal: SAM has opted out of the authentication process. - Principal userPrincipal = jbossSct.getUtil().getUserPrincipal(); - if (userPrincipal == null) { - return null; - } - - // SAM handled the same principal found in the cached account: indicates we must use the cached account. - if (cachedAccount != null && cachedAccount.getPrincipal() == userPrincipal) { - // populate the security context using the cached account data. - jbossSct.getUtil().createSubjectInfo(userPrincipal, ((AccountImpl) cachedAccount).getCredential(), jbossSct.getUtil().getSubject()); - RoleGroup roleGroup = new SimpleRoleGroup(SecurityConstants.ROLES_IDENTIFIER); - for (String role : cachedAccount.getRoles()) - roleGroup.addRole(new SimpleRole(role)); - jbossSct.getUtil().setRoles(roleGroup); - return cachedAccount; - } - - // SAM handled a different principal or there is no cached account: build a new account. - Set stringRoles = new HashSet(); - RoleGroup roleGroup = jbossSct.getUtil().getRoles(); - if (roleGroup != null) { - for (Role role : roleGroup.getRoles()) { - stringRoles.add(role.getRoleName()); - } - } - Object credential = jbossSct.getUtil().getCredential(); - Principal original = null; - if(cachedAccount != null) { - original = cachedAccount.getPrincipal(); - } - return new AccountImpl(userPrincipal, stringRoles, credential, original); - } - - /** - *

The authentication is mandatory if the servlet has http constraints (eg.: {@link - * javax.servlet.annotation.HttpConstraint}).

- * - * @param attachment - * @return - */ - private Boolean isMandatory(final ServletRequestContext attachment) { - return attachment.getExchange().getSecurityContext() != null && attachment.getExchange().getSecurityContext().isAuthenticationRequired(); - } - - private boolean statusIndicatesError(HttpServerExchange exchange) { - return exchange.getResponseCode() != StatusCodes.OK; - } - - - static boolean wasAuthExceptionThrown(HttpServerExchange exchange) { - return exchange.getAttachment(UndertowSecurityAttachments.SECURITY_CONTEXT_ATTACHMENT).getData().get(AuthException.class.getName()) != null; - } - - static boolean isFormAuthentication(HttpServerExchange exchange) { - ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); - List mechanisms = src.getDeployment().getAuthenticationMechanisms(); - for (AuthenticationMechanism mech : mechanisms) { - if (mech instanceof ServletFormAuthenticationMechanism) return true; - } - return false; - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICContext.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICContext.java deleted file mode 100644 index b4f5ba04de16..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICContext.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security.jaspi; - -import io.undertow.util.AttachmentKey; -import org.jboss.security.auth.callback.JASPICallbackHandler; -import org.jboss.security.plugins.auth.JASPIServerAuthenticationManager; - -import javax.security.auth.message.MessageInfo; - -/** - * @author Stuart Douglas - */ -public class JASPICContext { - - public static final AttachmentKey ATTACHMENT_KEY = AttachmentKey.create(JASPICContext.class); - - private final MessageInfo messageInfo; - private final JASPIServerAuthenticationManager sam; - private final JASPICallbackHandler cbh; - - public JASPICContext(MessageInfo messageInfo, JASPIServerAuthenticationManager sam, JASPICallbackHandler cbh) { - this.messageInfo = messageInfo; - this.sam = sam; - this.cbh = cbh; - } - - public MessageInfo getMessageInfo() { - return messageInfo; - } - - public JASPIServerAuthenticationManager getSam() { - return sam; - } - - public JASPICallbackHandler getCbh() { - return cbh; - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecureResponseHandler.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecureResponseHandler.java deleted file mode 100644 index 60d531ee7b12..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecureResponseHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security.jaspi; - -import io.undertow.server.HttpHandler; -import io.undertow.server.HttpServerExchange; -import io.undertow.servlet.handlers.ServletRequestContext; -import org.wildfly.extension.undertow.logging.UndertowLogger; - -import javax.security.auth.Subject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Stuart Douglas - */ -public class JASPICSecureResponseHandler implements HttpHandler { - - private final HttpHandler next; - - public JASPICSecureResponseHandler(HttpHandler next) { - this.next = next; - } - - @Override - public void handleRequest(HttpServerExchange exchange) throws Exception { - try { - next.handleRequest(exchange); - } finally { - try { - JASPICContext context = exchange.getAttachment(JASPICContext.ATTACHMENT_KEY); - - if (!JASPICAuthenticationMechanism.wasAuthExceptionThrown(exchange) && context != null) { - ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); - String applicationIdentifier = JASPICAuthenticationMechanism.buildApplicationIdentifier(requestContext); - UndertowLogger.ROOT_LOGGER.debugf("secureResponse for layer [%s] and applicationContextIdentifier [%s].", JASPICAuthenticationMechanism.JASPI_HTTP_SERVLET_LAYER, applicationIdentifier); - context.getSam().secureResponse(context.getMessageInfo(), new Subject(), JASPICAuthenticationMechanism.JASPI_HTTP_SERVLET_LAYER, applicationIdentifier, context.getCbh()); - - // A SAM can unwrap the HTTP request/response objects - update the servlet request context with the values found in the message info. - ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); - servletRequestContext.setServletRequest((HttpServletRequest) context.getMessageInfo().getRequestMessage()); - servletRequestContext.setServletResponse((HttpServletResponse) context.getMessageInfo().getResponseMessage()); - } - } catch (Exception e) { - UndertowLogger.ROOT_LOGGER.errorInvokingSecureResponse(e); - } - } - } - -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecurityContext.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecurityContext.java deleted file mode 100644 index 6213779c6cbd..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecurityContext.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.wildfly.extension.undertow.security.jaspi; - -import static org.wildfly.extension.undertow.security.jaspi.SecurityActions.getAuthConfigFactory; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.message.MessageInfo; -import javax.security.auth.message.config.AuthConfigProvider; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; - -import io.undertow.security.api.AuthenticationMode; -import io.undertow.security.idm.Account; -import io.undertow.security.idm.IdentityManager; -import io.undertow.security.impl.SecurityContextImpl; -import io.undertow.server.HttpServerExchange; -import io.undertow.servlet.handlers.ServletRequestContext; -import org.jboss.security.auth.callback.JASPICallbackHandler; -import org.jboss.security.auth.callback.JBossCallbackHandler; -import org.jboss.security.auth.message.GenericMessageInfo; -import org.jboss.security.plugins.auth.JASPIServerAuthenticationManager; - -/** - *

- * A {@link io.undertow.security.api.SecurityContext} that implements the {@code login} and {@code logout} methods - * according to the Jakarta Authentication 1.1 specification. - *

- * - * @author Stefan Guilhen - */ -class JASPICSecurityContext extends SecurityContextImpl { - - private static final String layer = "HttpServlet"; - private static final CallbackHandler handler = new JASPICallbackHandler(); - - private final HttpServerExchange exchange; - private final JASPIServerAuthenticationManager manager; - private Account cachedAuthenticatedAccount; - - public JASPICSecurityContext(final HttpServerExchange exchange, final AuthenticationMode mode, final IdentityManager identityManager, - final String securityDomain) { - super (exchange, mode, identityManager); - this.exchange = exchange; - this.manager = new JASPIServerAuthenticationManager(securityDomain, new JBossCallbackHandler()); - } - - /** - *

- * Jakarta Authentication 1.1 specification: if there is an {@code AuthConfigProvider} for the {@code HttpServlet} layer and - * application context, then @{@code login} must throw a {@code ServletException} which may convey that the - * exception was caused by an incompatibility between the {@code login} method and the configured authentication - * mechanism. If there is no such provider, then the container must proceed with the regular {@code login} processing. - *

- * - * @param username The username - * @param password The password - * @return true if the login succeeded, false otherwise - * @throws SecurityException if login is called when Jakarta Authentication is enabled for application context and layer. - */ - @Override - public boolean login(final String username, final String password) { - // if there is an AuthConfigProvider for the HttpServlet layer and appContext, this method must throw an exception. - String appContext = this.buildAppContext(); - AuthConfigProvider provider = getAuthConfigFactory().getConfigProvider(layer, appContext, null); - if (provider != null) { - ServletException se = new ServletException("login is not supported by the Jakarta Authentication mechanism"); - throw new SecurityException(se); - } - return super.login(username, password); - } - - /** - *

- * Jakarta Authentication 1.1 specification: if there is an {@code AuthConfigProvider} for the {@code HttpServlet} layer and - * application context, then @{@code logout} must acquire a {@code ServerAuthContext} and call {@code cleanSubject} - * on the acquired context. - *

- *

- * The specified {@code Subject} should be non-null and should be the {@code Subject} returning from the most recent - * call to {@code validateRequest}. In our case, that {@code Subject} is set in the underlying security context, so - * we must retrieve it from there before calling {@code cleanSubject}. - *

- *

- * Once {@code cleanSubject} returns, {@code logout} must perform the regular (non-Jakarta Authentication) {@code logout} processing. - *

- */ - @Override - public void logout() { - if (!isAuthenticated()) - return; - - // call cleanSubject() if there is an AuthConfigProvider for the HttpServlet layer and appContext. - String appContext = this.buildAppContext(); - if (getAuthConfigFactory().getConfigProvider(layer, appContext, null) != null) { - Subject authenticatedSubject = this.getAuthenticatedSubject(); - MessageInfo messageInfo = this.buildMessageInfo(); - this.manager.cleanSubject(messageInfo, authenticatedSubject, layer, appContext, handler); - } - - // following the return from cleanSubject(), logout must perform the regular logout processing. - super.logout(); - } - - /** - *

- * Overrides the parent method to return the cached authenticated account (that is, the account that was set in the - * session as a result of a SAM setting the {@code javax.servlet.http.registerSession} property) when the regular - * account is null. This allows a SAM to retrieve the cached account principal by calling {@code getUserPrincipal()} - * on {@code HttpServletRequest}. - *

- * - * @return the authenticated account (or cached account when it is null). - */ - @Override - public Account getAuthenticatedAccount() { - Account account = super.getAuthenticatedAccount(); - if (account == null) - account = this.cachedAuthenticatedAccount; - return account; - } - - /** - *

- * Sets the cached authenticated account. This is set by the Jakarta Authentication mechanism when it detects an existing account - * in the session. - *

- * - * @param account the cached authenticated account. - */ - public void setCachedAuthenticatedAccount(final Account account) { - this.cachedAuthenticatedAccount = account; - } - - /** - *

- * Builds the Jakarta Authentication application context. - *

- * - * @return a {@code String} representing the application context. - */ - private String buildAppContext() { - final ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); - ServletRequest servletRequest = requestContext.getServletRequest(); - return servletRequest.getServletContext().getVirtualServerName() + " " + servletRequest.getServletContext().getContextPath(); - } - - /** - *

- * Builds the {@code MessageInfo} instance for the {@code cleanSubject()} call. - *

- * - * @return the constructed {@code MessageInfo} object. - */ - private MessageInfo buildMessageInfo() { - ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); - GenericMessageInfo messageInfo = new GenericMessageInfo(); - messageInfo.setRequestMessage(servletRequestContext.getServletRequest()); - messageInfo.setResponseMessage(servletRequestContext.getServletResponse()); - // when calling cleanSubject, isMandatory must be set to true. - messageInfo.getMap().put("javax.security.auth.message.MessagePolicy.isMandatory", "true"); - return messageInfo; - - } - - /** - *

- * Retrieves the authenticated subject from the underlying security context. - *

- * - * @return a reference to the authenticated subject. - */ - private Subject getAuthenticatedSubject() { - Subject subject = null; - org.jboss.security.SecurityContext picketBoxContext = SecurityActions.getSecurityContext(); - if (picketBoxContext != null && picketBoxContext.getSubjectInfo() != null) - subject = picketBoxContext.getSubjectInfo().getAuthenticatedSubject(); - return subject != null ? subject : new Subject(); - } - - -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecurityContextFactory.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecurityContextFactory.java deleted file mode 100644 index 6fff967fd475..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/JASPICSecurityContextFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.wildfly.extension.undertow.security.jaspi; - -import io.undertow.security.api.AuthenticationMode; -import io.undertow.security.api.SecurityContext; -import io.undertow.security.api.SecurityContextFactory; -import io.undertow.security.idm.IdentityManager; -import io.undertow.server.HttpServerExchange; - -/** - *

- * A {@link io.undertow.security.api.SecurityContextFactory} implementation that creates {@link JASPICSecurityContext} - * instances. - *

- */ -public class JASPICSecurityContextFactory implements SecurityContextFactory { - - private final String securityDomain; - - /** - *

- * Creates an instance of {@code JASPICSecurityContextFactory} with the specified security domain. - *

- * - * @param securityDomain the security domain that is to be set in all created {@link JASPICSecurityContext} instances. - */ - public JASPICSecurityContextFactory(final String securityDomain) { - this.securityDomain = securityDomain; - } - - @Override - public SecurityContext createSecurityContext(final HttpServerExchange exchange, final AuthenticationMode mode, - final IdentityManager identityManager, final String programmaticMechName) { - JASPICSecurityContext context = new JASPICSecurityContext(exchange, mode, identityManager, this.securityDomain); - if (programmaticMechName != null) - context.setProgramaticMechName(programmaticMechName); - return context; - } -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/SecurityActions.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/SecurityActions.java deleted file mode 100644 index 979b90d7005a..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/SecurityActions.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security.jaspi; - -import static java.security.AccessController.doPrivileged; -import java.security.PrivilegedAction; - -import javax.security.auth.message.config.AuthConfigFactory; - -import org.jboss.security.SecurityContext; -import org.jboss.security.SecurityContextAssociation; -import org.wildfly.security.manager.WildFlySecurityManager; - -/** - * Privileged Actions - * - * @author Anil.Saldhana@redhat.com - * @since Jan 12, 2011 - */ -class SecurityActions { - - private static final PrivilegedAction GET_AUTH_CONFIG_FACTORY_ACTION = new PrivilegedAction() { - - @Override - public AuthConfigFactory run() { - return AuthConfigFactory.getFactory(); - } - - }; - - static AuthConfigFactory getAuthConfigFactory() { - return WildFlySecurityManager.isChecking() ? doPrivileged(GET_AUTH_CONFIG_FACTORY_ACTION) : GET_AUTH_CONFIG_FACTORY_ACTION.run(); - } - - /** - * Get the current {@code SecurityContext} - * - * @return an instance of {@code SecurityContext} - */ - public static SecurityContext getSecurityContext() { - if (WildFlySecurityManager.isChecking()) { - return WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - @Override - public SecurityContext run() { - return SecurityContextAssociation.getSecurityContext(); - } - }); - } else { - return SecurityContextAssociation.getSecurityContext(); - } - } - -} diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/modules/HTTPSchemeServerAuthModule.java b/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/modules/HTTPSchemeServerAuthModule.java deleted file mode 100644 index bcca0fb6ef55..000000000000 --- a/undertow/src/main/java/org/wildfly/extension/undertow/security/jaspi/modules/HTTPSchemeServerAuthModule.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.extension.undertow.security.jaspi.modules; - -import io.undertow.security.api.AuthenticationMechanism; -import io.undertow.security.api.SecurityContext; -import io.undertow.server.HttpServerExchange; -import io.undertow.servlet.handlers.ServletRequestContext; -import org.wildfly.extension.undertow.logging.UndertowLogger; -import org.wildfly.extension.undertow.security.jaspi.JASPICAuthenticationMechanism; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.message.AuthException; -import javax.security.auth.message.AuthStatus; -import javax.security.auth.message.MessageInfo; -import javax.security.auth.message.MessagePolicy; -import javax.security.auth.message.module.ServerAuthModule; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.List; -import java.util.Map; - -import static io.undertow.security.api.AuthenticationMechanism.AuthenticationMechanismOutcome.AUTHENTICATED; -import static io.undertow.security.api.AuthenticationMechanism.AuthenticationMechanismOutcome.NOT_AUTHENTICATED; -import static javax.security.auth.message.AuthStatus.SEND_CONTINUE; -import static javax.security.auth.message.AuthStatus.SUCCESS; - -/** - *

This class implements a JASPI {@code ServerAuthModule} that handles the standards HTTP Authentication - * Schemes.

- * - * @author Pedro Igor - */ -public class HTTPSchemeServerAuthModule implements ServerAuthModule { - - private final String securityDomain; - private AuthenticationMechanism authenticationMechanism; - - public HTTPSchemeServerAuthModule(String securityDomain) { - this.securityDomain = securityDomain; - } - - @Override - public void initialize(final MessagePolicy messagePolicy, final MessagePolicy messagePolicy2, final CallbackHandler callbackHandler, final Map map) throws AuthException { - } - - @Override - public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) - throws AuthException { - // do nothing, just return SUCCESS. - return SUCCESS; - } - - @Override - public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) - throws AuthException { - HttpServerExchange exchange = (HttpServerExchange) messageInfo.getMap().get(JASPICAuthenticationMechanism.HTTP_SERVER_EXCHANGE_ATTACHMENT_KEY); - SecurityContext securityContext = (SecurityContext) messageInfo.getMap().get(JASPICAuthenticationMechanism.SECURITY_CONTEXT_ATTACHMENT_KEY); - ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); - List mechanisms = src.getDeployment().getAuthenticationMechanisms(); - - try { - boolean success = false; - for (AuthenticationMechanism mechanism : mechanisms) { - AuthenticationMechanism.AuthenticationMechanismOutcome result = mechanism.authenticate(exchange, securityContext); - if (result == AUTHENTICATED) { - success = true; - break; - } else if (result == NOT_AUTHENTICATED) { - break; - } - } - - if (!success) { - String mandatory = (String) messageInfo.getMap().get("javax.security.auth.message.MessagePolicy.isMandatory"); - if(mandatory != null && mandatory.toLowerCase().equals("false")) { - return SUCCESS; - } else { - for (AuthenticationMechanism mechanism : mechanisms) { - AuthenticationMechanism.ChallengeResult challengeResult = mechanism.sendChallenge(exchange, securityContext); - if (challengeResult.getDesiredResponseCode() != null) { - exchange.setResponseCode(challengeResult.getDesiredResponseCode()); - } - if (exchange.isResponseComplete()) { - break; - } - } - return SEND_CONTINUE; - } - } - } catch (Exception e) { - UndertowLogger.ROOT_LOGGER.debug(e); - throw new AuthException("Could not validateRequest using mechanisms [" + mechanisms + "."); - } - - return SUCCESS; - } - - @Override - public Class[] getSupportedMessageTypes() { - return new Class[]{ServletRequest.class, ServletResponse.class, - HttpServletRequest.class, HttpServletResponse.class}; - } - - @Override - public void cleanSubject(final MessageInfo messageInfo, final Subject subject) throws AuthException { - //TODO: is necessary to clean the subject here ? - } -} From 9f3f203dbd9b5c23e52d4a13ce195b37d3980890 Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Tue, 23 Nov 2021 19:29:53 +0000 Subject: [PATCH 04/11] [WFLY-15732] / [WFLY-15356] Remove the legacy mechanism SSO integration. --- .../sso/AuthenticatedSessionExternalizer.java | 83 ------ .../sso/AuthenticatedSessionMarshaller.java | 116 -------- .../sso/DistributableSingleSignOn.java | 274 ----------------- .../sso/DistributableSingleSignOnManager.java | 116 -------- ...ingleSignOnManagerServiceConfigurator.java | 146 --------- .../sso/InvalidatableSingleSignOn.java | 32 -- ...SessionIdGeneratorServiceConfigurator.java | 80 ----- .../SessionListenerServiceConfigurator.java | 100 ------- .../undertow/sso/SessionManagerRegistry.java | 37 --- ...ionManagerRegistryServiceConfigurator.java | 137 --------- ...curitySerializationContextInitializer.java | 44 --- ...ndertowSingleSignOnManagementProvider.java | 59 ---- ...tributableSingleSignOnManagerTestCase.java | 146 --------- .../DistributableSingleSignOnTestCase.java | 281 ------------------ .../UndertowSecurityMarshallingTestCase.java | 70 ----- 15 files changed, 1721 deletions(-) delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/AuthenticatedSessionExternalizer.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/AuthenticatedSessionMarshaller.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOn.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManager.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManagerServiceConfigurator.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/InvalidatableSingleSignOn.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionIdGeneratorServiceConfigurator.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionListenerServiceConfigurator.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionManagerRegistry.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionManagerRegistryServiceConfigurator.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/UndertowSecuritySerializationContextInitializer.java delete mode 100644 clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/UndertowSingleSignOnManagementProvider.java delete mode 100644 clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManagerTestCase.java delete mode 100644 clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnTestCase.java delete mode 100644 clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/UndertowSecurityMarshallingTestCase.java diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/AuthenticatedSessionExternalizer.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/AuthenticatedSessionExternalizer.java deleted file mode 100644 index fa59667c6cc4..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/AuthenticatedSessionExternalizer.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2020, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; -import java.security.Principal; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -import org.kohsuke.MetaInfServices; -import org.wildfly.clustering.marshalling.Externalizer; -import org.wildfly.clustering.marshalling.spi.IndexSerializer; -import org.wildfly.extension.undertow.security.AccountImpl; - -import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; -import io.undertow.security.idm.Account; - -/** - * Externalizer for an {@link AuthenticatedSession}. - * @author Paul Ferraro - */ -@MetaInfServices(Externalizer.class) -public class AuthenticatedSessionExternalizer implements Externalizer { - - @Override - public void writeObject(ObjectOutput output, AuthenticatedSession session) throws IOException { - AccountImpl account = (AccountImpl) session.getAccount(); - output.writeUTF(session.getMechanism()); - output.writeUTF(account.getPrincipal().getName()); - Set roles = account.getRoles(); - IndexSerializer.VARIABLE.writeInt(output, roles.size()); - for (String role : roles) { - output.writeUTF(role); - } - output.writeObject(account.getCredential()); - Principal original = account.getOriginalPrincipal(); - output.writeUTF((original != null) ? original.getName() : null); - } - - @Override - public AuthenticatedSession readObject(ObjectInput input) throws IOException, ClassNotFoundException { - String mechanism = input.readUTF(); - Principal principal = new AccountImpl(input.readUTF()).getPrincipal(); - int roleCount = IndexSerializer.VARIABLE.readInt(input); - List roles = new ArrayList<>(roleCount); - for (int i = 0; i < roleCount; ++i) { - roles.add(input.readUTF()); - } - Object credential = input.readObject(); - Principal original = new AccountImpl(input.readUTF()).getPrincipal(); - Account account = new AccountImpl(principal, new CopyOnWriteArraySet<>(roles), credential, original); - return new AuthenticatedSession(account, mechanism); - } - - @Override - public Class getTargetClass() { - return AuthenticatedSession.class; - } -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/AuthenticatedSessionMarshaller.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/AuthenticatedSessionMarshaller.java deleted file mode 100644 index 1dc085a66bff..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/AuthenticatedSessionMarshaller.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2021, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import java.io.IOException; -import java.security.Principal; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.CopyOnWriteArraySet; - -import javax.servlet.http.HttpServletRequest; - -import org.infinispan.protostream.descriptors.WireType; -import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller; -import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader; -import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter; -import org.wildfly.extension.undertow.security.AccountImpl; - -import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; -import io.undertow.security.idm.Account; - -/** - * @author Paul Ferraro - */ -public class AuthenticatedSessionMarshaller implements ProtoStreamMarshaller { - - private static final int MECHANISM_INDEX = 1; - private static final int PRINCIPAL_INDEX = 2; - private static final int ROLE_INDEX = 3; - private static final int CREDENTIAL_INDEX = 4; - private static final int ORIGINAL_INDEX = 5; - - private static final String DEFAULT_MECHANISM = HttpServletRequest.FORM_AUTH; - - @Override - public AuthenticatedSession readFrom(ProtoStreamReader reader) throws IOException { - String mechanism = DEFAULT_MECHANISM; - Principal principal = null; - List roles = new LinkedList<>(); - Object credential = null; - Principal original = null; - while (!reader.isAtEnd()) { - int tag = reader.readTag(); - switch (WireType.getTagFieldNumber(tag)) { - case MECHANISM_INDEX: - mechanism = reader.readString(); - break; - case PRINCIPAL_INDEX: - principal = new AccountImpl(reader.readString()).getPrincipal(); - break; - case ROLE_INDEX: - roles.add(reader.readString()); - break; - case CREDENTIAL_INDEX: - credential = reader.readAny(); - break; - case ORIGINAL_INDEX: - original = new AccountImpl(reader.readString()).getPrincipal(); - break; - default: - reader.skipField(tag); - } - } - Account account = new AccountImpl(principal, new CopyOnWriteArraySet<>(roles), credential, original); - return new AuthenticatedSession(account, mechanism); - } - - @Override - public void writeTo(ProtoStreamWriter writer, AuthenticatedSession auth) throws IOException { - String mechanism = auth.getMechanism(); - if (!mechanism.equals(DEFAULT_MECHANISM)) { - writer.writeString(MECHANISM_INDEX, mechanism); - } - AccountImpl account = (AccountImpl) auth.getAccount(); - Principal principal = account.getPrincipal(); - if (principal != null) { - writer.writeString(PRINCIPAL_INDEX, principal.getName()); - } - for (String role : account.getRoles()) { - writer.writeString(ROLE_INDEX, role); - } - Object credential = account.getCredential(); - if (credential != null) { - writer.writeAny(CREDENTIAL_INDEX, credential); - } - Principal original = account.getOriginalPrincipal(); - if (original != null) { - writer.writeString(ORIGINAL_INDEX, original.getName()); - } - } - - @Override - public Class getJavaClass() { - return AuthenticatedSession.class; - } -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOn.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOn.java deleted file mode 100644 index 509b2f58bd9f..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOn.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.wildfly.clustering.web.undertow.sso; - -import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; -import io.undertow.security.idm.Account; -import io.undertow.security.impl.SingleSignOn; -import io.undertow.server.HttpServerExchange; -import io.undertow.server.session.Session; -import io.undertow.server.session.SessionConfig; -import io.undertow.server.session.SessionManager; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.jboss.logging.Logger; -import org.wildfly.clustering.ee.Batch; -import org.wildfly.clustering.ee.BatchContext; -import org.wildfly.clustering.ee.Batcher; -import org.wildfly.clustering.web.sso.SSO; -import org.wildfly.clustering.web.sso.Sessions; - -/** - * Adapts an {@link SSO} to a {@link SingleSignOn}. - * @author Paul Ferraro - */ -public class DistributableSingleSignOn implements InvalidatableSingleSignOn { - - static final Logger LOGGER = Logger.getLogger(DistributableSingleSignOn.class); - - private final SSO sso; - private final SessionManagerRegistry registry; - private final Batcher batcher; - private final Batch batch; - private final AtomicBoolean closed = new AtomicBoolean(false); - - public DistributableSingleSignOn(SSO sso, SessionManagerRegistry registry, Batcher batcher, Batch batch) { - this.sso = sso; - this.registry = registry; - this.batcher = batcher; - this.batch = batch; - } - - @Override - public String getId() { - return this.sso.getId(); - } - - @Override - public Account getAccount() { - try (BatchContext context = this.batcher.resumeBatch(this.batch)) { - return this.sso.getAuthentication().getAccount(); - } - } - - @Override - public String getMechanismName() { - try (BatchContext context = this.batcher.resumeBatch(this.batch)) { - return this.sso.getAuthentication().getMechanism(); - } - } - - @Override - public Iterator iterator() { - try (BatchContext context = this.batcher.resumeBatch(this.batch)) { - Sessions sessions = this.sso.getSessions(); - Set deployments = sessions.getDeployments(); - List result = new ArrayList<>(deployments.size()); - for (String deployment : sessions.getDeployments()) { - String sessionId = sessions.getSession(deployment); - if (sessionId != null) { - SessionManager manager = this.registry.getSessionManager(deployment); - if (manager != null) { - result.add(new InvalidatableSession(manager, sessionId)); - } - } - } - return result.iterator(); - } - } - - @Override - public boolean contains(Session session) { - try (BatchContext context = this.batcher.resumeBatch(this.batch)) { - return this.sso.getSessions().getDeployments().contains(session.getSessionManager().getDeploymentName()); - } - } - - @Override - public void add(Session session) { - try (BatchContext context = this.batcher.resumeBatch(this.batch)) { - if (LOGGER.isTraceEnabled()) { - LOGGER.tracef("Adding Session ID %s to SSO session %s.", session.getId(), this.sso.getId()); - } - this.sso.getSessions().addSession(session.getSessionManager().getDeploymentName(), session.getId()); - } - } - - @Override - public void remove(Session session) { - try (BatchContext context = this.batcher.resumeBatch(this.batch)) { - if (LOGGER.isTraceEnabled()) { - LOGGER.tracef("Removing SSO ID %s from deployment %s.", this.sso.getId(), session.getSessionManager().getDeploymentName()); - } - this.sso.getSessions().removeSession(session.getSessionManager().getDeploymentName()); - } - } - - @Override - public Session getSession(SessionManager manager) { - try (BatchContext context = this.batcher.resumeBatch(this.batch)) { - String sessionId = this.sso.getSessions().getSession(manager.getDeploymentName()); - return (sessionId != null) ? new InvalidatableSession(manager, sessionId) : null; - } - } - - @Override - public void close() { - if (this.closed.compareAndSet(false, true)) { - try (BatchContext context = this.batcher.resumeBatch(this.batch)) { - this.batch.close(); - } - } - } - - @Override - public void invalidate() { - // The batch associated with this SSO might not be valid (e.g. in the case of logout). - try (BatchContext context = this.closed.compareAndSet(false, true) ? this.batcher.resumeBatch(this.batch) : null) { - try (Batch batch = (context != null) ? this.batch : this.batcher.createBatch()) { - if (LOGGER.isTraceEnabled()) { - LOGGER.tracef("Invalidating SSO ID %s.", this.sso.getId()); - } - this.sso.invalidate(); - } - } - } - - private static class InvalidatableSession implements Session { - private final SessionManager manager; - private final String sessionId; - - InvalidatableSession(SessionManager manager, String sessionId) { - this.manager = manager; - this.sessionId = sessionId; - } - - @Override - public String getId() { - return this.sessionId; - } - - @Override - public SessionManager getSessionManager() { - return this.manager; - } - - @Override - public void invalidate(HttpServerExchange exchange) { - Session session = this.manager.getSession(exchange, new SimpleSessionConfig(this.sessionId)); - if (session != null) { - if (LOGGER.isTraceEnabled()) { - LOGGER.tracef("Invalidating Session ID %s.", session.getId()); - } - session.invalidate(exchange); - } - } - - @Override - public String changeSessionId(HttpServerExchange exchange, SessionConfig config) { - throw new UnsupportedOperationException(); - } - - @Override - public Object getAttribute(String name) { - throw new UnsupportedOperationException(); - } - - @Override - public Set getAttributeNames() { - throw new UnsupportedOperationException(); - } - - @Override - public long getCreationTime() { - throw new UnsupportedOperationException(); - } - - @Override - public long getLastAccessedTime() { - throw new UnsupportedOperationException(); - } - - @Override - public int getMaxInactiveInterval() { - throw new UnsupportedOperationException(); - } - - @Override - public Object removeAttribute(String name) { - throw new UnsupportedOperationException(); - } - - @Override - public void requestDone(HttpServerExchange exchange) { - throw new UnsupportedOperationException(); - } - - @Override - public Object setAttribute(String name, Object value) { - throw new UnsupportedOperationException(); - } - - @Override - public void setMaxInactiveInterval(int interval) { - throw new UnsupportedOperationException(); - } - } - - private static class SimpleSessionConfig implements SessionConfig { - private final String id; - - SimpleSessionConfig(String id) { - this.id = id; - } - - @Override - public String findSessionId(HttpServerExchange exchange) { - return this.id; - } - - @Override - public void setSessionId(HttpServerExchange exchange, String sessionId) { - throw new UnsupportedOperationException(); - } - - @Override - public void clearSession(HttpServerExchange exchange, String sessionId) { - throw new UnsupportedOperationException(); - } - - @Override - public SessionCookieSource sessionCookieSource(HttpServerExchange exchange) { - throw new UnsupportedOperationException(); - } - - @Override - public String rewriteUrl(String originalUrl, String sessionId) { - throw new UnsupportedOperationException(); - } - } -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManager.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManager.java deleted file mode 100644 index a846767b6219..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManager.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.wildfly.clustering.web.undertow.sso; - -import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; -import io.undertow.security.idm.Account; -import io.undertow.security.impl.SingleSignOn; -import io.undertow.security.impl.SingleSignOnManager; - -import java.util.Base64; - -import org.jboss.logging.Logger; -import org.wildfly.clustering.ee.Batch; -import org.wildfly.clustering.ee.Batcher; -import org.wildfly.clustering.web.sso.SSO; -import org.wildfly.clustering.web.sso.SSOManager; - -/** - * Adapts an {@link SSOManager} to a {@link SingleSignOnManager}. - * @author Paul Ferraro - */ -public class DistributableSingleSignOnManager implements SingleSignOnManager { - - private static final Logger log = Logger.getLogger(DistributableSingleSignOnManager.class); - - private final SSOManager manager; - private final SessionManagerRegistry registry; - - public DistributableSingleSignOnManager(SSOManager manager, SessionManagerRegistry registry) { - this.manager = manager; - this.registry = registry; - } - - @Override - public SingleSignOn createSingleSignOn(Account account, String mechanism) { - String id = this.manager.getIdentifierFactory().get(); - Batcher batcher = this.manager.getBatcher(); - // Batch will be closed when SSO is closed - @SuppressWarnings("resource") - Batch batch = batcher.createBatch(); - try { - AuthenticatedSession session = new AuthenticatedSession(account, mechanism); - SSO sso = this.manager.createSSO(id, session); - if (log.isTraceEnabled()) { - log.tracef("Creating SSO ID %s for Principal %s and Roles %s", id, account.getPrincipal().getName(), account.getRoles().toString()); - } - return new DistributableSingleSignOn(sso, this.registry, batcher, batcher.suspendBatch()); - } catch (RuntimeException | Error e) { - batch.discard(); - batch.close(); - throw e; - } - } - - @Override - public SingleSignOn findSingleSignOn(String id) { - // If requested id contains invalid characters, then sso cannot exist and would otherwise cause sso lookup to fail - try { - Base64.getUrlDecoder().decode(id); - } catch (IllegalArgumentException e) { - return null; - } - - Batcher batcher = this.manager.getBatcher(); - // Batch will be closed when SSO is closed - @SuppressWarnings("resource") - Batch batch = batcher.createBatch(); - try { - SSO sso = this.manager.findSSO(id); - if (sso == null) { - if (log.isTraceEnabled()) { - log.tracef("SSO ID %s not found on the session manager.", id); - } - batch.close(); - return null; - } - if (log.isTraceEnabled()) { - log.tracef("SSO ID %s found on the session manager.", id); - } - return new DistributableSingleSignOn(sso, this.registry, batcher, batcher.suspendBatch()); - } catch (RuntimeException | Error e) { - batch.discard(); - batch.close(); - throw e; - } - } - - @Override - public void removeSingleSignOn(SingleSignOn sso) { - if (sso instanceof InvalidatableSingleSignOn) { - if(log.isTraceEnabled()) { - log.tracef("Removing SSO ID %s", sso.getId()); - } - ((InvalidatableSingleSignOn) sso).invalidate(); - } - } -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManagerServiceConfigurator.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManagerServiceConfigurator.java deleted file mode 100644 index 326ea92490c3..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManagerServiceConfigurator.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; -import org.jboss.as.controller.OperationContext; -import org.jboss.as.controller.capability.CapabilityServiceSupport; -import org.jboss.msc.Service; -import org.jboss.msc.service.ServiceBuilder; -import org.jboss.msc.service.ServiceController; -import org.jboss.msc.service.ServiceName; -import org.jboss.msc.service.ServiceTarget; -import org.wildfly.clustering.ee.Batch; -import org.wildfly.clustering.service.CascadeRemovalLifecycleListener; -import org.wildfly.clustering.service.ChildTargetService; -import org.wildfly.clustering.service.CompositeDependency; -import org.wildfly.clustering.service.FunctionalService; -import org.wildfly.clustering.service.ServiceConfigurator; -import org.wildfly.clustering.service.ServiceSupplierDependency; -import org.wildfly.clustering.service.SimpleServiceNameProvider; -import org.wildfly.clustering.service.SimpleSupplierDependency; -import org.wildfly.clustering.service.SupplierDependency; -import org.wildfly.clustering.web.WebDefaultProviderRequirement; -import org.wildfly.clustering.web.WebProviderRequirement; -import org.wildfly.clustering.web.container.HostSingleSignOnManagementConfiguration; -import org.wildfly.clustering.web.sso.DistributableSSOManagementProvider; -import org.wildfly.clustering.web.sso.LegacySSOManagementProviderFactory; -import org.wildfly.clustering.web.sso.SSOManager; -import org.wildfly.clustering.web.sso.SSOManagerFactory; -import org.wildfly.clustering.web.undertow.UndertowBinaryRequirement; -import org.wildfly.clustering.web.undertow.logging.UndertowClusteringLogger; - -import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; -import io.undertow.security.impl.SingleSignOnManager; -import io.undertow.server.session.SessionIdGenerator; -import io.undertow.server.session.SessionListener; - - -/** - * Builds a distributable {@link SingleSignOnManagerFactory} service. - * @author Paul Ferraro - */ -public class DistributableSingleSignOnManagerServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Supplier { - - private final HostSingleSignOnManagementConfiguration configuration; - private final LegacySSOManagementProviderFactory legacyProviderFactory; - - private volatile SupplierDependency> manager; - private volatile SupplierDependency registry; - - private volatile SupplierDependency provider; - private volatile Consumer installer; - - public DistributableSingleSignOnManagerServiceConfigurator(ServiceName name, HostSingleSignOnManagementConfiguration configuration, LegacySSOManagementProviderFactory legacyProviderFactory) { - super(name); - this.configuration = configuration; - this.legacyProviderFactory = legacyProviderFactory; - } - - @Override - public SingleSignOnManager get() { - return new DistributableSingleSignOnManager(this.manager.get(), this.registry.get()); - } - - @Override - public ServiceConfigurator configure(OperationContext context) { - String serverName = this.configuration.getServerName(); - String hostName = this.configuration.getHostName(); - CapabilityServiceSupport support = context.getCapabilityServiceSupport(); - SupplierDependency provider = getProvider(context, serverName, hostName); - ServiceName serviceName = this.getServiceName(); - ServiceName generatorServiceName = serviceName.append("generator"); - ServiceName managerServiceName = serviceName.append("manager"); - ServiceName listenerServiceName = serviceName.append("listener"); - ServiceName registryServiceName = serviceName.append("registry"); - this.manager = new ServiceSupplierDependency<>(managerServiceName); - this.registry = new ServiceSupplierDependency<>(registryServiceName); - this.provider = provider; - this.installer = new Consumer() { - @Override - public void accept(ServiceTarget target) { - ServiceConfigurator factoryConfigurator = provider.get().getServiceConfigurator(hostName).configure(support); - factoryConfigurator.build(target).install(); - - new SessionIdGeneratorServiceConfigurator(generatorServiceName, serverName).configure(support).build(target).install(); - - SupplierDependency> factoryDependency = new ServiceSupplierDependency<>(factoryConfigurator); - SupplierDependency generatorDependency = new ServiceSupplierDependency<>(generatorServiceName); - new SSOManagerServiceConfigurator<>(managerServiceName, factoryDependency, generatorDependency, () -> null).configure(support).build(target).install(); - - SupplierDependency> managerDependency = new ServiceSupplierDependency<>(managerServiceName); - new SessionListenerServiceConfigurator(listenerServiceName, managerDependency).configure(support).build(target).install(); - - SupplierDependency listenerDependency = new ServiceSupplierDependency<>(listenerServiceName); - new SessionManagerRegistryServiceConfigurator(registryServiceName, serverName, hostName, listenerDependency).configure(support).build(target).install(); - } - }; - return this; - } - - @Override - public ServiceBuilder build(ServiceTarget target) { - ServiceName name = this.getServiceName(); - ServiceController installerController = this.provider.register(target.addService(name.append("installer"))).setInstance(new ChildTargetService(this.installer)).install(); - - ServiceBuilder builder = target.addService(name).addListener(new CascadeRemovalLifecycleListener(installerController)); - Consumer manager = new CompositeDependency(this.manager, this.registry).register(builder).provides(name); - Service service = new FunctionalService<>(manager, Function.identity(), this); - return builder.setInstance(service); - } - - private SupplierDependency getProvider(OperationContext context, String serverName, String hostName) { - String hostCapabilityName = UndertowBinaryRequirement.HOST.resolve(serverName, hostName); - if (context.hasOptionalCapability(WebProviderRequirement.SSO_MANAGEMENT_PROVIDER.resolve(hostName), hostCapabilityName, null)) { - return new ServiceSupplierDependency<>(WebProviderRequirement.SSO_MANAGEMENT_PROVIDER.getServiceName(context, hostName)); - } else if (context.hasOptionalCapability(WebDefaultProviderRequirement.SSO_MANAGEMENT_PROVIDER.getName(), hostCapabilityName, null)) { - return new ServiceSupplierDependency<>(WebDefaultProviderRequirement.SSO_MANAGEMENT_PROVIDER.getServiceName(context)); - } - UndertowClusteringLogger.ROOT_LOGGER.legacySingleSignOnProviderInUse(hostName); - return new SimpleSupplierDependency<>(this.legacyProviderFactory.createSSOManagementProvider()); - } -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/InvalidatableSingleSignOn.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/InvalidatableSingleSignOn.java deleted file mode 100644 index 5acb8ba6e83e..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/InvalidatableSingleSignOn.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2015, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import io.undertow.security.impl.SingleSignOn; - -/** - * @author Paul Ferraro - */ -public interface InvalidatableSingleSignOn extends SingleSignOn { - void invalidate(); -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionIdGeneratorServiceConfigurator.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionIdGeneratorServiceConfigurator.java deleted file mode 100644 index 1072d43339e1..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionIdGeneratorServiceConfigurator.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import java.util.function.Consumer; -import java.util.function.Function; - -import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; -import org.jboss.as.controller.capability.CapabilityServiceSupport; -import org.jboss.msc.Service; -import org.jboss.msc.service.ServiceBuilder; -import org.jboss.msc.service.ServiceController; -import org.jboss.msc.service.ServiceName; -import org.jboss.msc.service.ServiceTarget; -import org.wildfly.clustering.service.FunctionalService; -import org.wildfly.clustering.service.ServiceConfigurator; -import org.wildfly.clustering.service.ServiceSupplierDependency; -import org.wildfly.clustering.service.SimpleServiceNameProvider; -import org.wildfly.clustering.service.SupplierDependency; -import org.wildfly.clustering.web.undertow.UndertowUnaryRequirement; -import org.wildfly.extension.undertow.Server; - -import io.undertow.server.session.SecureRandomSessionIdGenerator; -import io.undertow.server.session.SessionIdGenerator; - -/** - * @author Paul Ferraro - */ -public class SessionIdGeneratorServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Function { - - private final String serverName; - - private volatile SupplierDependency server; - - public SessionIdGeneratorServiceConfigurator(ServiceName name, String serverName) { - super(name); - this.serverName = serverName; - } - - @Override - public SessionIdGenerator apply(Server server) { - SecureRandomSessionIdGenerator generator = new SecureRandomSessionIdGenerator(); - generator.setLength(server.getServletContainer().getSessionIdLength()); - return generator; - } - - @Override - public ServiceConfigurator configure(CapabilityServiceSupport support) { - this.server = new ServiceSupplierDependency<>(UndertowUnaryRequirement.SERVER.getServiceName(support, this.serverName)); - return this; - } - - @Override - public ServiceBuilder build(ServiceTarget target) { - ServiceBuilder builder = target.addService(this.getServiceName()); - Consumer generator = this.server.register(builder).provides(this.getServiceName()); - Service service = new FunctionalService<>(generator, this, this.server); - return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); - } -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionListenerServiceConfigurator.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionListenerServiceConfigurator.java deleted file mode 100644 index 0880063d28f5..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionListenerServiceConfigurator.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2016, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import java.util.function.Consumer; - -import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; -import org.jboss.msc.Service; -import org.jboss.msc.service.ServiceBuilder; -import org.jboss.msc.service.ServiceController; -import org.jboss.msc.service.ServiceName; -import org.jboss.msc.service.ServiceTarget; -import org.wildfly.clustering.ee.Batch; -import org.wildfly.clustering.service.SimpleServiceNameProvider; -import org.wildfly.clustering.service.SupplierDependency; -import org.wildfly.clustering.web.sso.SSOManager; -import org.wildfly.clustering.web.sso.Sessions; - -import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; -import io.undertow.server.HttpServerExchange; -import io.undertow.server.session.Session; -import io.undertow.server.session.SessionListener; - -/** - * @author Paul Ferraro - */ -public class SessionListenerServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, SessionListener { - - private final SupplierDependency> manager; - - public SessionListenerServiceConfigurator(ServiceName name, SupplierDependency> manager) { - super(name); - this.manager = manager; - } - - @Override - public ServiceBuilder build(ServiceTarget target) { - ServiceBuilder builder = target.addService(this.getServiceName()); - Consumer listener = this.manager.register(builder).provides(this.getServiceName()); - Service service = Service.newInstance(listener, this); - return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); - } - - @Override - public void sessionIdChanged(Session session, String oldSessionId) { - SSOManager manager = this.manager.get(); - try (Batch batch = manager.getBatcher().createBatch()) { - Sessions sessions = manager.findSessionsContaining(oldSessionId); - if (sessions != null) { - for (String deployment : sessions.getDeployments()) { - if (sessions.getSession(deployment) != null) { - sessions.removeSession(deployment); - sessions.addSession(deployment, session.getId()); - break; - } - } - } - } - } - - @Override - public void sessionCreated(Session session, HttpServerExchange exchange) { - } - - @Override - public void sessionDestroyed(Session session, HttpServerExchange exchange, SessionDestroyedReason reason) { - } - - @Override - public void attributeAdded(Session session, String name, Object value) { - } - - @Override - public void attributeUpdated(Session session, String name, Object newValue, Object oldValue) { - } - - @Override - public void attributeRemoved(Session session, String name, Object oldValue) { - } -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionManagerRegistry.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionManagerRegistry.java deleted file mode 100644 index ccd1191a0c3b..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionManagerRegistry.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.wildfly.clustering.web.undertow.sso; - -import io.undertow.server.session.SessionManager; - -/** - * Mechanism for looking up the {@link SessionManager} for a given deployment. - * @author Paul Ferraro - */ -public interface SessionManagerRegistry { - /** - * Returns the session manager for the specified deployment, or null if the deployment does not exist. - * @param deployment a deployment name - * @return a session manager - */ - SessionManager getSessionManager(String deployment); -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionManagerRegistryServiceConfigurator.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionManagerRegistryServiceConfigurator.java deleted file mode 100644 index e5006b79da4b..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/SessionManagerRegistryServiceConfigurator.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.wildfly.clustering.web.undertow.sso; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.function.Consumer; - -import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; -import org.jboss.as.controller.capability.CapabilityServiceSupport; -import org.jboss.msc.Service; -import org.jboss.msc.service.ServiceBuilder; -import org.jboss.msc.service.ServiceController; -import org.jboss.msc.service.ServiceName; -import org.jboss.msc.service.ServiceTarget; -import org.jboss.msc.service.StartContext; -import org.jboss.msc.service.StopContext; -import org.wildfly.clustering.service.CompositeDependency; -import org.wildfly.clustering.service.ServiceConfigurator; -import org.wildfly.clustering.service.ServiceSupplierDependency; -import org.wildfly.clustering.service.SimpleServiceNameProvider; -import org.wildfly.clustering.service.SupplierDependency; -import org.wildfly.clustering.web.undertow.UndertowBinaryRequirement; -import org.wildfly.clustering.web.undertow.UndertowRequirement; -import org.wildfly.extension.undertow.Host; -import org.wildfly.extension.undertow.UndertowEventListener; -import org.wildfly.extension.undertow.UndertowService; - -import io.undertow.server.session.SessionListener; -import io.undertow.server.session.SessionManager; -import io.undertow.servlet.api.Deployment; - -/** - * Service providing a {@link SessionManagerRegistry} for a host. - * @author Paul Ferraro - */ -public class SessionManagerRegistryServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, Service, SessionManagerRegistry, UndertowEventListener { - - private final String serverName; - private final String hostName; - private final SupplierDependency listener; - - private final ConcurrentMap managers = new ConcurrentHashMap<>(); - - private volatile SupplierDependency service; - private volatile SupplierDependency host; - private volatile Consumer registry; - - public SessionManagerRegistryServiceConfigurator(ServiceName name, String serverName, String hostName, SupplierDependency listener) { - super(name); - this.serverName = serverName; - this.hostName = hostName; - this.listener = listener; - } - - @Override - public ServiceConfigurator configure(CapabilityServiceSupport support) { - this.service = new ServiceSupplierDependency<>(UndertowRequirement.UNDERTOW.getServiceName(support)); - this.host = new ServiceSupplierDependency<>(UndertowBinaryRequirement.HOST.getServiceName(support, this.serverName, this.hostName)); - return this; - } - - @Override - public ServiceBuilder build(ServiceTarget target) { - ServiceBuilder builder = target.addService(this.getServiceName()); - this.registry = new CompositeDependency(this.listener, this.service, this.host).register(builder).provides(this.getServiceName()); - return builder.setInstance(this).setInitialMode(ServiceController.Mode.ON_DEMAND); - } - - @Override - public void start(StartContext context) { - this.service.get().registerListener(this); - for (Deployment deployment : this.host.get().getDeployments()) { - this.addDeployment(deployment); - } - this.registry.accept(this); - } - - @Override - public void stop(StopContext context) { - for (Deployment deployment : this.host.get().getDeployments()) { - this.removeDeployment(deployment); - } - this.service.get().unregisterListener(this); - } - - private void addDeployment(Deployment deployment) { - SessionManager manager = deployment.getSessionManager(); - if (this.managers.putIfAbsent(deployment.getDeploymentInfo().getDeploymentName(), deployment.getSessionManager()) == null) { - manager.registerSessionListener(this.listener.get()); - } - } - - private void removeDeployment(Deployment deployment) { - if (this.managers.remove(deployment.getDeploymentInfo().getDeploymentName()) != null) { - deployment.getSessionManager().removeSessionListener(this.listener.get()); - } - } - - @Override - public void onDeploymentStart(Deployment deployment, Host host) { - if (this.host.get().getName().equals(host.getName())) { - this.addDeployment(deployment); - } - } - - @Override - public void onDeploymentStop(Deployment deployment, Host host) { - if (this.host.get().getName().equals(host.getName())) { - this.removeDeployment(deployment); - } - } - - @Override - public SessionManager getSessionManager(String deployment) { - return this.managers.get(deployment); - } -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/UndertowSecuritySerializationContextInitializer.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/UndertowSecuritySerializationContextInitializer.java deleted file mode 100644 index fdf0b59f3a0c..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/UndertowSecuritySerializationContextInitializer.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2020, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import org.infinispan.protostream.SerializationContext; -import org.infinispan.protostream.SerializationContextInitializer; -import org.kohsuke.MetaInfServices; -import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; - -/** - * @author Paul Ferraro - */ -@MetaInfServices(SerializationContextInitializer.class) -public class UndertowSecuritySerializationContextInitializer extends AbstractSerializationContextInitializer { - - public UndertowSecuritySerializationContextInitializer() { - super("io.undertow.security.api.proto"); - } - - @Override - public void registerMarshallers(SerializationContext context) { - context.registerMarshaller(new AuthenticatedSessionMarshaller()); - } -} diff --git a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/UndertowSingleSignOnManagementProvider.java b/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/UndertowSingleSignOnManagementProvider.java deleted file mode 100644 index 7abf76e9560b..000000000000 --- a/clustering/web/undertow/src/main/java/org/wildfly/clustering/web/undertow/sso/UndertowSingleSignOnManagementProvider.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import java.util.Iterator; -import java.util.ServiceConfigurationError; -import java.util.ServiceLoader; - -import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; -import org.jboss.msc.service.ServiceName; -import org.kohsuke.MetaInfServices; -import org.wildfly.clustering.web.container.HostSingleSignOnManagementConfiguration; -import org.wildfly.clustering.web.container.HostSingleSignOnManagementProvider; -import org.wildfly.clustering.web.sso.DistributableSSOManagementProvider; -import org.wildfly.clustering.web.sso.LegacySSOManagementProviderFactory; -import org.wildfly.extension.undertow.session.SessionManagementProviderFactory; - -/** - * {@link SessionManagementProviderFactory} for Undertow using either the {@link DistributableSSOManagementProvider} for the given host, the default provider, or a legacy provider. - * @author Paul Ferraro - */ -@MetaInfServices(HostSingleSignOnManagementProvider.class) -public class UndertowSingleSignOnManagementProvider implements HostSingleSignOnManagementProvider { - - private final LegacySSOManagementProviderFactory legacyProviderFactory; - - public UndertowSingleSignOnManagementProvider() { - Iterator factories = ServiceLoader.load(LegacySSOManagementProviderFactory.class, LegacySSOManagementProviderFactory.class.getClassLoader()).iterator(); - if (!factories.hasNext()) { - throw new ServiceConfigurationError(LegacySSOManagementProviderFactory.class.getName()); - } - this.legacyProviderFactory = factories.next(); - } - - @Override - public CapabilityServiceConfigurator getServiceConfigurator(ServiceName name, HostSingleSignOnManagementConfiguration configuration) { - return new DistributableSingleSignOnManagerServiceConfigurator(name, configuration, this.legacyProviderFactory); - } -} diff --git a/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManagerTestCase.java b/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManagerTestCase.java deleted file mode 100644 index 4ea800ed665e..000000000000 --- a/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnManagerTestCase.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.same; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import java.util.function.Supplier; - -import javax.servlet.http.HttpServletRequest; - -import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; -import io.undertow.security.idm.Account; -import io.undertow.security.impl.SingleSignOn; -import io.undertow.security.impl.SingleSignOnManager; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.wildfly.clustering.ee.Batch; -import org.wildfly.clustering.ee.Batcher; -import org.wildfly.clustering.web.sso.SSO; -import org.wildfly.clustering.web.sso.SSOManager; - -/** - * Unit test for {@link DistributableSingleSignOnManager} - * - * @author Paul Ferraro - */ -public class DistributableSingleSignOnManagerTestCase { - - private final SSOManager manager = mock(SSOManager.class); - private final SessionManagerRegistry registry = mock(SessionManagerRegistry.class); - - private final SingleSignOnManager subject = new DistributableSingleSignOnManager(this.manager, this.registry); - - @Test - public void createSingleSignOn() { - String id = "sso"; - Supplier identifierFactory = mock(Supplier.class); - Batcher batcher = mock(Batcher.class); - Batch batch = mock(Batch.class); - Account account = mock(Account.class); - String mechanism = HttpServletRequest.BASIC_AUTH; - SSO sso = mock(SSO.class); - ArgumentCaptor authenticationCaptor = ArgumentCaptor.forClass(AuthenticatedSession.class); - - when(this.manager.getIdentifierFactory()).thenReturn(identifierFactory); - when(identifierFactory.get()).thenReturn(id); - when(this.manager.getBatcher()).thenReturn(batcher); - when(batcher.createBatch()).thenReturn(batch); - when(this.manager.createSSO(same(id), authenticationCaptor.capture())).thenReturn(sso); - - SingleSignOn result = this.subject.createSingleSignOn(account, mechanism); - - verify(batcher).suspendBatch(); - - assertNotNull(result); - - AuthenticatedSession capturedAuthentication = authenticationCaptor.getValue(); - assertNotNull(capturedAuthentication); - assertSame(capturedAuthentication.getAccount(), account); - assertSame(capturedAuthentication.getMechanism(), mechanism); - } - - @Test - public void findSingleSignOnNotExists() { - String id = "sso"; - Batcher batcher = mock(Batcher.class); - Batch batch = mock(Batch.class); - - when(this.manager.getBatcher()).thenReturn(batcher); - when(batcher.createBatch()).thenReturn(batch); - when(this.manager.findSSO(id)).thenReturn(null); - - SingleSignOn result = this.subject.findSingleSignOn(id); - - assertNull(result); - - verify(batch).close(); - verify(batcher, never()).suspendBatch(); - } - - @Test - public void findSingleSignOnInvalidCharacters() { - String id = "sso+"; - - SingleSignOn result = this.subject.findSingleSignOn(id); - - assertNull(result); - - verifyNoInteractions(this.manager); - } - - @Test - public void findSingleSignOn() { - String id = "sso"; - Batcher batcher = mock(Batcher.class); - Batch batch = mock(Batch.class); - SSO sso = mock(SSO.class); - - when(this.manager.getBatcher()).thenReturn(batcher); - when(batcher.createBatch()).thenReturn(batch); - when(this.manager.findSSO(id)).thenReturn(sso); - - SingleSignOn result = this.subject.findSingleSignOn(id); - - assertNotNull(result); - - verify(batcher).suspendBatch(); - } - - @Test - public void removeSingleSignOn() { - InvalidatableSingleSignOn sso = mock(InvalidatableSingleSignOn.class); - - this.subject.removeSingleSignOn(sso); - - verify(sso).invalidate(); - } -} diff --git a/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnTestCase.java b/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnTestCase.java deleted file mode 100644 index 0642d73297c5..000000000000 --- a/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/DistributableSingleSignOnTestCase.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.same; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.Iterator; -import javax.servlet.http.HttpServletRequest; - -import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; -import io.undertow.security.idm.Account; -import io.undertow.server.HttpServerExchange; -import io.undertow.server.session.Session; -import io.undertow.server.session.SessionManager; -import org.junit.Test; -import org.wildfly.clustering.ee.Batch; -import org.wildfly.clustering.ee.BatchContext; -import org.wildfly.clustering.ee.Batcher; -import org.wildfly.clustering.web.sso.SSO; -import org.wildfly.clustering.web.sso.Sessions; - -/** - * Unit test for {@link DistributableSingleSignOn} - * - * @author Paul Ferraro - */ -public class DistributableSingleSignOnTestCase { - - private final SSO sso = mock(SSO.class); - private final SessionManagerRegistry registry = mock(SessionManagerRegistry.class); - private final Batcher batcher = mock(Batcher.class); - private final Batch batch = mock(Batch.class); - private final InvalidatableSingleSignOn subject = new DistributableSingleSignOn(this.sso, this.registry, this.batcher, this.batch); - - @Test - public void getId() { - String id = "sso"; - - when(this.sso.getId()).thenReturn(id); - - String result = this.subject.getId(); - - assertSame(id, result); - - verifyNoInteractions(this.batch); - } - - @Test - public void getAccount() { - BatchContext context = mock(BatchContext.class); - Account account = mock(Account.class); - String mechanism = HttpServletRequest.BASIC_AUTH; - AuthenticatedSession authentication = new AuthenticatedSession(account, mechanism); - - when(this.batcher.resumeBatch(this.batch)).thenReturn(context); - when(this.sso.getAuthentication()).thenReturn(authentication); - - Account result = this.subject.getAccount(); - - assertSame(account, result); - - verifyNoInteractions(this.batch); - verify(context).close(); - } - - @Test - public void getMechanismName() { - BatchContext context = mock(BatchContext.class); - Account account = mock(Account.class); - String mechanism = HttpServletRequest.CLIENT_CERT_AUTH; - AuthenticatedSession authentication = new AuthenticatedSession(account, mechanism); - - when(this.batcher.resumeBatch(this.batch)).thenReturn(context); - when(this.sso.getAuthentication()).thenReturn(authentication); - - String result = this.subject.getMechanismName(); - - assertEquals(HttpServletRequest.CLIENT_CERT_AUTH, result); - - verifyNoInteractions(this.batch); - verify(context).close(); - } - - @Test - public void iterator() { - BatchContext context = mock(BatchContext.class); - Sessions sessions = mock(Sessions.class); - SessionManager manager = mock(SessionManager.class); - Session session = mock(Session.class); - String deployment = "deployment"; - String sessionId = "session"; - - when(this.batcher.resumeBatch(this.batch)).thenReturn(context); - when(this.sso.getSessions()).thenReturn(sessions); - when(sessions.getDeployments()).thenReturn(Collections.singleton(deployment)); - when(sessions.getSession(deployment)).thenReturn(sessionId); - when(this.registry.getSessionManager(deployment)).thenReturn(manager); - when(manager.getSession(sessionId)).thenReturn(session); - when(session.getId()).thenReturn(sessionId); - - Iterator results = this.subject.iterator(); - - assertTrue(results.hasNext()); - Session result = results.next(); - assertEquals(session.getId(), result.getId()); - assertFalse(results.hasNext()); - - verifyNoInteractions(this.batch); - verify(context).close(); - - // Validate that returned sessions can be invalidated - HttpServerExchange exchange = new HttpServerExchange(null); - Session mutableSession = mock(Session.class); - - when(session.getSessionManager()).thenReturn(manager); - when(manager.getSession(same(exchange), any())).thenReturn(mutableSession); - - result.invalidate(exchange); - - verify(mutableSession).invalidate(same(exchange)); - verifyNoInteractions(this.batch); - verifyNoMoreInteractions(context); - } - - @Test - public void contains() { - String deployment = "deployment"; - BatchContext context = mock(BatchContext.class); - Session session = mock(Session.class); - SessionManager manager = mock(SessionManager.class); - Sessions sessions = mock(Sessions.class); - - when(this.batcher.resumeBatch(this.batch)).thenReturn(context); - when(session.getSessionManager()).thenReturn(manager); - when(manager.getDeploymentName()).thenReturn(deployment); - when(this.sso.getSessions()).thenReturn(sessions); - when(sessions.getDeployments()).thenReturn(Collections.emptySet()); - - boolean result = this.subject.contains(session); - - assertFalse(result); - - verifyNoInteractions(this.batch); - verify(context).close(); - reset(context); - - when(sessions.getDeployments()).thenReturn(Collections.singleton(deployment)); - - result = this.subject.contains(session); - - assertTrue(result); - - verifyNoInteractions(this.batch); - verify(context).close(); - } - - @Test - public void add() { - String deployment = "deployment"; - String sessionId = "session"; - BatchContext context = mock(BatchContext.class); - Session session = mock(Session.class); - SessionManager manager = mock(SessionManager.class); - Sessions sessions = mock(Sessions.class); - - when(this.batcher.resumeBatch(this.batch)).thenReturn(context); - when(session.getId()).thenReturn(sessionId); - when(session.getSessionManager()).thenReturn(manager); - when(manager.getDeploymentName()).thenReturn(deployment); - when(this.sso.getSessions()).thenReturn(sessions); - - this.subject.add(session); - - verify(sessions).addSession(deployment, sessionId); - verifyNoInteractions(this.batch); - verify(context).close(); - } - - @Test - public void remove() { - String deployment = "deployment"; - BatchContext context = mock(BatchContext.class); - Session session = mock(Session.class); - SessionManager manager = mock(SessionManager.class); - Sessions sessions = mock(Sessions.class); - - when(this.batcher.resumeBatch(this.batch)).thenReturn(context); - when(session.getSessionManager()).thenReturn(manager); - when(manager.getDeploymentName()).thenReturn(deployment); - when(this.sso.getSessions()).thenReturn(sessions); - - this.subject.remove(session); - - verify(sessions).removeSession(deployment); - verifyNoInteractions(this.batch); - verify(context).close(); - } - - @Test - public void getSession() { - String deployment = "deployment"; - String sessionId = "session"; - BatchContext context = mock(BatchContext.class); - SessionManager manager = mock(SessionManager.class); - Sessions sessions = mock(Sessions.class); - - when(this.batcher.resumeBatch(this.batch)).thenReturn(context); - when(manager.getDeploymentName()).thenReturn(deployment); - when(this.sso.getSessions()).thenReturn(sessions); - when(sessions.getSession(deployment)).thenReturn(sessionId); - - Session result = this.subject.getSession(manager); - - assertSame(sessionId, result.getId()); - assertSame(manager, result.getSessionManager()); - - verifyNoInteractions(this.batch); - verify(context).close(); - } - - @Test - public void close() { - BatchContext context = mock(BatchContext.class); - - when(this.batcher.resumeBatch(this.batch)).thenReturn(context); - - this.subject.close(); - - verify(this.batch).close(); - verify(context).close(); - reset(this.batch); - - this.subject.close(); - - verify(this.batch, never()).close(); - } - - @Test - public void invalidate() { - BatchContext context = mock(BatchContext.class); - - when(this.batcher.resumeBatch(this.batch)).thenReturn(context); - - this.subject.invalidate(); - - verify(context).close(); - } -} diff --git a/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/UndertowSecurityMarshallingTestCase.java b/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/UndertowSecurityMarshallingTestCase.java deleted file mode 100644 index 57133e9d21d9..000000000000 --- a/clustering/web/undertow/src/test/java/org/wildfly/clustering/web/undertow/sso/UndertowSecurityMarshallingTestCase.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2020, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.wildfly.clustering.web.undertow.sso; - -import java.io.IOException; -import java.util.Collections; - -import javax.servlet.http.HttpServletRequest; - -import org.junit.Assert; -import org.junit.Test; -import org.wildfly.clustering.marshalling.ExternalizerTester; -import org.wildfly.clustering.marshalling.Tester; -import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; -import org.wildfly.extension.undertow.security.AccountImpl; - -import io.undertow.security.api.AuthenticatedSessionManager.AuthenticatedSession; - -/** - * @author Paul Ferraro - */ -public class UndertowSecurityMarshallingTestCase { - - @Test - public void testExternalizer() throws IOException { - test(new ExternalizerTester<>(new AuthenticatedSessionExternalizer())); - } - - @Test - public void testProtoStream() throws IOException { - test(ProtoStreamTesterFactory.INSTANCE.createTester()); - } - - private static void test(Tester tester) throws IOException { - tester.test(new AuthenticatedSession(new AccountImpl("test"), HttpServletRequest.BASIC_AUTH), UndertowSecurityMarshallingTestCase::assertEquals); - tester.test(new AuthenticatedSession(new AccountImpl(new AccountImpl("test").getPrincipal()), HttpServletRequest.CLIENT_CERT_AUTH), UndertowSecurityMarshallingTestCase::assertEquals); - tester.test(new AuthenticatedSession(new AccountImpl(new AccountImpl("test").getPrincipal(), Collections.singleton("user"), "password"), HttpServletRequest.DIGEST_AUTH), UndertowSecurityMarshallingTestCase::assertEquals); - tester.test(new AuthenticatedSession(new AccountImpl(new AccountImpl("test").getPrincipal(), Collections.singleton("user"), "password", new AccountImpl("original").getPrincipal()), HttpServletRequest.FORM_AUTH), UndertowSecurityMarshallingTestCase::assertEquals); - } - - static void assertEquals(AuthenticatedSession session1, AuthenticatedSession session2) { - Assert.assertEquals(session1.getMechanism(), session2.getMechanism()); - AccountImpl account1 = (AccountImpl) session1.getAccount(); - AccountImpl account2 = (AccountImpl) session2.getAccount(); - Assert.assertEquals(account1.getPrincipal(), account2.getPrincipal()); - Assert.assertEquals(account1.getRoles(), account2.getRoles()); - Assert.assertEquals(account1.getCredential(), account2.getCredential()); - Assert.assertEquals(account1.getOriginalPrincipal(), account2.getOriginalPrincipal()); - } -} From d1d6058835fa1416050fb03a19480e33cf8a52a2 Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Wed, 24 Nov 2021 08:55:46 +0000 Subject: [PATCH 05/11] [WFLY-15732] / [WFLY-15356] Temporarily ignore PolicyContextTestCase. --- .../security/jacc/context/PolicyContextTestCase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/security/jacc/context/PolicyContextTestCase.java b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/security/jacc/context/PolicyContextTestCase.java index 23d6572f396f..b0d644af4d7b 100644 --- a/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/security/jacc/context/PolicyContextTestCase.java +++ b/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/security/jacc/context/PolicyContextTestCase.java @@ -35,6 +35,7 @@ import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -44,6 +45,7 @@ @RunWith(Arquillian.class) @RunAsClient +@Ignore("[WFLY-15740] Rework PolicyContextTestCase for Elytron") public class PolicyContextTestCase { private static Logger LOGGER = Logger.getLogger(PolicyContextTestCase.class); From 7a97d5705aa49314b52dc463a24f6a5d7b183395 Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Wed, 24 Nov 2021 12:53:40 +0000 Subject: [PATCH 06/11] [WFLY-15734] / [WFLY-15356] Remove security-plugins dependency from EJB3. --- .../base/org/jboss/as/ejb3/main/module.xml | 1 - ejb3/pom.xml | 6 - .../jboss/as/ejb3/component/EJBComponent.java | 28 +-- .../component/EJBComponentCreateService.java | 10 - .../component/EJBComponentDescription.java | 56 +---- .../AsyncFutureInterceptorFactory.java | 95 +------ .../SingletonComponentDescription.java | 6 +- .../org/jboss/as/ejb3/logging/EjbLogger.java | 4 + .../jboss/as/ejb3/remote/AssociationImpl.java | 23 -- .../jboss/as/ejb3/remote/SecurityActions.java | 165 ------------ .../security/AuthorizationInterceptor.java | 235 ------------------ .../security/EJBSecurityViewConfigurator.java | 9 +- .../security/SecurityContextInterceptor.java | 148 ----------- .../SecurityContextInterceptorFactory.java | 99 -------- .../SecurityContextInterceptorHolder.java | 8 - 15 files changed, 23 insertions(+), 870 deletions(-) delete mode 100644 ejb3/src/main/java/org/jboss/as/ejb3/remote/SecurityActions.java delete mode 100644 ejb3/src/main/java/org/jboss/as/ejb3/security/AuthorizationInterceptor.java delete mode 100644 ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptor.java delete mode 100644 ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptorFactory.java diff --git a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/ejb3/main/module.xml b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/ejb3/main/module.xml index 6bc340ab9ec2..87e95bc6160d 100644 --- a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/ejb3/main/module.xml +++ b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/ejb3/main/module.xml @@ -67,7 +67,6 @@ - diff --git a/ejb3/pom.xml b/ejb3/pom.xml index 1d21df9b1e58..824948627e5c 100644 --- a/ejb3/pom.xml +++ b/ejb3/pom.xml @@ -98,12 +98,6 @@ vi:ts=4:sw=4:expandtab wildfly-iiop-openjdk - - ${project.groupId} - wildfly-security-plugins - provided - - org.wildfly.core wildfly-network diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponent.java b/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponent.java index 828dbad7681c..dea8581ba33a 100644 --- a/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponent.java +++ b/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponent.java @@ -52,7 +52,6 @@ import javax.transaction.TransactionSynchronizationRegistry; import javax.transaction.UserTransaction; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.ee.component.BasicComponent; import org.jboss.as.ee.component.ComponentView; import org.jboss.as.ee.component.interceptors.InvocationType; @@ -122,17 +121,9 @@ public abstract class EJBComponent extends BasicComponent implements ServerActiv private final ShutDownInterceptorFactory shutDownInterceptorFactory; private final TransactionSynchronizationRegistry transactionSynchronizationRegistry; private final UserTransaction userTransaction; - private final ServerSecurityManager serverSecurityManager; private final ControlPoint controlPoint; private final AtomicBoolean exceptionLoggingEnabled; - private final PrivilegedAction getCaller = new PrivilegedAction() { - @Override - public Principal run() { - return serverSecurityManager.getCallerPrincipal(); - } - }; - private final SecurityDomain securityDomain; private final boolean enableJacc; private SecurityIdentity incomingRunAsIdentity; @@ -185,7 +176,6 @@ protected EJBComponent(final EJBComponentCreateService ejbComponentCreateService this.ejbSuspendHandlerService = ejbComponentCreateService.getEJBSuspendHandler(); this.transactionSynchronizationRegistry = ejbComponentCreateService.getTransactionSynchronizationRegistry(); this.userTransaction = ejbComponentCreateService.getUserTransaction(); - this.serverSecurityManager = ejbComponentCreateService.getServerSecurityManager(); this.controlPoint = ejbComponentCreateService.getControlPoint(); this.exceptionLoggingEnabled = ejbComponentCreateService.getExceptionLoggingEnabled(); @@ -281,11 +271,10 @@ public ApplicationExceptionDetails getApplicationException(Class exceptionCla public Principal getCallerPrincipal() { if (isSecurityDomainKnown()) { return getCallerSecurityIdentity().getPrincipal(); - } else if (WildFlySecurityManager.isChecking()) { - return WildFlySecurityManager.doUnchecked(getCaller); - } else { - return this.serverSecurityManager.getCallerPrincipal(); } + + // TODO Should this return a Principal when security is not activated. + return null; } public SecurityIdentity getIncomingRunAsIdentity() { @@ -374,10 +363,6 @@ public boolean getRollbackOnly() throws IllegalStateException { } } - public ServerSecurityManager getSecurityManager() { - return this.serverSecurityManager; - } - public TimerService getTimerService() throws IllegalStateException { return timerService; } @@ -457,11 +442,10 @@ public boolean isCallerInRole(final String roleName) throws IllegalStateExceptio } else { return checkCallerSecurityIdentityRole(roleName); } - } else if (WildFlySecurityManager.isChecking()) { - return WildFlySecurityManager.doUnchecked((PrivilegedAction) () -> serverSecurityManager.isCallerInRole(getComponentName(), policyContextID, securityMetaData.getSecurityRoles(), securityMetaData.getSecurityRoleLinks(), roleName)); - } else { - return this.serverSecurityManager.isCallerInRole(getComponentName(), policyContextID, securityMetaData.getSecurityRoles(), securityMetaData.getSecurityRoleLinks(), roleName); } + + // No security, no role membership. + return false; } public boolean isStatisticsEnabled() { diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentCreateService.java b/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentCreateService.java index 87725a8e1472..44a65f95f877 100644 --- a/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentCreateService.java +++ b/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentCreateService.java @@ -40,7 +40,6 @@ import javax.transaction.TransactionSynchronizationRegistry; import javax.transaction.UserTransaction; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.ee.component.BasicComponentCreateService; import org.jboss.as.ee.component.ComponentConfiguration; import org.jboss.as.ee.component.ViewConfiguration; @@ -98,7 +97,6 @@ public class EJBComponentCreateService extends BasicComponentCreateService { private final String policyContextID; private final InjectedValue transactionSynchronizationRegistryValue = new InjectedValue(); - private final InjectedValue serverSecurityManagerInjectedValue = new InjectedValue<>(); private final InjectedValue controlPoint = new InjectedValue<>(); private final InjectedValue exceptionLoggingEnabled = new InjectedValue<>(); private final InjectedValue securityDomain = new InjectedValue<>(); @@ -355,14 +353,6 @@ EJBSuspendHandlerService getEJBSuspendHandler() { return this.ejbSuspendHandler.getValue(); } - ServerSecurityManager getServerSecurityManager() { - return this.serverSecurityManagerInjectedValue.getOptionalValue(); - } - - Injector getServerSecurityManagerInjector() { - return this.serverSecurityManagerInjectedValue; - } - public ControlPoint getControlPoint() { return this.controlPoint.getOptionalValue(); } diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentDescription.java b/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentDescription.java index 403f96c53c7b..0b4266e30b97 100644 --- a/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentDescription.java +++ b/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentDescription.java @@ -21,8 +21,8 @@ */ package org.jboss.as.ejb3.component; +import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER; import static org.jboss.as.ejb3.subsystem.IdentityResourceDefinition.IDENTITY_CAPABILITY_NAME; -import static org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT; import java.lang.reflect.Method; import java.rmi.Remote; @@ -48,7 +48,6 @@ import javax.transaction.TransactionSynchronizationRegistry; import org.jboss.as.controller.capability.CapabilityServiceSupport; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.BindingConfiguration; import org.jboss.as.ee.component.Component; @@ -89,7 +88,6 @@ import org.jboss.as.ejb3.security.PolicyContextIdInterceptor; import org.jboss.as.ejb3.security.RoleAddingInterceptor; import org.jboss.as.ejb3.security.RunAsPrincipalInterceptor; -import org.jboss.as.ejb3.security.SecurityContextInterceptorFactory; import org.jboss.as.ejb3.security.SecurityDomainInterceptorFactory; import org.jboss.as.ejb3.security.SecurityRolesAddingInterceptor; import org.jboss.as.ejb3.subsystem.EJB3RemoteResourceDefinition; @@ -114,7 +112,6 @@ import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; -import org.jboss.security.SecurityConstants; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.authz.RoleMapper; import org.wildfly.security.authz.Roles; @@ -131,10 +128,6 @@ public abstract class EJBComponentDescription extends ComponentDescription { private static final String REMOTE_TRANSACTION_SERVICE_CAPABILITY_NAME = "org.wildfly.transactions.remote-transaction-service"; private static final String TRANSACTION_GLOBAL_DEFAULT_LOCAL_PROVIDER_CAPABILITY_NAME = "org.wildfly.transactions.global-default-local-provider"; private static final String TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY_NAME = "org.wildfly.transactions.transaction-synchronization-registry"; - private static final String LEGACY_SECURITY_CAPABILITY_NAME = "org.wildfly.legacy-security"; - private static final String LEGACY_SECURITY_SERVER_MANAGER_CAPABILITY_NAME = "org.wildfly.legacy-security.server-security-manager"; - - private static final ServiceName SECURITY_DOMAIN_SERVICE = ServiceName.JBOSS.append("security", "security-domain"); /** * EJB 3.1 FR 13.3.1, the default transaction management type is container-managed transaction demarcation. @@ -315,11 +308,9 @@ public EJBComponentDescription(final String componentName, final String componen setNamingMode(ComponentNamingMode.CREATE); } - final boolean legacySecurityInstalled = legacySecurityAvailable(deploymentUnit); - getConfigurators().addFirst(new NamespaceConfigurator()); getConfigurators().add(new EjbJarConfigurationConfigurator()); - getConfigurators().add(new SecurityDomainDependencyConfigurator(this, legacySecurityInstalled)); + getConfigurators().add(new SecurityDomainDependencyConfigurator(this)); // setup a current invocation interceptor @@ -371,8 +362,6 @@ public void configure(final DeploymentPhaseContext context, final ComponentDescr if (ejbComponentDescription.getSecurityDomainServiceName() != null) { final HashMap elytronInterceptorFactories = getElytronInterceptorFactories(policyContextID, ejbComponentDescription.requiresJacc(), true); elytronInterceptorFactories.forEach((priority, elytronInterceptorFactory) -> configuration.addTimeoutViewInterceptor(elytronInterceptorFactory, priority)); - } else if (legacySecurityInstalled) { - configuration.addTimeoutViewInterceptor(new SecurityContextInterceptorFactory(securityRequired, policyContextID), InterceptorOrder.View.SECURITY_CONTEXT); } final Set classMethods = configuration.getClassIndex().getClassMethods(); for (final Method method : classMethods) { @@ -412,16 +401,6 @@ public void configureDependency(ServiceBuilder serviceBuilder, EJBComponentCr // setup ejb suspend handler dependency addEJBSuspendHandlerDependency(); - - if (legacySecurityInstalled) { - // setup dependency on ServerSecurityManager - addServerSecurityManagerDependency(); - } - } - - private static boolean legacySecurityAvailable(DeploymentUnit deploymentUnit) { - final CapabilityServiceSupport support = deploymentUnit.getAttachment(CAPABILITY_SERVICE_SUPPORT); - return support.hasCapability("org.wildfly.legacy-security"); } private static InterceptorFactory weaved(final Collection interceptorFactories) { @@ -650,27 +629,6 @@ public void configure(final DeploymentPhaseContext context, final ComponentDescr }); } - /** - * Sets up a {@link ComponentConfigurator} which then sets up the dependency on the ServerSecurityManager service for the {@link EJBComponentCreateService} - */ - protected void addServerSecurityManagerDependency() { - getConfigurators().add(new ComponentConfigurator() { - @Override - public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration componentConfiguration) throws DeploymentUnitProcessingException { - if (((EJBComponentDescription) description).getSecurityDomainServiceName() == null) { - final DeploymentUnit deploymentUnit = context.getDeploymentUnit(); - final CapabilityServiceSupport support = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT); - componentConfiguration.getCreateDependencies().add(new DependencyConfigurator() { - @Override - public void configureDependency(final ServiceBuilder serviceBuilder, final EJBComponentCreateService ejbComponentCreateService) throws DeploymentUnitProcessingException { - serviceBuilder.addDependency(support.getCapabilityServiceName(LEGACY_SECURITY_SERVER_MANAGER_CAPABILITY_NAME), ServerSecurityManager.class, ejbComponentCreateService.getServerSecurityManagerInjector()); - } - }); - } - } - }); - } - protected void setupSecurityInterceptors(final ViewDescription view) { // setup security interceptor for the component view.getConfigurators().add(new EJBSecurityViewConfigurator()); @@ -963,11 +921,9 @@ public void configure(DeploymentPhaseContext context, ComponentDescription descr private class SecurityDomainDependencyConfigurator implements ComponentConfigurator { private final EJBComponentDescription ejbComponentDescription; - private final boolean legacySecurityInstalled; - SecurityDomainDependencyConfigurator(final EJBComponentDescription ejbComponentDescription, final boolean legacySecurityInstalled) { + SecurityDomainDependencyConfigurator(final EJBComponentDescription ejbComponentDescription) { this.ejbComponentDescription = ejbComponentDescription; - this.legacySecurityInstalled = legacySecurityInstalled; } @Override @@ -987,11 +943,7 @@ public void configureDependency(ServiceBuilder serviceBuilder, Service invocationTask = () -> { - setConnection(remoteConnection); StartupCountdown.restore(frame); try { return asyncInterceptorContext.proceed(); } finally { StartupCountdown.restore(null); - clearConnection(); } }; final AsyncInvocationTask task = new AsyncInvocationTask(flag) { @@ -120,43 +110,17 @@ public Object processInvocation(final InterceptorContext context) throws Excepti final InterceptorContext asyncInterceptorContext = context.clone(); asyncInterceptorContext.putPrivateData(InvocationType.class, InvocationType.ASYNC); final CancellationFlag flag = new CancellationFlag(); - final SecurityContext securityContext; - if (WildFlySecurityManager.isChecking()) { - securityContext = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public SecurityContext run() { - return SecurityContextAssociation.getSecurityContext(); - } - }); - } else { - securityContext = SecurityContextAssociation.getSecurityContext(); - } - // clone the original security context so that changes to the original security context in a separate (caller/unrelated) thread doesn't affect - // the security context associated with the async invocation thread - final SecurityContext clonedSecurityContext; - if (securityContext instanceof JBossSecurityContext) { - clonedSecurityContext = (SecurityContext) ((JBossSecurityContext) securityContext).clone(); - } else { - // we can't do anything if it isn't a JBossSecurityContext so just use the original one - clonedSecurityContext = securityContext; - } - final RemoteConnection remoteConnection = getConnection(); + + final StartupCountdown.Frame frame = StartupCountdown.current(); final AsyncInvocationTask task = new AsyncInvocationTask(flag) { @Override protected Object runInvocation() throws Exception { - setSecurityContextOnAssociation(clonedSecurityContext); - setConnection(remoteConnection); StartupCountdown.restore(frame); try { return asyncInterceptorContext.proceed(); } finally { StartupCountdown.restore(null); - try { - clearSecurityContextOnAssociation(); - } finally { - clearConnection(); - } } } }; @@ -168,41 +132,6 @@ protected Object runInvocation() throws Exception { } } - private void setConnection(final RemoteConnection remoteConnection) { - if (WildFlySecurityManager.isChecking()) { - WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - @Override - public Void run() { - RemotingContext.setConnection(remoteConnection); - return null; - } - }); - } else { - RemotingContext.setConnection(remoteConnection); - } - } - - private void clearConnection() { - if (WildFlySecurityManager.isChecking()) { - WildFlySecurityManager.doUnchecked(new PrivilegedAction() { - @Override - public Void run() { - RemotingContext.clear(); - return null; - } - }); - } else { - RemotingContext.clear(); - } - } - private RemoteConnection getConnection() { - if(WildFlySecurityManager.isChecking()) { - return WildFlySecurityManager.doUnchecked((PrivilegedAction) () -> RemotingContext.getRemoteConnection()); - } else { - return RemotingContext.getRemoteConnection(); - } - } - private AsyncInvocationTask execute(SessionBeanComponent component, AsyncInvocationTask task) { // The interceptor runs in user application's context classloader. Triggering an execute via an executor service from here can potentially lead to // new thread creation which will assign themselves the context classloader of the parent thread (i.e. this thread). This effectively can lead to @@ -218,25 +147,5 @@ private AsyncInvocationTask execute(SessionBeanComponent component, AsyncInvocat return task; } - private static void setSecurityContextOnAssociation(final SecurityContext sc) { - AccessController.doPrivileged(new PrivilegedAction() { - - @Override - public Void run() { - SecurityContextAssociation.setSecurityContext(sc); - return null; - } - }); - } - - private static void clearSecurityContextOnAssociation() { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - SecurityContextAssociation.clearSecurityContext(); - return null; - } - }); - } } diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonComponentDescription.java b/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonComponentDescription.java index 25de4754d965..a8e9348d758f 100644 --- a/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonComponentDescription.java +++ b/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonComponentDescription.java @@ -22,6 +22,8 @@ package org.jboss.as.ejb3.component.singleton; +import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER; + import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; @@ -53,7 +55,6 @@ import org.jboss.as.ejb3.component.session.StatelessRemoteViewInstanceFactory; import org.jboss.as.ejb3.component.session.StatelessWriteReplaceInterceptor; import org.jboss.as.ejb3.deployment.EjbJarDescription; -import org.jboss.as.ejb3.security.SecurityContextInterceptorFactory; import org.jboss.as.ejb3.tx.EjbBMTInterceptor; import org.jboss.as.ejb3.tx.LifecycleCMTTxInterceptor; import org.jboss.as.ejb3.tx.TimerCMTTxInterceptor; @@ -129,8 +130,7 @@ public void configure(final DeploymentPhaseContext context, final ComponentDescr final HashMap elytronInterceptorFactories = getElytronInterceptorFactories(contextID, ejbComponentDescription.requiresJacc(), false); elytronInterceptorFactories.forEach((priority, elytronInterceptorFactory) -> configuration.addPostConstructInterceptor(elytronInterceptorFactory, priority)); } else if (definedSecurityDomain){ - ejbComponentDescription.setSecurityRequired(definedSecurityDomain); - configuration.addPostConstructInterceptor(new SecurityContextInterceptorFactory(definedSecurityDomain, false, contextID), InterceptorOrder.View.SECURITY_CONTEXT); + throw ROOT_LOGGER.legacySecurityUnsupported(); } } }); diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/logging/EjbLogger.java b/ejb3/src/main/java/org/jboss/as/ejb3/logging/EjbLogger.java index 43acc6d1d7b9..b8d6d07bf8ce 100644 --- a/ejb3/src/main/java/org/jboss/as/ejb3/logging/EjbLogger.java +++ b/ejb3/src/main/java/org/jboss/as/ejb3/logging/EjbLogger.java @@ -3250,4 +3250,8 @@ public interface EjbLogger extends BasicLogger { @LogMessage(level = WARN) @Message(id = 529, value = "Failed to retrieve info from database for timer: %s") void failedToRetrieveTimerInfo(final TimerImpl timer, @Cause Exception e); + + @Message(id = 530, value = "The deployment is configured to use legacy security which is no longer supported.") + IllegalStateException legacySecurityUnsupported(); + } diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/remote/AssociationImpl.java b/ejb3/src/main/java/org/jboss/as/ejb3/remote/AssociationImpl.java index c7aab3d01e5a..559460d14b16 100644 --- a/ejb3/src/main/java/org/jboss/as/ejb3/remote/AssociationImpl.java +++ b/ejb3/src/main/java/org/jboss/as/ejb3/remote/AssociationImpl.java @@ -39,7 +39,6 @@ import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.network.ClientMapping; import org.jboss.as.network.ProtocolSocketBinding; -import org.jboss.as.security.remoting.RemoteConnection; import org.jboss.ejb.client.Affinity; import org.jboss.ejb.client.ClusterAffinity; import org.jboss.ejb.client.EJBClientInvocationContext; @@ -59,7 +58,6 @@ import org.jboss.ejb.server.Request; import org.jboss.ejb.server.SessionOpenRequest; import org.jboss.invocation.InterceptorContext; -import org.jboss.remoting3.Connection; import org.wildfly.clustering.Registration; import org.wildfly.clustering.group.Group; import org.wildfly.clustering.registry.Registry; @@ -69,7 +67,6 @@ import org.wildfly.security.manager.WildFlySecurityManager; import javax.ejb.EJBException; -import javax.net.ssl.SSLSession; import java.io.IOException; import java.lang.reflect.Method; @@ -228,24 +225,6 @@ public CancelHandle receiveInvocationRequest(@NotNull final InvocationRequest in // invoke the method final Object result; - // the Remoting connection that is set here is only used for legacy purposes - Connection remotingConnection = invocationRequest.getProviderInterface(Connection.class); - if(remotingConnection != null) { - SecurityActions.remotingContextSetConnection(remotingConnection); - } else if (invocationRequest.getSecurityIdentity() != null) { - SecurityActions.remotingContextSetConnection(new RemoteConnection() { - @Override - public SSLSession getSslSession() { - return null; - } - - @Override - public SecurityIdentity getSecurityIdentity() { - return invocationRequest.getSecurityIdentity(); - } - }); - } - try { final Map contextDataHolder = new HashMap<>(); result = invokeMethod(componentView, invokedMethod, invocationRequest, requestContent, cancellationFlag, actualLocator, contextDataHolder); @@ -282,8 +261,6 @@ public SecurityIdentity getSecurityIdentity() { } invocationRequest.writeException(exceptionToWrite); return; - } finally { - SecurityActions.remotingContextClear(); } // invocation was successful if (! oneWay) try { diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/remote/SecurityActions.java b/ejb3/src/main/java/org/jboss/as/ejb3/remote/SecurityActions.java deleted file mode 100644 index f8fbfff4629b..000000000000 --- a/ejb3/src/main/java/org/jboss/as/ejb3/remote/SecurityActions.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2010, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.ejb3.remote; - -import java.security.PrivilegedAction; - -import org.jboss.as.security.remoting.RemoteConnection; -import org.jboss.as.security.remoting.RemotingContext; -import org.jboss.remoting3.Connection; -import org.wildfly.security.manager.WildFlySecurityManager; - -import static java.security.AccessController.doPrivileged; - -final class SecurityActions { - - private SecurityActions() { - // forbidden inheritance - } - - /** - * Set the Remoting Connection on the RemotingContext. - * - * @param connection - The Remoting connection. - */ - static void remotingContextSetConnection(final Connection connection) { - remotingContextAssociationActions().setConnection(connection); - } - - /** - * Set the Remoting Connection on the RemotingContext. - * - * @param connection - The Remoting connection. - */ - static void remotingContextSetConnection(final RemoteConnection connection) { - remoteContextAssociationActions().setConnection(connection); - } - - /** - * Clear the Remoting Connection on the RemotingContext. - */ - static void remotingContextClear() { - remotingContextAssociationActions().clear(); - } - - private static RemotingContextAssociationActions remotingContextAssociationActions() { - return ! WildFlySecurityManager.isChecking() ? RemotingContextAssociationActions.NON_PRIVILEGED - : RemotingContextAssociationActions.PRIVILEGED; - } - - private static RemoteContextAssociationActions remoteContextAssociationActions() { - return ! WildFlySecurityManager.isChecking() ? RemoteContextAssociationActions.NON_PRIVILEGED - : RemoteContextAssociationActions.PRIVILEGED; - } - private interface RemotingContextAssociationActions { - - void setConnection(final Connection connection); - - void clear(); - - RemotingContextAssociationActions NON_PRIVILEGED = new RemotingContextAssociationActions() { - - public void setConnection(Connection connection) { - RemotingContext.setConnection(connection); - } - - public void clear() { - RemotingContext.clear(); - } - }; - - RemotingContextAssociationActions PRIVILEGED = new RemotingContextAssociationActions() { - - private PrivilegedAction CLEAR_ACTION = new PrivilegedAction() { - - public Void run() { - NON_PRIVILEGED.clear(); - return null; - } - }; - - public void setConnection(final Connection connection) { - doPrivileged(new PrivilegedAction() { - - public Void run() { - NON_PRIVILEGED.setConnection(connection); - return null; - } - }); - - } - - @Override - public void clear() { - doPrivileged(CLEAR_ACTION); - } - }; - - } - - private interface RemoteContextAssociationActions { - - void setConnection(final RemoteConnection connection); - - void clear(); - - RemoteContextAssociationActions NON_PRIVILEGED = new RemoteContextAssociationActions() { - - public void setConnection(RemoteConnection connection) { - RemotingContext.setConnection(connection); - } - - public void clear() { - RemotingContext.clear(); - } - }; - - RemoteContextAssociationActions PRIVILEGED = new RemoteContextAssociationActions() { - - private PrivilegedAction CLEAR_ACTION = new PrivilegedAction() { - - public Void run() { - NON_PRIVILEGED.clear(); - return null; - } - }; - - public void setConnection(final RemoteConnection connection) { - doPrivileged(new PrivilegedAction() { - - public Void run() { - NON_PRIVILEGED.setConnection(connection); - return null; - } - }); - - } - - @Override - public void clear() { - doPrivileged(CLEAR_ACTION); - } - }; - - } -} diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/security/AuthorizationInterceptor.java b/ejb3/src/main/java/org/jboss/as/ejb3/security/AuthorizationInterceptor.java deleted file mode 100644 index 0dd09a287505..000000000000 --- a/ejb3/src/main/java/org/jboss/as/ejb3/security/AuthorizationInterceptor.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2011, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.ejb3.security; - -import java.lang.reflect.Method; -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.security.ProtectionDomain; -import java.util.HashSet; -import java.util.Set; - -import javax.security.jacc.PolicyContext; - -import org.jboss.as.core.security.ServerSecurityManager; -import org.jboss.as.ee.component.Component; -import org.jboss.as.ee.component.ComponentView; -import org.jboss.as.ejb3.logging.EjbLogger; -import org.jboss.as.ejb3.component.EJBComponent; -import org.jboss.as.ejb3.component.MethodIntf; -import org.jboss.invocation.Interceptor; -import org.jboss.invocation.InterceptorContext; -import org.jboss.metadata.ejb.spec.MethodInterfaceType; -import org.jboss.security.AnybodyPrincipal; -import org.jboss.security.NobodyPrincipal; -import org.jboss.security.SimplePrincipal; -import org.wildfly.security.manager.WildFlySecurityManager; - -/** - * Jakarta Enterprise Beans authorization interceptor responsible for handling invocation on Jakarta Enterprise Beans methods and doing the necessary authorization - * checks on the invoked method. - *

- * User: Jaikiran Pai - */ -public class AuthorizationInterceptor implements Interceptor { - - /** - * Jakarta Enterprise Beans method security metadata - */ - private final EJBMethodSecurityAttribute ejbMethodSecurityMetaData; - - /** - * The view class name to which this interceptor is applicable - */ - private final String viewClassName; - - /** - * The view method to which this interceptor is applicable - */ - private final Method viewMethod; - - /* - * The JACC contextID to be used by this interceptor. - */ - private final String contextID; - - public AuthorizationInterceptor(final EJBMethodSecurityAttribute ejbMethodSecurityMetaData, final String viewClassName, final Method viewMethod, final String contextID) { - if (ejbMethodSecurityMetaData == null) { - throw EjbLogger.ROOT_LOGGER.ejbMethodSecurityMetaDataIsNull(); - } - if (viewClassName == null || viewClassName.trim().isEmpty()) { - throw EjbLogger.ROOT_LOGGER.viewClassNameIsNull(); - } - if (viewMethod == null) { - throw EjbLogger.ROOT_LOGGER.viewMethodIsNull(); - } - this.ejbMethodSecurityMetaData = ejbMethodSecurityMetaData; - this.viewClassName = viewClassName; - this.viewMethod = viewMethod; - this.contextID = contextID; - } - - @Override - public Object processInvocation(InterceptorContext context) throws Exception { - final Component component = context.getPrivateData(Component.class); - if (component instanceof EJBComponent == false) { - throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class); - } - final Method invokedMethod = context.getMethod(); - final ComponentView componentView = context.getPrivateData(ComponentView.class); - final String viewClassOfInvokedMethod = componentView.getViewClass().getName(); - // shouldn't really happen if the interceptor was setup correctly. But let's be safe and do a check - if (!this.viewClassName.equals(viewClassOfInvokedMethod) || !this.viewMethod.equals(invokedMethod)) { - throw EjbLogger.ROOT_LOGGER.failProcessInvocation(this.getClass().getName(), invokedMethod, viewClassOfInvokedMethod, viewMethod, viewClassName); - } - final EJBComponent ejbComponent = (EJBComponent) component; - final ServerSecurityManager securityManager = ejbComponent.getSecurityManager(); - final MethodInterfaceType methodIntfType = this.getMethodInterfaceType(componentView.getPrivateData(MethodIntf.class)); - - // set the JACC contextID before calling the security manager. - final String previousContextID = setContextID(this.contextID); - try { - if(WildFlySecurityManager.isChecking()) { - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public ProtectionDomain run() { - - if (!securityManager.authorize(ejbComponent.getComponentName(), componentView.getProxyClass().getProtectionDomain().getCodeSource(), - methodIntfType.name(), AuthorizationInterceptor.this.viewMethod, AuthorizationInterceptor.this.getMethodRolesAsPrincipals(), AuthorizationInterceptor.this.contextID)) { - throw EjbLogger.ROOT_LOGGER.invocationOfMethodNotAllowed(invokedMethod,ejbComponent.getComponentName()); - } - return null; - } - }); - } catch (PrivilegedActionException e) { - throw e.getException(); - } - } else { - if (!securityManager.authorize(ejbComponent.getComponentName(), componentView.getProxyClass().getProtectionDomain().getCodeSource(), - methodIntfType.name(), this.viewMethod, this.getMethodRolesAsPrincipals(), this.contextID)) { - throw EjbLogger.ROOT_LOGGER.invocationOfMethodNotAllowed(invokedMethod,ejbComponent.getComponentName()); - } - } - // successful authorization, let the invocation proceed - return context.proceed(); - } - finally { - // reset the previous JACC contextID. - setContextID(previousContextID); - } - } - - /** - *

- * Returns the method roles as a set of {@code Principal} instances. All roles specified in the method-permissions or - * via {@code RolesAllowed} for this method are wrapped by a {@code SimplePrincipal}. If the method has been added to - * the exclude-list or annotated with {@code DenyAll}, a NOBODY_PRINCIPAL is returned. If the method has been added - * to the unchecked list or annotated with {@code PermitAll}, an ANYBODY_PRINCIPAL is returned. - *

- * - * @return the constructed set of role principals. - */ - protected Set getMethodRolesAsPrincipals() { - Set methodRoles = new HashSet(); - if (this.ejbMethodSecurityMetaData.isDenyAll()) - methodRoles.add(NobodyPrincipal.NOBODY_PRINCIPAL); - else if (this.ejbMethodSecurityMetaData.isPermitAll()) - methodRoles.add(AnybodyPrincipal.ANYBODY_PRINCIPAL); - else { - for (String role : this.ejbMethodSecurityMetaData.getRolesAllowed()) - methodRoles.add(new SimplePrincipal(role)); - } - return methodRoles; - } - - /** - *

- * Gets the {@code MethodInterfaceType} that corresponds to the specified {@code MethodIntf}. - *

- * - * @param viewType the {@code MethodIntf} type to be converted. - * @return the converted type or {@code null} if the type cannot be converted. - */ - protected MethodInterfaceType getMethodInterfaceType(MethodIntf viewType) { - switch (viewType) { - case HOME: - return MethodInterfaceType.Home; - case LOCAL_HOME: - return MethodInterfaceType.LocalHome; - case SERVICE_ENDPOINT: - return MethodInterfaceType.ServiceEndpoint; - case LOCAL: - return MethodInterfaceType.Local; - case REMOTE: - return MethodInterfaceType.Remote; - case TIMER: - return MethodInterfaceType.Timer; - case MESSAGE_ENDPOINT: - return MethodInterfaceType.MessageEndpoint; - default: - return null; - } - } - - /** - *

- * Sets the JACC contextID using a privileged action and returns the previousID from the {@code PolicyContext}. - *

- * - * @param contextID the JACC contextID to be set. - * @return the previous contextID as retrieved from the {@code PolicyContext}. - */ - protected String setContextID(final String contextID) { - if (! WildFlySecurityManager.isChecking()) { - final String previousID = PolicyContext.getContextID(); - PolicyContext.setContextID(contextID); - return previousID; - } else { - final PrivilegedAction action = new SetContextIDAction(contextID); - return AccessController.doPrivileged(action); - } - } - - /** - * PrivilegedAction that sets the {@code PolicyContext} id. - */ - private static class SetContextIDAction implements PrivilegedAction { - - private String contextID; - - SetContextIDAction(final String contextID) { - this.contextID = contextID; - } - - @Override - public String run() { - final String previousID = PolicyContext.getContextID(); - PolicyContext.setContextID(this.contextID); - return previousID; - } - } -} diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/security/EJBSecurityViewConfigurator.java b/ejb3/src/main/java/org/jboss/as/ejb3/security/EJBSecurityViewConfigurator.java index 5bab167c831c..a680a633ce1f 100644 --- a/ejb3/src/main/java/org/jboss/as/ejb3/security/EJBSecurityViewConfigurator.java +++ b/ejb3/src/main/java/org/jboss/as/ejb3/security/EJBSecurityViewConfigurator.java @@ -158,8 +158,8 @@ public void configure(DeploymentPhaseContext context, ComponentConfiguration com if (elytronSecurityDomain) { final HashMap elytronInterceptorFactories = ejbComponentDescription.getElytronInterceptorFactories(contextID, ejbComponentDescription.requiresJacc(), true); elytronInterceptorFactories.forEach((priority, elytronInterceptorFactory) -> viewConfiguration.addViewInterceptor(elytronInterceptorFactory, priority)); - } else { - viewConfiguration.addViewInterceptor(new SecurityContextInterceptorFactory(securityRequired, true, contextID), InterceptorOrder.View.SECURITY_CONTEXT); + } else if (securityRequired) { + throw ROOT_LOGGER.legacySecurityUnsupported(); } // now add the authorization interceptor if the bean has *any* security metadata applicable if (securityRequired) { @@ -178,8 +178,7 @@ public void configure(DeploymentPhaseContext context, ComponentConfiguration com if (elytronSecurityDomain) { viewConfiguration.addViewInterceptor(viewMethod, new ImmediateInterceptorFactory(RolesAllowedInterceptor.DENY_ALL), InterceptorOrder.View.EJB_SECURITY_AUTHORIZATION_INTERCEPTOR); } else { - final Interceptor authorizationInterceptor = new AuthorizationInterceptor(EJBMethodSecurityAttribute.denyAll(), viewClassName, viewMethod, contextID); - viewConfiguration.addViewInterceptor(viewMethod, new ImmediateInterceptorFactory(authorizationInterceptor), InterceptorOrder.View.EJB_SECURITY_AUTHORIZATION_INTERCEPTOR); + throw ROOT_LOGGER.legacySecurityUnsupported(); } } } @@ -260,7 +259,7 @@ private boolean handlePermissions(String contextID, ComponentConfiguration compo } } } else { - authorizationInterceptor = new AuthorizationInterceptor(ejbMethodSecurityMetaData, viewClassName, viewMethod, contextID); + throw ROOT_LOGGER.legacySecurityUnsupported(); } viewConfiguration.addViewInterceptor(viewMethod, new ImmediateInterceptorFactory(authorizationInterceptor), InterceptorOrder.View.EJB_SECURITY_AUTHORIZATION_INTERCEPTOR); diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptor.java b/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptor.java deleted file mode 100644 index ed26805d625c..000000000000 --- a/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptor.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright (c) 2011, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.as.ejb3.security; - -import java.security.AccessController; -import java.security.PrivilegedAction; - -import javax.ejb.EJBAccessException; -import javax.security.jacc.PolicyContext; - -import org.jboss.invocation.Interceptor; -import org.jboss.invocation.InterceptorContext; -import org.jboss.security.SecurityRolesAssociation; -import org.wildfly.security.manager.WildFlySecurityManager; - -import static java.security.AccessController.doPrivileged; - -/** - * Establish the security context. - * - * @author Carlo de Wolf - * @author Anil Saldhana - */ -public class SecurityContextInterceptor implements Interceptor { - private final PrivilegedAction pushAction; - private final PrivilegedAction popAction; - private final String policyContextID; - - public SecurityContextInterceptor(final SecurityContextInterceptorHolder holder) { - this.pushAction = new PrivilegedAction() { - @Override - public Void run() { - holder.securityManager.push(holder.securityDomain); - try { - if (holder.skipAuthentication == false) { - holder.securityManager.authenticate(holder.runAs, holder.runAsPrincipal, holder.extraRoles); - } - if (holder.principalVsRolesMap != null) { - SecurityRolesAssociation.setSecurityRoles(holder.principalVsRolesMap); - } - } catch (Throwable t) { - // undo the push actions on failure - if (holder.principalVsRolesMap != null) { - // clear the threadlocal - SecurityRolesAssociation.setSecurityRoles(null); - } - holder.securityManager.pop(); - - if (t instanceof SecurityException) { - throw new EJBAccessException(t.getMessage()); - } - throw t; - } - return null; - } - }; - this.popAction = new PrivilegedAction() { - @Override - public Void run() { - if (holder.principalVsRolesMap != null) { - // Clear the threadlocal - SecurityRolesAssociation.setSecurityRoles(null); - } - holder.securityManager.pop(); - return null; - } - }; - this.policyContextID = holder.policyContextID; - } - - @Override - public Object processInvocation(final InterceptorContext context) throws Exception { - // TODO - special cases need to be handled where SecurityContext not established or minimal unauthenticated principal context instead. - String previousContextID = this.setContextID(this.policyContextID); - if (WildFlySecurityManager.isChecking()) { - doPrivileged(pushAction); - } else { - pushAction.run(); - } - try { - return context.proceed(); - } finally { - this.setContextID(previousContextID); - if (WildFlySecurityManager.isChecking()) { - doPrivileged(popAction); - } else { - popAction.run(); - } - } - } - - /** - *

- * Sets the JACC contextID using a privileged action and returns the previousID from the {@code PolicyContext}. - *

- * - * @param contextID the JACC contextID to be set. - * @return the previous contextID as retrieved from the {@code PolicyContext}. - */ - protected String setContextID(final String contextID) { - if (! WildFlySecurityManager.isChecking()) { - final String previousID = PolicyContext.getContextID(); - PolicyContext.setContextID(contextID); - return previousID; - } else { - final PrivilegedAction action = new SetContextIDAction(contextID); - return AccessController.doPrivileged(action); - } - } - - /** - * PrivilegedAction that sets the {@code PolicyContext} id. - */ - private static class SetContextIDAction implements PrivilegedAction { - - private String contextID; - - SetContextIDAction(final String contextID) { - this.contextID = contextID; - } - - @Override - public String run() { - final String previousID = PolicyContext.getContextID(); - PolicyContext.setContextID(this.contextID); - return previousID; - } - } -} diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptorFactory.java b/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptorFactory.java deleted file mode 100644 index 5328b1c6ca8d..000000000000 --- a/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptorFactory.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright (c) 2011, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.as.ejb3.security; - -import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER; - -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; - -import org.jboss.as.core.security.ServerSecurityManager; -import org.jboss.as.ee.component.Component; -import org.jboss.as.ee.component.ComponentInterceptorFactory; -import org.jboss.as.ejb3.logging.EjbLogger; -import org.jboss.as.ejb3.component.EJBComponent; -import org.jboss.invocation.Interceptor; -import org.jboss.invocation.InterceptorFactoryContext; -import org.jboss.metadata.javaee.spec.SecurityRolesMetaData; -/** - * @author Carlo de Wolf - * @author Anil Saldhana - */ -public class SecurityContextInterceptorFactory extends ComponentInterceptorFactory { - - private static final String DEFAULT_DOMAIN = "other"; - - private final boolean securityRequired; - private final boolean propagateSecurity; - private final String policyContextID; - - public SecurityContextInterceptorFactory(final boolean securityRequired, final String policyContextID) { - this(securityRequired, true, policyContextID); - } - - public SecurityContextInterceptorFactory(final boolean securityRequired, final boolean propagateSecurity, final String policyContextID) { - this.securityRequired = securityRequired; - this.propagateSecurity = propagateSecurity; - this.policyContextID = policyContextID; - } - - @Override - protected Interceptor create(final Component component, final InterceptorFactoryContext context) { - if (component instanceof EJBComponent == false) { - throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class); - } - final EJBComponent ejbComponent = (EJBComponent) component; - final ServerSecurityManager securityManager; - if(propagateSecurity) { - securityManager = ejbComponent.getSecurityManager(); - } else { - securityManager = ((Supplier) ejbComponent.getSecurityManager()).get(); - } - final EJBSecurityMetaData securityMetaData = ejbComponent.getSecurityMetaData(); - String securityDomainName = securityMetaData.getSecurityDomainName(); - if (securityDomainName == null) { - securityDomainName = DEFAULT_DOMAIN; - } - if (ROOT_LOGGER.isTraceEnabled()) { - ROOT_LOGGER.trace("Using security domain: " + securityDomainName + " for Jakarta Enterprise Beans " + ejbComponent.getComponentName()); - } - final String runAs = securityMetaData.getRunAs(); - // TODO - We should do something with DeclaredRoles although it never has much meaning in JBoss AS - final String runAsPrincipal = securityMetaData.getRunAsPrincipal(); - final SecurityRolesMetaData securityRoles = securityMetaData.getSecurityRoles(); - Set extraRoles = null; - Map> principalVsRolesMap = null; - if (securityRoles != null) { - principalVsRolesMap = securityRoles.getPrincipalVersusRolesMap(); - if (runAsPrincipal != null) - extraRoles = securityRoles.getSecurityRoleNamesByPrincipal(runAsPrincipal); - } - SecurityContextInterceptorHolder holder = new SecurityContextInterceptorHolder(); - holder.setSecurityManager(securityManager).setSecurityDomain(securityDomainName) - .setRunAs(runAs).setRunAsPrincipal(runAsPrincipal).setPolicyContextID(this.policyContextID) - .setExtraRoles(extraRoles).setPrincipalVsRolesMap(principalVsRolesMap) - .setSkipAuthentication(securityRequired == false); - - return new SecurityContextInterceptor(holder); - } -} diff --git a/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptorHolder.java b/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptorHolder.java index 61be225e967e..175038deb844 100644 --- a/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptorHolder.java +++ b/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityContextInterceptorHolder.java @@ -24,15 +24,12 @@ import java.util.Map; import java.util.Set; -import org.jboss.as.core.security.ServerSecurityManager; - /** * A simple transfer object * * @author anil saldhana */ class SecurityContextInterceptorHolder { - ServerSecurityManager securityManager; String securityDomain, runAs, runAsPrincipal; String policyContextID; Set extraRoles; @@ -42,11 +39,6 @@ class SecurityContextInterceptorHolder { public SecurityContextInterceptorHolder() { } - public SecurityContextInterceptorHolder setSecurityManager(ServerSecurityManager ssm) { - this.securityManager = ssm; - return this; - } - public SecurityContextInterceptorHolder setSecurityDomain(String sd) { this.securityDomain = sd; return this; From 144d802de2ab177f4bd305f84c4013375248178a Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Wed, 24 Nov 2021 14:09:40 +0000 Subject: [PATCH 07/11] [WFLY-15733] / [WFLY-15356] Remove security-plugins dependency from messaging. --- .../apache/activemq/artemis/main/module.xml | 1 - .../apache/activemq/artemis/main/module.xml | 1 - .../messaging-activemq/main/module.xml | 1 - .../activemq/logging/MessagingLogger.java | 3 + messaging-activemq/subsystem/pom.xml | 6 -- .../activemq/ActiveMQServerService.java | 8 +-- .../messaging/activemq/ServerAdd.java | 13 +--- .../activemq/WildFlySecurityManager.java | 71 ++----------------- 8 files changed, 12 insertions(+), 92 deletions(-) diff --git a/ee-9/feature-pack/src/main/resources/modules/system/layers/base/org/apache/activemq/artemis/main/module.xml b/ee-9/feature-pack/src/main/resources/modules/system/layers/base/org/apache/activemq/artemis/main/module.xml index 1c0e45eb17bd..c1beac89116f 100644 --- a/ee-9/feature-pack/src/main/resources/modules/system/layers/base/org/apache/activemq/artemis/main/module.xml +++ b/ee-9/feature-pack/src/main/resources/modules/system/layers/base/org/apache/activemq/artemis/main/module.xml @@ -63,7 +63,6 @@ - diff --git a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/apache/activemq/artemis/main/module.xml b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/apache/activemq/artemis/main/module.xml index 51612138a480..b6a1bf8a5d19 100644 --- a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/apache/activemq/artemis/main/module.xml +++ b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/apache/activemq/artemis/main/module.xml @@ -63,7 +63,6 @@ - diff --git a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/wildfly/extension/messaging-activemq/main/module.xml b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/wildfly/extension/messaging-activemq/main/module.xml index f92ff290f214..c7daa52a98f6 100644 --- a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/wildfly/extension/messaging-activemq/main/module.xml +++ b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/wildfly/extension/messaging-activemq/main/module.xml @@ -75,7 +75,6 @@ - diff --git a/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/logging/MessagingLogger.java b/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/logging/MessagingLogger.java index 11b8af309869..ef0bf4fcca09 100644 --- a/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/logging/MessagingLogger.java +++ b/messaging-activemq/injection/src/main/java/org/wildfly/extension/messaging/activemq/logging/MessagingLogger.java @@ -876,4 +876,7 @@ public interface MessagingLogger extends BasicLogger { @Message(id = 103, value = "Broker is not started. It cannot be managed yet.") IllegalStateException brokerNotStarted(); + @Message(id = 104, value = "Legacy security is no longer supported.") + IllegalStateException legacySecurityUnsupported(); + } diff --git a/messaging-activemq/subsystem/pom.xml b/messaging-activemq/subsystem/pom.xml index 3f90a9628659..d68816c6a969 100644 --- a/messaging-activemq/subsystem/pom.xml +++ b/messaging-activemq/subsystem/pom.xml @@ -196,12 +196,6 @@ wildfly-clustering-spi - - ${project.groupId} - wildfly-security-plugins - provided - - ${project.groupId} wildfly-web-common diff --git a/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ActiveMQServerService.java b/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ActiveMQServerService.java index a92be896d1ae..87a6458fd8b5 100644 --- a/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ActiveMQServerService.java +++ b/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ActiveMQServerService.java @@ -56,7 +56,6 @@ import org.jboss.as.network.ManagedBinding; import org.jboss.as.network.OutboundSocketBinding; import org.jboss.as.network.SocketBinding; -import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; @@ -110,8 +109,6 @@ class ActiveMQServerService implements Service { private final Map> commandDispatcherFactories; // Supplier for Elytron SecurityDomain private final Optional> elytronSecurityDomain; - // Supplier for legacy SecurityDomainContext - private final Optional> securityDomainContext; // credential source injectors private Map>> bridgeCredentialSource = new HashMap<>(); @@ -128,7 +125,6 @@ public ActiveMQServerService(Configuration configuration, Map> commandDispatcherFactories, Map clusterNames, Optional> elytronSecurityDomain, - Optional> securityDomainContext, Optional> mbeanServer, Optional> dataSource) { this.configuration = configuration; @@ -137,7 +133,6 @@ public ActiveMQServerService(Configuration configuration, this.mbeanServer = mbeanServer; this.pathManager = pathManager; this.elytronSecurityDomain = elytronSecurityDomain; - this.securityDomainContext = securityDomainContext; this.incomingInterceptors = incomingInterceptors; this.outgoingInterceptors = outgoingInterceptors; this.socketBindings = socketBindings; @@ -252,8 +247,7 @@ public synchronized void start(final StartContext context) throws StartException if (elytronSecurityDomain.isPresent()) { securityManager = new ElytronSecurityManager(elytronSecurityDomain.get().get()); } else { - assert securityDomainContext.isPresent(); - securityManager = new WildFlySecurityManager(securityDomainContext.get().get()); + securityManager = new WildFlySecurityManager(); } // insert possible credential source hold passwords diff --git a/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ServerAdd.java b/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ServerAdd.java index f86aa80e7d2c..88f9ce9dd762 100644 --- a/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ServerAdd.java +++ b/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/ServerAdd.java @@ -21,6 +21,8 @@ */ package org.wildfly.extension.messaging.activemq; +import static org.wildfly.extension.messaging.activemq.logging.MessagingLogger.ROOT_LOGGER; + import static java.util.concurrent.TimeUnit.SECONDS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PATH; import static org.jboss.as.controller.security.CredentialReference.handleCredentialReferenceUpdate; @@ -105,7 +107,6 @@ import static org.wildfly.extension.messaging.activemq.ServerDefinition.PERSIST_DELIVERY_COUNT_BEFORE_DELIVERY; import static org.wildfly.extension.messaging.activemq.ServerDefinition.PERSIST_ID_CACHE; import static org.wildfly.extension.messaging.activemq.ServerDefinition.SCHEDULED_THREAD_POOL_MAX_SIZE; -import static org.wildfly.extension.messaging.activemq.ServerDefinition.SECURITY_DOMAIN; import static org.wildfly.extension.messaging.activemq.ServerDefinition.SECURITY_ENABLED; import static org.wildfly.extension.messaging.activemq.ServerDefinition.SECURITY_INVALIDATION_INTERVAL; import static org.wildfly.extension.messaging.activemq.ServerDefinition.SERVER_DUMP_INTERVAL; @@ -158,7 +159,6 @@ import org.jboss.as.controller.services.path.PathManager; import org.jboss.as.network.OutboundSocketBinding; import org.jboss.as.network.SocketBinding; -import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.modules.Module; @@ -329,18 +329,12 @@ public void execute(OperationContext context, ModelNode operation) throws Operat // Inject a reference to the Elytron security domain if one has been defined. Optional> elytronSecurityDomain = Optional.empty(); // legacy security - Optional> securityDomainContext = Optional.empty(); final ModelNode elytronSecurityDomainModel = ELYTRON_DOMAIN.resolveModelAttribute(context, model); if (elytronSecurityDomainModel.isDefined()) { ServiceName elytronDomainCapability = context.getCapabilityServiceName(ELYTRON_DOMAIN_CAPABILITY, elytronSecurityDomainModel.asString(), SecurityDomain.class); elytronSecurityDomain = Optional.of(serviceBuilder.requires(elytronDomainCapability)); } else { - // Add legacy security - String domain = SECURITY_DOMAIN.resolveModelAttribute(context, model).asString(); - securityDomainContext = Optional.of(serviceBuilder.requires(SECURITY_DOMAIN_SERVICE.append(domain))); - // WFLY-6652 / WFLY-10292 this dependency ensures that Artemis will be able to destroy any queues created on behalf of a - // pooled-connection-factory client during server stop - serviceBuilder.requires(SECURITY_BOOTSTRAP_SERVICE); + throw ROOT_LOGGER.legacySecurityUnsupported(); } List incomingInterceptors = processInterceptors(INCOMING_INTERCEPTORS.resolveModelAttribute(context, operation)); @@ -456,7 +450,6 @@ public void execute(OperationContext context, ModelNode operation) throws Operat commandDispatcherFactories, clusterNames, elytronSecurityDomain, - securityDomainContext, mbeanServer, dataSource ); diff --git a/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/WildFlySecurityManager.java b/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/WildFlySecurityManager.java index 0aa65a08ac6f..dbd060a461ea 100644 --- a/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/WildFlySecurityManager.java +++ b/messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/WildFlySecurityManager.java @@ -22,30 +22,18 @@ package org.wildfly.extension.messaging.activemq; +import java.util.Set; + import org.apache.activemq.artemis.core.security.CheckType; import org.apache.activemq.artemis.core.security.Role; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; import org.wildfly.extension.messaging.activemq.logging.MessagingLogger; -import org.jboss.as.security.plugins.SecurityDomainContext; -import org.jboss.security.SecurityContext; -import org.jboss.security.SecurityContextAssociation; -import org.jboss.security.SecurityContextFactory; -import org.jboss.security.SimplePrincipal; - -import javax.security.auth.Subject; -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.util.HashSet; -import java.util.Set; public class WildFlySecurityManager implements ActiveMQSecurityManager { - private SecurityDomainContext securityDomainContext; private String defaultUser = null; private String defaultPassword = null; - public WildFlySecurityManager(SecurityDomainContext sdc) { - securityDomainContext = sdc; + public WildFlySecurityManager() { defaultUser = DefaultCredentials.getUsername(); defaultPassword = DefaultCredentials.getPassword(); } @@ -55,10 +43,7 @@ public boolean validateUser(String username, String password) { if (defaultUser.equals(username) && defaultPassword.equals(password)) return true; - if (securityDomainContext == null) - throw MessagingLogger.ROOT_LOGGER.securityDomainContextNotSet(); - - return securityDomainContext.getAuthenticationManager().isValid(new SimplePrincipal(username), password, new Subject()); + throw MessagingLogger.ROOT_LOGGER.legacySecurityUnsupported(); } @Override @@ -66,52 +51,6 @@ public boolean validateUserAndRole(final String username, final String password, if (defaultUser.equals(username) && defaultPassword.equals(password)) return true; - if (securityDomainContext == null) - throw MessagingLogger.ROOT_LOGGER.securityDomainContextNotSet(); - - final Subject subject = new Subject(); - - // The authentication call here changes the subject and that subject must be used later. That is why we don't call validateUser(String, String) here. - boolean authenticated = securityDomainContext.getAuthenticationManager().isValid(new SimplePrincipal(username), password, subject); - - if (authenticated) { - authenticated = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Boolean run() { - final SimplePrincipal principal = new SimplePrincipal(username); - - // push a new security context if there is not one. - final SecurityContext currentSecurityContext = SecurityContextAssociation.getSecurityContext(); - final SecurityContext securityContext; - if (currentSecurityContext == null) { - try { - securityContext = SecurityContextFactory.createSecurityContext(principal, password, subject, securityDomainContext.getAuthenticationManager().getSecurityDomain()); - } catch (Exception e) { - throw new RuntimeException(e); - } - } else { - securityContext = currentSecurityContext; - securityContext.getUtil().createSubjectInfo(principal, password, subject); - } - SecurityContextAssociation.setSecurityContext(securityContext); - - final Set principals = new HashSet(); - for (Role role : roles) { - if (checkType.hasRole(role)) { - principals.add(new SimplePrincipal(role.getName())); - } - } - - final boolean authenticated = securityDomainContext.getAuthorizationManager().doesUserHaveRole(new SimplePrincipal(username), principals); - - // restore the previous security context if any - SecurityContextAssociation.setSecurityContext(currentSecurityContext); - - return authenticated; - } - }); - } - - return authenticated; + throw MessagingLogger.ROOT_LOGGER.legacySecurityUnsupported(); } } From 7d5fdf1f90fe952f59d373c5935df3a526214985 Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Wed, 24 Nov 2021 14:27:41 +0000 Subject: [PATCH 08/11] [WFLY-15743] / [WFLY-15356] Remove security-plugins dependency from weld. --- .../layers/base/org/jboss/as/weld/main/module.xml | 1 - weld/subsystem/pom.xml | 5 ----- .../services/bootstrap/WeldSecurityServices.java | 12 +----------- 3 files changed, 1 insertion(+), 17 deletions(-) diff --git a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/weld/main/module.xml b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/weld/main/module.xml index 50d1d98382f5..903426d23bae 100644 --- a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/weld/main/module.xml +++ b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/weld/main/module.xml @@ -41,7 +41,6 @@ - diff --git a/weld/subsystem/pom.xml b/weld/subsystem/pom.xml index c1dee4124a43..2091cecd1ef2 100644 --- a/weld/subsystem/pom.xml +++ b/weld/subsystem/pom.xml @@ -69,11 +69,6 @@ wildfly-ee - - ${project.groupId} - wildfly-security-plugins - - ${project.groupId} wildfly-naming diff --git a/weld/subsystem/src/main/java/org/jboss/as/weld/services/bootstrap/WeldSecurityServices.java b/weld/subsystem/src/main/java/org/jboss/as/weld/services/bootstrap/WeldSecurityServices.java index e2c52388cd4e..514aa54c8f4d 100644 --- a/weld/subsystem/src/main/java/org/jboss/as/weld/services/bootstrap/WeldSecurityServices.java +++ b/weld/subsystem/src/main/java/org/jboss/as/weld/services/bootstrap/WeldSecurityServices.java @@ -27,7 +27,6 @@ import java.util.function.Consumer; import java.util.function.Supplier; -import org.jboss.as.core.security.ServerSecurityManager; import org.jboss.as.weld.ServiceNames; import org.jboss.as.weld.logging.WeldLogger; import org.jboss.msc.Service; @@ -76,16 +75,7 @@ public Principal getPrincipal() { return elytronDomain.getCurrentSecurityIdentity().getPrincipal(); } - // Use 'Object' initially to avoid loading ServerSecurityManager (which may not be present) - // until we know for sure we need it. - final Object securityManager = securityManagerSupplier != null ? securityManagerSupplier.get() : null; - if (securityManager == null) - throw WeldLogger.ROOT_LOGGER.securityNotEnabled(); - if (WildFlySecurityManager.isChecking()) { - return AccessController.doPrivileged((PrivilegedAction) ((ServerSecurityManager) securityManager)::getCallerPrincipal); - } else { - return ((ServerSecurityManager)securityManager).getCallerPrincipal(); - } + throw WeldLogger.ROOT_LOGGER.securityNotEnabled(); } @Override From 6c41e2046596a808e48d4db0cf68c72fc42f2dc5 Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Wed, 24 Nov 2021 15:01:02 +0000 Subject: [PATCH 09/11] [WFLY-15743] / [WFLY-15356] Also remove the dependency from the transformed subsystem. --- ee-9/source-transform/weld/subsystem/pom.xml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ee-9/source-transform/weld/subsystem/pom.xml b/ee-9/source-transform/weld/subsystem/pom.xml index cf90b8c6380c..fca079450bc3 100644 --- a/ee-9/source-transform/weld/subsystem/pom.xml +++ b/ee-9/source-transform/weld/subsystem/pom.xml @@ -201,10 +201,7 @@ test - - ${project.groupId} - wildfly-security-plugins - + ${project.groupId} From 6535911c72ab8a305a6dad593cc6adee91443efe Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Wed, 24 Nov 2021 15:41:33 +0000 Subject: [PATCH 10/11] [WFLY-15356] Remove the security-plugins module. --- pom.xml | 6 - security/plugins/pom.xml | 109 -- .../core/security/AbstractRealmPrincipal.java | 77 - .../as/core/security/AccountPrincipal.java | 32 - .../as/core/security/GroupPrincipal.java | 32 - .../jboss/as/core/security/RealmGroup.java | 41 - .../as/core/security/RealmPrincipal.java | 34 - .../org/jboss/as/core/security/RealmRole.java | 38 - .../org/jboss/as/core/security/RealmUser.java | 44 - .../jboss/as/core/security/RolePrincipal.java | 34 - .../core/security/SecurityRealmPrincipal.java | 71 - .../core/security/ServerSecurityManager.java | 63 - .../as/core/security/SimplePrincipal.java | 62 - .../core/security/api/AccountPrincipal.java | 34 - .../as/core/security/api/GroupPrincipal.java | 32 - .../as/core/security/api/RealmPrincipal.java | 41 - .../as/core/security/api/UserPrincipal.java | 32 - .../as/security/_private/SecurityLogger.java | 59 - .../security/lru/ConcurrentDirectDeque.java | 62 - .../lru/FastConcurrentDirectDeque.java | 1528 ----------------- .../org/jboss/as/security/lru/LRUCache.java | 391 ----- .../lru/PortableConcurrentDirectDeque.java | 1476 ---------------- .../jboss/as/security/lru/RemoveCallback.java | 10 - .../plugins/AuthenticationCacheFactory.java | 43 - .../DefaultAuthenticationCacheFactory.java | 50 - .../plugins/JNDIBasedSecurityManagement.java | 427 ----- .../plugins/ModuleClassLoaderLocator.java | 143 -- .../as/security/plugins/SecurityActions.java | 129 -- .../plugins/SecurityDomainContext.java | 99 -- .../security/remoting/RemoteConnection.java | 40 - .../RemotingConnectionCredential.java | 90 - .../as/security/remoting/RemotingContext.java | 122 -- .../remoting/RemotingLoginModule.java | 175 -- .../security/remoting/RemotingPermission.java | 107 -- .../as/security/remoting/SecurityActions.java | 77 - security/pom.xml | 1 - servlet-feature-pack/common/pom.xml | 11 - .../servlet-feature-pack-common-licenses.xml | 11 - .../jboss/as/security-plugins/main/module.xml | 48 - testsuite/integration/basic/pom.xml | 5 - 40 files changed, 5886 deletions(-) delete mode 100644 security/plugins/pom.xml delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/AbstractRealmPrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/AccountPrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/GroupPrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/RealmGroup.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/RealmPrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/RealmRole.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/RealmUser.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/RolePrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/SecurityRealmPrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/ServerSecurityManager.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/SimplePrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/api/AccountPrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/api/GroupPrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/api/RealmPrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/core/security/api/UserPrincipal.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/_private/SecurityLogger.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/lru/ConcurrentDirectDeque.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/lru/FastConcurrentDirectDeque.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/lru/LRUCache.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/lru/PortableConcurrentDirectDeque.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/lru/RemoveCallback.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/plugins/AuthenticationCacheFactory.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/plugins/DefaultAuthenticationCacheFactory.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/plugins/JNDIBasedSecurityManagement.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/plugins/ModuleClassLoaderLocator.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/plugins/SecurityActions.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/plugins/SecurityDomainContext.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/remoting/RemoteConnection.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingConnectionCredential.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingContext.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingLoginModule.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingPermission.java delete mode 100644 security/plugins/src/main/java/org/jboss/as/security/remoting/SecurityActions.java delete mode 100644 servlet-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/security-plugins/main/module.xml diff --git a/pom.xml b/pom.xml index 00060a4837dc..e43adfab0c02 100644 --- a/pom.xml +++ b/pom.xml @@ -1406,12 +1406,6 @@ - - ${ee.maven.groupId} - wildfly-security-plugins - ${ee.maven.version} - - ${ee.maven.groupId} wildfly-servlet-dist diff --git a/security/plugins/pom.xml b/security/plugins/pom.xml deleted file mode 100644 index 9c1d95de8944..000000000000 --- a/security/plugins/pom.xml +++ /dev/null @@ -1,109 +0,0 @@ - - - - - 4.0.0 - - - org.wildfly - wildfly-security-parent - - 26.0.0.Beta1-SNAPSHOT - ../pom.xml - - - wildfly-security-plugins - jar - - WildFly: Security Subsystem Plugins - - - - org.jboss.logging - jboss-logging-annotations - - provided - true - - - - org.jboss.logging - jboss-logging-processor - - provided - true - - - - org.jboss.modules - jboss-modules - - - - org.jboss.remoting - jboss-remoting - - - - org.jboss.spec.javax.security.jacc - jboss-jacc-api_1.5_spec - - - - org.picketbox - picketbox - - - - org.picketbox - picketbox-infinispan - - - - org.wildfly.core - wildfly-core-security - - - - org.wildfly.security - wildfly-elytron-auth-server - - - - org.wildfly.security - wildfly-elytron-security-manager - - - - org.wildfly.security - wildfly-elytron-security-manager-action - - - diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/AbstractRealmPrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/AbstractRealmPrincipal.java deleted file mode 100644 index 6be813aa069b..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/AbstractRealmPrincipal.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2013, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - -import static org.wildfly.common.Assert.checkNotNullParam; - -/** - * A base {@link Principal} where a realm is also associated. - * - * @author Darran Lofthouse - */ -abstract class AbstractRealmPrincipal extends SecurityRealmPrincipal implements RealmPrincipal { - - private static final long serialVersionUID = -5558581540228214884L; - - private int hashBase = this.getClass().getName().hashCode(); - private final String realm; - - public AbstractRealmPrincipal(final String name) { - super(name); - this.realm = null; - } - - public AbstractRealmPrincipal(final String realm, final String name) { - super(name); - this.realm = checkNotNullParam("realm", realm); - } - - public String getRealm() { - return realm; - } - - public String getFullName() { - return realm == null ? getName() : getName() + "@" + realm; - } - - @Override - public String toString() { - return getFullName(); - } - - @Override - public int hashCode() { - return (super.hashCode() + hashBase) * (realm == null ? 101 : realm.hashCode()); - } - - @Override - public boolean equals(Object obj) { - return obj != null && this.getClass().equals(obj.getClass()) ? equals((AbstractRealmPrincipal) obj) : false; - - } - - private boolean equals(AbstractRealmPrincipal user) { - return (this == user ? true : super.equals(user)) && (realm == null ? user.realm == null : realm.equals(user.realm)); - } - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/AccountPrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/AccountPrincipal.java deleted file mode 100644 index bd4f31e2bcc9..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/AccountPrincipal.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2013, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - -/** - * An interfaces to be implemented by a {@link Principal} that represents the account used for authentication. - * - * @author Darran Lofthouse - */ -public interface AccountPrincipal extends org.jboss.as.core.security.api.AccountPrincipal { - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/GroupPrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/GroupPrincipal.java deleted file mode 100644 index 865fb786adc0..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/GroupPrincipal.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2013, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - -/** - * An interfaces to be implemented by {@link Principal} instances that represent group membership. - * - * @author Darran Lofthouse - */ -public interface GroupPrincipal extends org.jboss.as.core.security.api.GroupPrincipal { - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/RealmGroup.java b/security/plugins/src/main/java/org/jboss/as/core/security/RealmGroup.java deleted file mode 100644 index ce9d3c27ba8f..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/RealmGroup.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2013, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.as.core.security; - -/** - * A {@link Principal} used to represent an authenticated identities group membership. - * - * @author Darran Lofthouse - */ -public final class RealmGroup extends AbstractRealmPrincipal implements GroupPrincipal { - - private static final long serialVersionUID = -6964117745867235712L; - - public RealmGroup(String realm, String name) { - super(realm, name); - } - - public RealmGroup(String name) { - super(name); - } - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/RealmPrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/RealmPrincipal.java deleted file mode 100644 index f32e4633d906..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/RealmPrincipal.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2013, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - -/** - * An interfaces to be implemented by all {@link Principal} instances that are also associated with a realm. - * - * @author Darran Lofthouse - */ -public interface RealmPrincipal extends org.jboss.as.core.security.api.RealmPrincipal { - - String getRealm(); - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/RealmRole.java b/security/plugins/src/main/java/org/jboss/as/core/security/RealmRole.java deleted file mode 100644 index 6684e6f42b04..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/RealmRole.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2012, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - -/** - * A {@link Principal} used to represent an authenticated identities role assignment. - * - * @author Darran Lofthouse - */ -public class RealmRole extends SecurityRealmPrincipal implements RolePrincipal { - - private static final long serialVersionUID = -3919796977468858556L; - - public RealmRole(final String name) { - super(name); - } - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/RealmUser.java b/security/plugins/src/main/java/org/jboss/as/core/security/RealmUser.java deleted file mode 100644 index c6911bfc524c..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/RealmUser.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2012, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - - - -/** - * The Principal used to represent the name of an authenticated user. - * - * @author Darran Lofthouse - */ -public class RealmUser extends AbstractRealmPrincipal implements AccountPrincipal, org.jboss.as.core.security.api.UserPrincipal { - - private static final long serialVersionUID = 5391073820551736954L; - - public RealmUser(String realm, String name) { - super(realm, name); - } - - public RealmUser(String name) { - super(name); - } - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/RolePrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/RolePrincipal.java deleted file mode 100644 index d1ae245934dd..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/RolePrincipal.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2013, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - -import java.security.Principal; - -/** - * An interfaces to be implemented by {@link Principal} instances that represent role assignment. - * - * @author Darran Lofthouse - */ -public interface RolePrincipal extends Principal { - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/SecurityRealmPrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/SecurityRealmPrincipal.java deleted file mode 100644 index c40a8ee6b7e2..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/SecurityRealmPrincipal.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2012, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - -import static org.wildfly.common.Assert.checkNotNullParam; - -import java.io.Serializable; -import java.security.Principal; - -/** - * Base class for Principals defined for security realms. - * - * @author Darran Lofthouse - */ -public abstract class SecurityRealmPrincipal implements Principal, Serializable { - - private static final long serialVersionUID = 3616079359863450698L; - - private final String name; - - SecurityRealmPrincipal(final String name) { - this.name = checkNotNullParam("name", name); - } - - /** - * @see java.security.Principal#getName() - */ - public String getName() { - return name; - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj != null && this.getClass().equals(obj.getClass()) ? equals((SecurityRealmPrincipal) obj) : false; - } - - protected boolean equals(SecurityRealmPrincipal principal) { - return this == principal || name.equals(principal.name); - } - - @Override - public String toString() { - return name; - } - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/ServerSecurityManager.java b/security/plugins/src/main/java/org/jboss/as/core/security/ServerSecurityManager.java deleted file mode 100644 index a78c52f7a236..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/ServerSecurityManager.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2012, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - -import java.lang.reflect.Method; -import java.security.CodeSource; -import java.security.Principal; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import javax.security.auth.Subject; - -/** - * Interface to the servers security manager implementation. - * - * @author Darran Lofthouse - */ -public interface ServerSecurityManager { - - void push(final String securityDomain); - void push(final String securityDomain, String userName, char[] password, final Subject subject); - - void authenticate(); - void authenticate(final String runAs, final String runAsPrincipal, final Set extraRoles); - - void pop(); - - Principal getCallerPrincipal(); - - Subject getSubject(); - - //TODO: we have no internal users of this, find out if it is used downstream - @Deprecated - boolean isCallerInRole(final String ejbName, final Object mappedRoles, final Map> roleLinks, - final String... roleNames); - - boolean isCallerInRole(final String ejbName, String policyContextId, final Object mappedRoles, final Map> roleLinks, - final String... roleNames); - - boolean authorize(String ejbName, CodeSource ejbCodeSource, String ejbMethodIntf, Method ejbMethod, Set methodRoles, String contextID); - -} diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/SimplePrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/SimplePrincipal.java deleted file mode 100644 index e891c8552e0c..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/SimplePrincipal.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2013, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security; - -import java.io.Serializable; -import java.security.Principal; - -/** - * A simple {@link Principal} implementation where categorising the Principal is not important. - * - * @author Darran Lofthouse - */ -public final class SimplePrincipal implements Principal, Serializable { - - private static final long serialVersionUID = 8804988619115765938L; - - private final String name; - - public SimplePrincipal(final String name) { - this.name = name; - } - - @Override - public String getName() { - return name; - } - - @Override - public int hashCode() { - return name == null ? 0 : name.hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof SimplePrincipal ? equals((SimplePrincipal) obj) : false; - } - - public boolean equals(SimplePrincipal other) { - return name == null ? other.name == null : name.equals(other.name); - } - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/api/AccountPrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/api/AccountPrincipal.java deleted file mode 100644 index f87a41596c7a..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/api/AccountPrincipal.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security.api; - -import java.security.Principal; - -/** - * An interfaces to be implemented by a {@link Principal} that represents the account used for authentication. - * - * @author Darran Lofthouse - */ -public interface AccountPrincipal extends Principal { - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/api/GroupPrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/api/GroupPrincipal.java deleted file mode 100644 index 55c00df1e3ea..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/api/GroupPrincipal.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security.api; - -/** - * A {@link Principal} type to represent a group, used generally to signify group membership information. - * - * @author Darran Lofthouse - */ -public interface GroupPrincipal extends RealmPrincipal { - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/api/RealmPrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/api/RealmPrincipal.java deleted file mode 100644 index 26933584ec5e..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/api/RealmPrincipal.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security.api; - -import java.security.Principal; - -/** - * An interface to be implemented by {@link Principal} types that also return a realm name. - * - * @author Darran Lofthouse - */ -public interface RealmPrincipal extends Principal { - - /** - * Obtain the name of the realm that this {@link Principal} is associated with. - * - * @return The name of the realm. - */ - String getRealm(); - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/core/security/api/UserPrincipal.java b/security/plugins/src/main/java/org/jboss/as/core/security/api/UserPrincipal.java deleted file mode 100644 index 7e534c667ac5..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/core/security/api/UserPrincipal.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.core.security.api; - -/** - * A {@link Principal} type to represent a user. - * - * @author Darran Lofthouse - */ -public interface UserPrincipal extends AccountPrincipal, RealmPrincipal { - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/security/_private/SecurityLogger.java b/security/plugins/src/main/java/org/jboss/as/security/_private/SecurityLogger.java deleted file mode 100644 index ccee71b25b09..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/_private/SecurityLogger.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2011, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.security._private; - -import org.jboss.logging.BasicLogger; -import org.jboss.logging.Logger; -import org.jboss.logging.annotations.Cause; -import org.jboss.logging.annotations.Message; -import org.jboss.logging.annotations.MessageLogger; - -/** - * Date: 05.11.2011 - * - * @author James R. Perkins - */ -@MessageLogger(projectCode = "WFLYSEC", length = 4) -public interface SecurityLogger extends BasicLogger { - - /** - * A logger with a category of the package name. - */ - SecurityLogger ROOT_LOGGER = Logger.getMessageLogger(SecurityLogger.class, "org.jboss.as.security"); - - /** - * Creates an exception indicating that the module name was missing - * @param name the missing module name - * @return {@link IllegalArgumentException} - */ - @Message(id = 6, value = "Missing module name for the %s") - IllegalArgumentException missingModuleName(String name); - - /** - * Creates a {@link RuntimeException} - * @param e the underlying exception - * @return the exception - */ - @Message(id = 7, value = "Runtime Exception:") - RuntimeException runtimeException(@Cause Throwable e); -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/lru/ConcurrentDirectDeque.java b/security/plugins/src/main/java/org/jboss/as/security/lru/ConcurrentDirectDeque.java deleted file mode 100644 index 9d5f1b54a163..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/lru/ConcurrentDirectDeque.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jboss.as.security.lru; - -import java.lang.reflect.Constructor; -import java.util.AbstractCollection; -import java.util.Deque; - -/** - * A concurrent deque that allows direct item removal without traversal. - * - * @author Jason T. Greene - */ -public abstract class ConcurrentDirectDeque extends AbstractCollection implements Deque, java.io.Serializable { - private static final Constructor CONSTRUCTOR; - - static { - boolean fast = false; - try { - new FastConcurrentDirectDeque(); - fast = true; - } catch (Throwable t) { - } - - Class klazz = fast ? FastConcurrentDirectDeque.class : PortableConcurrentDirectDeque.class; - try { - CONSTRUCTOR = klazz.getConstructor(); - } catch (NoSuchMethodException e) { - throw new NoSuchMethodError(e.getMessage()); - } - } - - public static ConcurrentDirectDeque newInstance() { - try { - return CONSTRUCTOR.newInstance(); - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - public abstract Object offerFirstAndReturnToken(E e); - - public abstract Object offerLastAndReturnToken(E e); - - public abstract void removeToken(Object token); -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/lru/FastConcurrentDirectDeque.java b/security/plugins/src/main/java/org/jboss/as/security/lru/FastConcurrentDirectDeque.java deleted file mode 100644 index 9ee981b6578f..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/lru/FastConcurrentDirectDeque.java +++ /dev/null @@ -1,1528 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Written by Doug Lea and Martin Buchholz with assistance from members of - * JCP JSR-166 Expert Group and released to the public domain, as explained - * at http://creativecommons.org/publicdomain/zero/1.0/ - */ - -package org.jboss.as.security.lru; - -import java.io.Serializable; -import java.lang.reflect.Field; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Deque; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import sun.misc.Unsafe; - -/** - * A modified version of ConcurrentLinkedDequeue which includes direct - * removal. Like the original, it relies on Unsafe for better performance. - * - * More specifically, an unbounded concurrent {@linkplain java.util.Deque deque} based on linked nodes. - * Concurrent insertion, removal, and access operations execute safely - * across multiple threads. - * A {@code ConcurrentLinkedDeque} is an appropriate choice when - * many threads will share access to a common collection. - * Like most other concurrent collection implementations, this class - * does not permit the use of {@code null} elements. - * - *

Iterators are weakly consistent, returning elements - * reflecting the state of the deque at some point at or since the - * creation of the iterator. They do not throw {@link - * java.util.ConcurrentModificationException - * ConcurrentModificationException}, and may proceed concurrently with - * other operations. - * - *

Beware that, unlike in most collections, the {@code size} method - * is NOT a constant-time operation. Because of the - * asynchronous nature of these deques, determining the current number - * of elements requires a traversal of the elements, and so may report - * inaccurate results if this collection is modified during traversal. - * Additionally, the bulk operations {@code addAll}, - * {@code removeAll}, {@code retainAll}, {@code containsAll}, - * {@code equals}, and {@code toArray} are not guaranteed - * to be performed atomically. For example, an iterator operating - * concurrently with an {@code addAll} operation might view only some - * of the added elements. - * - *

This class and its iterator implement all of the optional - * methods of the {@link java.util.Deque} and {@link java.util.Iterator} interfaces. - * - *

Memory consistency effects: As with other concurrent collections, - * actions in a thread prior to placing an object into a - * {@code ConcurrentLinkedDeque} - * happen-before - * actions subsequent to the access or removal of that element from - * the {@code ConcurrentLinkedDeque} in another thread. - * - *

This class is a member of the - * - * Java Collections Framework. - * - * @since 1.7 - * @author Doug Lea - * @author Martin Buchholz - * @author Jason T. Grene - * @param the type of elements held in this collection - */ - -public class FastConcurrentDirectDeque - extends ConcurrentDirectDeque implements Deque, Serializable { - - /* - * This is an implementation of a concurrent lock-free deque - * supporting interior removes but not interior insertions, as - * required to support the entire Deque interface. - * - * We extend the techniques developed for ConcurrentLinkedQueue and - * LinkedTransferQueue (see the internal docs for those classes). - * Understanding the ConcurrentLinkedQueue implementation is a - * prerequisite for understanding the implementation of this class. - * - * The data structure is a symmetrical doubly-linked "GC-robust" - * linked list of nodes. We minimize the number of volatile writes - * using two techniques: advancing multiple hops with a single CAS - * and mixing volatile and non-volatile writes of the same memory - * locations. - * - * A node contains the expected E ("item") and links to predecessor - * ("prev") and successor ("next") nodes: - * - * class Node { volatile Node prev, next; volatile E item; } - * - * A node p is considered "live" if it contains a non-null item - * (p.item != null). When an item is CASed to null, the item is - * atomically logically deleted from the collection. - * - * At any time, there is precisely one "first" node with a null - * prev reference that terminates any chain of prev references - * starting at a live node. Similarly there is precisely one - * "last" node terminating any chain of next references starting at - * a live node. The "first" and "last" nodes may or may not be live. - * The "first" and "last" nodes are always mutually reachable. - * - * A new element is added atomically by CASing the null prev or - * next reference in the first or last node to a fresh node - * containing the element. The element's node atomically becomes - * "live" at that point. - * - * A node is considered "active" if it is a live node, or the - * first or last node. Active nodes cannot be unlinked. - * - * A "self-link" is a next or prev reference that is the same node: - * p.prev == p or p.next == p - * Self-links are used in the node unlinking process. Active nodes - * never have self-links. - * - * A node p is active if and only if: - * - * p.item != null || - * (p.prev == null && p.next != p) || - * (p.next == null && p.prev != p) - * - * The deque object has two node references, "head" and "tail". - * The head and tail are only approximations to the first and last - * nodes of the deque. The first node can always be found by - * following prev pointers from head; likewise for tail. However, - * it is permissible for head and tail to be referring to deleted - * nodes that have been unlinked and so may not be reachable from - * any live node. - * - * There are 3 stages of node deletion; - * "logical deletion", "unlinking", and "gc-unlinking". - * - * 1. "logical deletion" by CASing item to null atomically removes - * the element from the collection, and makes the containing node - * eligible for unlinking. - * - * 2. "unlinking" makes a deleted node unreachable from active - * nodes, and thus eventually reclaimable by GC. Unlinked nodes - * may remain reachable indefinitely from an iterator. - * - * Physical node unlinking is merely an optimization (albeit a - * critical one), and so can be performed at our convenience. At - * any time, the set of live nodes maintained by prev and next - * links are identical, that is, the live nodes found via next - * links from the first node is equal to the elements found via - * prev links from the last node. However, this is not true for - * nodes that have already been logically deleted - such nodes may - * be reachable in one direction only. - * - * 3. "gc-unlinking" takes unlinking further by making active - * nodes unreachable from deleted nodes, making it easier for the - * GC to reclaim future deleted nodes. This step makes the data - * structure "gc-robust", as first described in detail by Boehm - * (http://portal.acm.org/citation.cfm?doid=503272.503282). - * - * GC-unlinked nodes may remain reachable indefinitely from an - * iterator, but unlike unlinked nodes, are never reachable from - * head or tail. - * - * Making the data structure GC-robust will eliminate the risk of - * unbounded memory retention with conservative GCs and is likely - * to improve performance with generational GCs. - * - * When a node is dequeued at either end, e.g. via poll(), we would - * like to break any references from the node to active nodes. We - * develop further the use of self-links that was very effective in - * other concurrent collection classes. The idea is to replace - * prev and next pointers with special values that are interpreted - * to mean off-the-list-at-one-end. These are approximations, but - * good enough to preserve the properties we want in our - * traversals, e.g. we guarantee that a traversal will never visit - * the same element twice, but we don't guarantee whether a - * traversal that runs out of elements will be able to see more - * elements later after enqueues at that end. Doing gc-unlinking - * safely is particularly tricky, since any node can be in use - * indefinitely (for example by an iterator). We must ensure that - * the nodes pointed at by head/tail never get gc-unlinked, since - * head/tail are needed to get "back on track" by other nodes that - * are gc-unlinked. gc-unlinking accounts for much of the - * implementation complexity. - * - * Since neither unlinking nor gc-unlinking are necessary for - * correctness, there are many implementation choices regarding - * frequency (eagerness) of these operations. Since volatile - * reads are likely to be much cheaper than CASes, saving CASes by - * unlinking multiple adjacent nodes at a time may be a win. - * gc-unlinking can be performed rarely and still be effective, - * since it is most important that long chains of deleted nodes - * are occasionally broken. - * - * The actual representation we use is that p.next == p means to - * goto the first node (which in turn is reached by following prev - * pointers from head), and p.next == null && p.prev == p means - * that the iteration is at an end and that p is a (static final) - * dummy node, NEXT_TERMINATOR, and not the last active node. - * Finishing the iteration when encountering such a TERMINATOR is - * good enough for read-only traversals, so such traversals can use - * p.next == null as the termination condition. When we need to - * find the last (active) node, for enqueueing a new node, we need - * to check whether we have reached a TERMINATOR node; if so, - * restart traversal from tail. - * - * The implementation is completely directionally symmetrical, - * except that most public methods that iterate through the list - * follow next pointers ("forward" direction). - * - * We believe (without full proof) that all single-element deque - * operations (e.g., addFirst, peekLast, pollLast) are linearizable - * (see Herlihy and Shavit's book). However, some combinations of - * operations are known not to be linearizable. In particular, - * when an addFirst(A) is racing with pollFirst() removing B, it is - * possible for an observer iterating over the elements to observe - * A B C and subsequently observe A C, even though no interior - * removes are ever performed. Nevertheless, iterators behave - * reasonably, providing the "weakly consistent" guarantees. - * - * Empirically, microbenchmarks suggest that this class adds about - * 40% overhead relative to ConcurrentLinkedQueue, which feels as - * good as we can hope for. - */ - - private static final long serialVersionUID = 876323262645176354L; - - /** - * A node from which the first node on list (that is, the unique node p - * with p.prev == null && p.next != p) can be reached in O(1) time. - * Invariants: - * - the first node is always O(1) reachable from head via prev links - * - all live nodes are reachable from the first node via succ() - * - head != null - * - (tmp = head).next != tmp || tmp != head - * - head is never gc-unlinked (but may be unlinked) - * Non-invariants: - * - head.item may or may not be null - * - head may not be reachable from the first or last node, or from tail - */ - private transient volatile Node head; - - /** - * A node from which the last node on list (that is, the unique node p - * with p.next == null && p.prev != p) can be reached in O(1) time. - * Invariants: - * - the last node is always O(1) reachable from tail via next links - * - all live nodes are reachable from the last node via pred() - * - tail != null - * - tail is never gc-unlinked (but may be unlinked) - * Non-invariants: - * - tail.item may or may not be null - * - tail may not be reachable from the first or last node, or from head - */ - private transient volatile Node tail; - - private static final Node PREV_TERMINATOR, NEXT_TERMINATOR; - - @SuppressWarnings("unchecked") - Node prevTerminator() { - return (Node) PREV_TERMINATOR; - } - - @SuppressWarnings("unchecked") - Node nextTerminator() { - return (Node) NEXT_TERMINATOR; - } - - static final class Node { - volatile Node prev; - volatile E item; - volatile Node next; - - Node() { // default constructor for NEXT_TERMINATOR, PREV_TERMINATOR - } - - /** - * Constructs a new node. Uses relaxed write because item can - * only be seen after publication via casNext or casPrev. - */ - Node(E item) { - UNSAFE.putObject(this, itemOffset, item); - } - - boolean casItem(E cmp, E val) { - return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val); - } - - void lazySetNext(Node val) { - UNSAFE.putOrderedObject(this, nextOffset, val); - } - - boolean casNext(Node cmp, Node val) { - return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val); - } - - void lazySetPrev(Node val) { - UNSAFE.putOrderedObject(this, prevOffset, val); - } - - boolean casPrev(Node cmp, Node val) { - return UNSAFE.compareAndSwapObject(this, prevOffset, cmp, val); - } - - // Unsafe mechanics - - private static final Unsafe UNSAFE; - private static final long prevOffset; - private static final long itemOffset; - private static final long nextOffset; - - static { - try { - UNSAFE = getUnsafe(); - Class k = Node.class; - prevOffset = UNSAFE.objectFieldOffset - (k.getDeclaredField("prev")); - itemOffset = UNSAFE.objectFieldOffset - (k.getDeclaredField("item")); - nextOffset = UNSAFE.objectFieldOffset - (k.getDeclaredField("next")); - } catch (Exception e) { - throw new Error(e); - } - } - } - - /** - * Links e as first element. - */ - private Node linkFirst(E e) { - checkNotNull(e); - final Node newNode = new Node<>(e); - - restartFromHead: - for (;;) - for (Node h = head, p = h, q;;) { - if ((q = p.prev) != null && - (q = (p = q).prev) != null) - // Check for head updates every other hop. - // If p == q, we are sure to follow head instead. - p = (h != (h = head)) ? h : q; - else if (p.next == p) // PREV_TERMINATOR - continue restartFromHead; - else { - // p is first node - newNode.lazySetNext(p); // CAS piggyback - if (p.casPrev(null, newNode)) { - // Successful CAS is the linearization point - // for e to become an element of this deque, - // and for newNode to become "live". - if (p != h) // hop two nodes at a time - casHead(h, newNode); // Failure is OK. - return newNode; - } - // Lost CAS race to another thread; re-read prev - } - } - } - - /** - * Links e as last element. - */ - private Node linkLast(E e) { - checkNotNull(e); - final Node newNode = new Node<>(e); - - restartFromTail: - for (;;) - for (Node t = tail, p = t, q;;) { - if ((q = p.next) != null && - (q = (p = q).next) != null) - // Check for tail updates every other hop. - // If p == q, we are sure to follow tail instead. - p = (t != (t = tail)) ? t : q; - else if (p.prev == p) // NEXT_TERMINATOR - continue restartFromTail; - else { - // p is last node - newNode.lazySetPrev(p); // CAS piggyback - if (p.casNext(null, newNode)) { - // Successful CAS is the linearization point - // for e to become an element of this deque, - // and for newNode to become "live". - if (p != t) // hop two nodes at a time - casTail(t, newNode); // Failure is OK. - return newNode; - } - // Lost CAS race to another thread; re-read next - } - } - } - - private static final int HOPS = 2; - - /** - * Unlinks non-null node x. - */ - void unlink(Node x) { - // assert x != null; - // assert x.item == null; - // assert x != PREV_TERMINATOR; - // assert x != NEXT_TERMINATOR; - - final Node prev = x.prev; - final Node next = x.next; - if (prev == null) { - unlinkFirst(x, next); - } else if (next == null) { - unlinkLast(x, prev); - } else { - // Unlink interior node. - // - // This is the common case, since a series of polls at the - // same end will be "interior" removes, except perhaps for - // the first one, since end nodes cannot be unlinked. - // - // At any time, all active nodes are mutually reachable by - // following a sequence of either next or prev pointers. - // - // Our strategy is to find the unique active predecessor - // and successor of x. Try to fix up their links so that - // they point to each other, leaving x unreachable from - // active nodes. If successful, and if x has no live - // predecessor/successor, we additionally try to gc-unlink, - // leaving active nodes unreachable from x, by rechecking - // that the status of predecessor and successor are - // unchanged and ensuring that x is not reachable from - // tail/head, before setting x's prev/next links to their - // logical approximate replacements, self/TERMINATOR. - Node activePred, activeSucc; - boolean isFirst, isLast; - int hops = 1; - - // Find active predecessor - for (Node p = prev; ; ++hops) { - if (p.item != null) { - activePred = p; - isFirst = false; - break; - } - Node q = p.prev; - if (q == null) { - if (p.next == p) - return; - activePred = p; - isFirst = true; - break; - } - else if (p == q) - return; - else - p = q; - } - - // Find active successor - for (Node p = next; ; ++hops) { - if (p.item != null) { - activeSucc = p; - isLast = false; - break; - } - Node q = p.next; - if (q == null) { - if (p.prev == p) - return; - activeSucc = p; - isLast = true; - break; - } - else if (p == q) - return; - else - p = q; - } - - // TODO: better HOP heuristics - if (hops < HOPS - // always squeeze out interior deleted nodes - && (isFirst | isLast)) - return; - - // Squeeze out deleted nodes between activePred and - // activeSucc, including x. - skipDeletedSuccessors(activePred); - skipDeletedPredecessors(activeSucc); - - // Try to gc-unlink, if possible - if ((isFirst | isLast) && - - // Recheck expected state of predecessor and successor - (activePred.next == activeSucc) && - (activeSucc.prev == activePred) && - (isFirst ? activePred.prev == null : activePred.item != null) && - (isLast ? activeSucc.next == null : activeSucc.item != null)) { - - updateHead(); // Ensure x is not reachable from head - updateTail(); // Ensure x is not reachable from tail - - // Finally, actually gc-unlink - x.lazySetPrev(isFirst ? prevTerminator() : x); - x.lazySetNext(isLast ? nextTerminator() : x); - } - } - } - - /** - * Unlinks non-null first node. - */ - private void unlinkFirst(Node first, Node next) { - // assert first != null; - // assert next != null; - // assert first.item == null; - for (Node o = null, p = next, q;;) { - if (p.item != null || (q = p.next) == null) { - if (o != null && p.prev != p && first.casNext(next, p)) { - skipDeletedPredecessors(p); - if (first.prev == null && - (p.next == null || p.item != null) && - p.prev == first) { - - updateHead(); // Ensure o is not reachable from head - updateTail(); // Ensure o is not reachable from tail - - // Finally, actually gc-unlink - o.lazySetNext(o); - o.lazySetPrev(prevTerminator()); - } - } - return; - } - else if (p == q) - return; - else { - o = p; - p = q; - } - } - } - - /** - * Unlinks non-null last node. - */ - private void unlinkLast(Node last, Node prev) { - // assert last != null; - // assert prev != null; - // assert last.item == null; - for (Node o = null, p = prev, q;;) { - if (p.item != null || (q = p.prev) == null) { - if (o != null && p.next != p && last.casPrev(prev, p)) { - skipDeletedSuccessors(p); - if (last.next == null && - (p.prev == null || p.item != null) && - p.next == last) { - - updateHead(); // Ensure o is not reachable from head - updateTail(); // Ensure o is not reachable from tail - - // Finally, actually gc-unlink - o.lazySetPrev(o); - o.lazySetNext(nextTerminator()); - } - } - return; - } - else if (p == q) - return; - else { - o = p; - p = q; - } - } - } - - /** - * Guarantees that any node which was unlinked before a call to - * this method will be unreachable from head after it returns. - * Does not guarantee to eliminate slack, only that head will - * point to a node that was active while this method was running. - */ - private void updateHead() { - // Either head already points to an active node, or we keep - // trying to cas it to the first node until it does. - Node h, p, q; - restartFromHead: - while ((h = head).item == null && (p = h.prev) != null) { - for (;;) { - if ((q = p.prev) == null || - (q = (p = q).prev) == null) { - // It is possible that p is PREV_TERMINATOR, - // but if so, the CAS is guaranteed to fail. - if (casHead(h, p)) - return; - else - continue restartFromHead; - } - else if (h != head) - continue restartFromHead; - else - p = q; - } - } - } - - /** - * Guarantees that any node which was unlinked before a call to - * this method will be unreachable from tail after it returns. - * Does not guarantee to eliminate slack, only that tail will - * point to a node that was active while this method was running. - */ - private void updateTail() { - // Either tail already points to an active node, or we keep - // trying to cas it to the last node until it does. - Node t, p, q; - restartFromTail: - while ((t = tail).item == null && (p = t.next) != null) { - for (;;) { - if ((q = p.next) == null || - (q = (p = q).next) == null) { - // It is possible that p is NEXT_TERMINATOR, - // but if so, the CAS is guaranteed to fail. - if (casTail(t, p)) - return; - else - continue restartFromTail; - } - else if (t != tail) - continue restartFromTail; - else - p = q; - } - } - } - - private void skipDeletedPredecessors(Node x) { - whileActive: - do { - Node prev = x.prev; - // assert prev != null; - // assert x != NEXT_TERMINATOR; - // assert x != PREV_TERMINATOR; - Node p = prev; - findActive: - for (;;) { - if (p.item != null) - break findActive; - Node q = p.prev; - if (q == null) { - if (p.next == p) - continue whileActive; - break findActive; - } - else if (p == q) - continue whileActive; - else - p = q; - } - - // found active CAS target - if (prev == p || x.casPrev(prev, p)) - return; - - } while (x.item != null || x.next == null); - } - - private void skipDeletedSuccessors(Node x) { - whileActive: - do { - Node next = x.next; - // assert next != null; - // assert x != NEXT_TERMINATOR; - // assert x != PREV_TERMINATOR; - Node p = next; - findActive: - for (;;) { - if (p.item != null) - break findActive; - Node q = p.next; - if (q == null) { - if (p.prev == p) - continue whileActive; - break findActive; - } - else if (p == q) - continue whileActive; - else - p = q; - } - - // found active CAS target - if (next == p || x.casNext(next, p)) - return; - - } while (x.item != null || x.prev == null); - } - - /** - * Returns the successor of p, or the first node if p.next has been - * linked to self, which will only be true if traversing with a - * stale pointer that is now off the list. - */ - final Node succ(Node p) { - // TODO: should we skip deleted nodes here? - Node q = p.next; - return (p == q) ? first() : q; - } - - /** - * Returns the predecessor of p, or the last node if p.prev has been - * linked to self, which will only be true if traversing with a - * stale pointer that is now off the list. - */ - final Node pred(Node p) { - Node q = p.prev; - return (p == q) ? last() : q; - } - - /** - * Returns the first node, the unique node p for which: - * p.prev == null && p.next != p - * The returned node may or may not be logically deleted. - * Guarantees that head is set to the returned node. - */ - Node first() { - restartFromHead: - for (;;) - for (Node h = head, p = h, q;;) { - if ((q = p.prev) != null && - (q = (p = q).prev) != null) - // Check for head updates every other hop. - // If p == q, we are sure to follow head instead. - p = (h != (h = head)) ? h : q; - else if (p == h - // It is possible that p is PREV_TERMINATOR, - // but if so, the CAS is guaranteed to fail. - || casHead(h, p)) - return p; - else - continue restartFromHead; - } - } - - /** - * Returns the last node, the unique node p for which: - * p.next == null && p.prev != p - * The returned node may or may not be logically deleted. - * Guarantees that tail is set to the returned node. - */ - Node last() { - restartFromTail: - for (;;) - for (Node t = tail, p = t, q;;) { - if ((q = p.next) != null && - (q = (p = q).next) != null) - // Check for tail updates every other hop. - // If p == q, we are sure to follow tail instead. - p = (t != (t = tail)) ? t : q; - else if (p == t - // It is possible that p is NEXT_TERMINATOR, - // but if so, the CAS is guaranteed to fail. - || casTail(t, p)) - return p; - else - continue restartFromTail; - } - } - - // Minor convenience utilities - - /** - * Throws NullPointerException if argument is null. - * - * @param v the element - */ - private static void checkNotNull(Object v) { - if (v == null) - throw new NullPointerException(); - } - - /** - * Returns element unless it is null, in which case throws - * NoSuchElementException. - * - * @param v the element - * @return the element - */ - private E screenNullResult(E v) { - if (v == null) - throw new NoSuchElementException(); - return v; - } - - /** - * Creates an array list and fills it with elements of this list. - * Used by toArray. - * - * @return the arrayList - */ - private ArrayList toArrayList() { - ArrayList list = new ArrayList<>(); - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null) - list.add(item); - } - return list; - } - - /** - * Constructs an empty deque. - */ - public FastConcurrentDirectDeque() { - head = tail = new Node<>(null); - } - - /** - * Constructs a deque initially containing the elements of - * the given collection, added in traversal order of the - * collection's iterator. - * - * @param c the collection of elements to initially contain - * @throws NullPointerException if the specified collection or any - * of its elements are null - */ - public FastConcurrentDirectDeque(Collection c) { - // Copy c into a private chain of Nodes - Node h = null, t = null; - for (E e : c) { - checkNotNull(e); - Node newNode = new Node<>(e); - if (h == null) - h = t = newNode; - else { - t.lazySetNext(newNode); - newNode.lazySetPrev(t); - t = newNode; - } - } - initHeadTail(h, t); - } - - /** - * Initializes head and tail, ensuring invariants hold. - */ - private void initHeadTail(Node h, Node t) { - if (h == t) { - if (h == null) - h = t = new Node<>(null); - else { - // Avoid edge case of a single Node with non-null item. - Node newNode = new Node<>(null); - t.lazySetNext(newNode); - newNode.lazySetPrev(t); - t = newNode; - } - } - head = h; - tail = t; - } - - /** - * Inserts the specified element at the front of this deque. - * As the deque is unbounded, this method will never throw - * {@link IllegalStateException}. - * - * @throws NullPointerException if the specified element is null - */ - public void addFirst(E e) { - linkFirst(e); - } - - /** - * Inserts the specified element at the end of this deque. - * As the deque is unbounded, this method will never throw - * {@link IllegalStateException}. - * - *

This method is equivalent to {@link #add}. - * - * @throws NullPointerException if the specified element is null - */ - public void addLast(E e) { - linkLast(e); - } - - /** - * Inserts the specified element at the front of this deque. - * As the deque is unbounded, this method will never return {@code false}. - * - * @return {@code true} (as specified by {@link java.util.Deque#offerFirst}) - * @throws NullPointerException if the specified element is null - */ - public boolean offerFirst(E e) { - linkFirst(e); - return true; - } - - public Object offerFirstAndReturnToken(E e) { - return linkFirst(e); - } - - public Object offerLastAndReturnToken(E e) { - return linkLast(e); - } - - - @SuppressWarnings("unchecked") - public void removeToken(Object token) { - if (!(token instanceof Node)) { - throw new IllegalArgumentException(); - } - - Node node = (Node) (token); - for (;;) { - Object item = node.item; - if (item == null) { - break; - } - if (node.casItem(item, null)) { - unlink(node); - break; - } - } - } - - /** - * Inserts the specified element at the end of this deque. - * As the deque is unbounded, this method will never return {@code false}. - * - *

This method is equivalent to {@link #add}. - * - * @return {@code true} (as specified by {@link java.util.Deque#offerLast}) - * @throws NullPointerException if the specified element is null - */ - public boolean offerLast(E e) { - linkLast(e); - return true; - } - - public E peekFirst() { - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null) - return item; - } - return null; - } - - public E peekLast() { - for (Node p = last(); p != null; p = pred(p)) { - E item = p.item; - if (item != null) - return item; - } - return null; - } - - /** - * @throws java.util.NoSuchElementException {@inheritDoc} - */ - public E getFirst() { - return screenNullResult(peekFirst()); - } - - /** - * @throws java.util.NoSuchElementException {@inheritDoc} - */ - public E getLast() { - return screenNullResult(peekLast()); - } - - public E pollFirst() { - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null && p.casItem(item, null)) { - unlink(p); - return item; - } - } - return null; - } - - public E pollLast() { - for (Node p = last(); p != null; p = pred(p)) { - E item = p.item; - if (item != null && p.casItem(item, null)) { - unlink(p); - return item; - } - } - return null; - } - - /** - * @throws java.util.NoSuchElementException {@inheritDoc} - */ - public E removeFirst() { - return screenNullResult(pollFirst()); - } - - /** - * @throws java.util.NoSuchElementException {@inheritDoc} - */ - public E removeLast() { - return screenNullResult(pollLast()); - } - - // *** Queue and stack methods *** - - /** - * Inserts the specified element at the tail of this deque. - * As the deque is unbounded, this method will never return {@code false}. - * - * @return {@code true} (as specified by {@link java.util.Queue#offer}) - * @throws NullPointerException if the specified element is null - */ - public boolean offer(E e) { - return offerLast(e); - } - - /** - * Inserts the specified element at the tail of this deque. - * As the deque is unbounded, this method will never throw - * {@link IllegalStateException} or return {@code false}. - * - * @return {@code true} (as specified by {@link java.util.Collection#add}) - * @throws NullPointerException if the specified element is null - */ - public boolean add(E e) { - return offerLast(e); - } - - public E poll() { - return pollFirst(); - } - public E remove() { - return removeFirst(); - } - public E peek() { - return peekFirst(); - } - public E element() { - return getFirst(); - } - public void push(E e) { - addFirst(e); - } - public E pop() { - return removeFirst(); - } - - /** - * Removes the first element {@code e} such that - * {@code o.equals(e)}, if such an element exists in this deque. - * If the deque does not contain the element, it is unchanged. - * - * @param o element to be removed from this deque, if present - * @return {@code true} if the deque contained the specified element - * @throws NullPointerException if the specified element is null - */ - public boolean removeFirstOccurrence(Object o) { - checkNotNull(o); - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null && o.equals(item) && p.casItem(item, null)) { - unlink(p); - return true; - } - } - return false; - } - - /** - * Removes the last element {@code e} such that - * {@code o.equals(e)}, if such an element exists in this deque. - * If the deque does not contain the element, it is unchanged. - * - * @param o element to be removed from this deque, if present - * @return {@code true} if the deque contained the specified element - * @throws NullPointerException if the specified element is null - */ - public boolean removeLastOccurrence(Object o) { - checkNotNull(o); - for (Node p = last(); p != null; p = pred(p)) { - E item = p.item; - if (item != null && o.equals(item) && p.casItem(item, null)) { - unlink(p); - return true; - } - } - return false; - } - - /** - * Returns {@code true} if this deque contains at least one - * element {@code e} such that {@code o.equals(e)}. - * - * @param o element whose presence in this deque is to be tested - * @return {@code true} if this deque contains the specified element - */ - public boolean contains(Object o) { - if (o == null) return false; - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null && o.equals(item)) - return true; - } - return false; - } - - /** - * Returns {@code true} if this collection contains no elements. - * - * @return {@code true} if this collection contains no elements - */ - public boolean isEmpty() { - return peekFirst() == null; - } - - /** - * Returns the number of elements in this deque. If this deque - * contains more than {@code Integer.MAX_VALUE} elements, it - * returns {@code Integer.MAX_VALUE}. - * - *

Beware that, unlike in most collections, this method is - * NOT a constant-time operation. Because of the - * asynchronous nature of these deques, determining the current - * number of elements requires traversing them all to count them. - * Additionally, it is possible for the size to change during - * execution of this method, in which case the returned result - * will be inaccurate. Thus, this method is typically not very - * useful in concurrent applications. - * - * @return the number of elements in this deque - */ - public int size() { - int count = 0; - for (Node p = first(); p != null; p = succ(p)) - if (p.item != null) - // Collection.size() spec says to max out - if (++count == Integer.MAX_VALUE) - break; - return count; - } - - /** - * Removes the first element {@code e} such that - * {@code o.equals(e)}, if such an element exists in this deque. - * If the deque does not contain the element, it is unchanged. - * - * @param o element to be removed from this deque, if present - * @return {@code true} if the deque contained the specified element - * @throws NullPointerException if the specified element is null - */ - public boolean remove(Object o) { - return removeFirstOccurrence(o); - } - - /** - * Appends all of the elements in the specified collection to the end of - * this deque, in the order that they are returned by the specified - * collection's iterator. Attempts to {@code addAll} of a deque to - * itself result in {@code IllegalArgumentException}. - * - * @param c the elements to be inserted into this deque - * @return {@code true} if this deque changed as a result of the call - * @throws NullPointerException if the specified collection or any - * of its elements are null - * @throws IllegalArgumentException if the collection is this deque - */ - public boolean addAll(Collection c) { - if (c == this) - // As historically specified in AbstractQueue#addAll - throw new IllegalArgumentException(); - - // Copy c into a private chain of Nodes - Node beginningOfTheEnd = null, last = null; - for (E e : c) { - checkNotNull(e); - Node newNode = new Node<>(e); - if (beginningOfTheEnd == null) - beginningOfTheEnd = last = newNode; - else { - last.lazySetNext(newNode); - newNode.lazySetPrev(last); - last = newNode; - } - } - if (beginningOfTheEnd == null) - return false; - - // Atomically append the chain at the tail of this collection - restartFromTail: - for (;;) - for (Node t = tail, p = t, q;;) { - if ((q = p.next) != null && - (q = (p = q).next) != null) - // Check for tail updates every other hop. - // If p == q, we are sure to follow tail instead. - p = (t != (t = tail)) ? t : q; - else if (p.prev == p) // NEXT_TERMINATOR - continue restartFromTail; - else { - // p is last node - beginningOfTheEnd.lazySetPrev(p); // CAS piggyback - if (p.casNext(null, beginningOfTheEnd)) { - // Successful CAS is the linearization point - // for all elements to be added to this deque. - if (!casTail(t, last)) { - // Try a little harder to update tail, - // since we may be adding many elements. - t = tail; - if (last.next == null) - casTail(t, last); - } - return true; - } - // Lost CAS race to another thread; re-read next - } - } - } - - /** - * Removes all of the elements from this deque. - */ - public void clear() { - while (pollFirst() != null) { } - } - - /** - * Returns an array containing all of the elements in this deque, in - * proper sequence (from first to last element). - * - *

The returned array will be "safe" in that no references to it are - * maintained by this deque. (In other words, this method must allocate - * a new array). The caller is thus free to modify the returned array. - * - *

This method acts as bridge between array-based and collection-based - * APIs. - * - * @return an array containing all of the elements in this deque - */ - public Object[] toArray() { - return toArrayList().toArray(); - } - - /** - * Returns an array containing all of the elements in this deque, - * in proper sequence (from first to last element); the runtime - * type of the returned array is that of the specified array. If - * the deque fits in the specified array, it is returned therein. - * Otherwise, a new array is allocated with the runtime type of - * the specified array and the size of this deque. - * - *

If this deque fits in the specified array with room to spare - * (i.e., the array has more elements than this deque), the element in - * the array immediately following the end of the deque is set to - * {@code null}. - * - *

Like the {@link #toArray()} method, this method acts as - * bridge between array-based and collection-based APIs. Further, - * this method allows precise control over the runtime type of the - * output array, and may, under certain circumstances, be used to - * save allocation costs. - * - *

Suppose {@code x} is a deque known to contain only strings. - * The following code can be used to dump the deque into a newly - * allocated array of {@code String}: - * - *

 {@code String[] y = x.toArray(new String[0]);}
- * - * Note that {@code toArray(new Object[0])} is identical in function to - * {@code toArray()}. - * - * @param a the array into which the elements of the deque are to - * be stored, if it is big enough; otherwise, a new array of the - * same runtime type is allocated for this purpose - * @return an array containing all of the elements in this deque - * @throws ArrayStoreException if the runtime type of the specified array - * is not a supertype of the runtime type of every element in - * this deque - * @throws NullPointerException if the specified array is null - */ - public T[] toArray(T[] a) { - return toArrayList().toArray(a); - } - - /** - * Returns an iterator over the elements in this deque in proper sequence. - * The elements will be returned in order from first (head) to last (tail). - * - *

The returned iterator is a "weakly consistent" iterator that - * will never throw {@link java.util.ConcurrentModificationException - * ConcurrentModificationException}, and guarantees to traverse - * elements as they existed upon construction of the iterator, and - * may (but is not guaranteed to) reflect any modifications - * subsequent to construction. - * - * @return an iterator over the elements in this deque in proper sequence - */ - public Iterator iterator() { - return new Itr(); - } - - /** - * Returns an iterator over the elements in this deque in reverse - * sequential order. The elements will be returned in order from - * last (tail) to first (head). - * - *

The returned iterator is a "weakly consistent" iterator that - * will never throw {@link java.util.ConcurrentModificationException - * ConcurrentModificationException}, and guarantees to traverse - * elements as they existed upon construction of the iterator, and - * may (but is not guaranteed to) reflect any modifications - * subsequent to construction. - * - * @return an iterator over the elements in this deque in reverse order - */ - public Iterator descendingIterator() { - return new DescendingItr(); - } - - private abstract class AbstractItr implements Iterator { - /** - * Next node to return item for. - */ - private Node nextNode; - - /** - * nextItem holds on to item fields because once we claim - * that an element exists in hasNext(), we must return it in - * the following next() call even if it was in the process of - * being removed when hasNext() was called. - */ - private E nextItem; - - /** - * Node returned by most recent call to next. Needed by remove. - * Reset to null if this element is deleted by a call to remove. - */ - private Node lastRet; - - abstract Node startNode(); - abstract Node nextNode(Node p); - - AbstractItr() { - advance(); - } - - /** - * Sets nextNode and nextItem to next valid node, or to null - * if no such. - */ - private void advance() { - lastRet = nextNode; - - Node p = (nextNode == null) ? startNode() : nextNode(nextNode); - for (;; p = nextNode(p)) { - if (p == null) { - // p might be active end or TERMINATOR node; both are OK - nextNode = null; - nextItem = null; - break; - } - E item = p.item; - if (item != null) { - nextNode = p; - nextItem = item; - break; - } - } - } - - public boolean hasNext() { - return nextItem != null; - } - - public E next() { - E item = nextItem; - if (item == null) throw new NoSuchElementException(); - advance(); - return item; - } - - public void remove() { - Node l = lastRet; - if (l == null) throw new IllegalStateException(); - l.item = null; - unlink(l); - lastRet = null; - } - } - - /** Forward iterator */ - private class Itr extends AbstractItr { - Node startNode() { - return first(); - } - Node nextNode(Node p) { - return succ(p); - } - } - - /** Descending iterator */ - private class DescendingItr extends AbstractItr { - Node startNode() { - return last(); - } - Node nextNode(Node p) { - return pred(p); - } - } - - /** - * Saves this deque to a stream (that is, serializes it). - * - * @serialData All of the elements (each an {@code E}) in - * the proper order, followed by a null - */ - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - - // Write out any hidden stuff - s.defaultWriteObject(); - - // Write out all elements in the proper order. - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null) - s.writeObject(item); - } - - // Use trailing null as sentinel - s.writeObject(null); - } - - /** - * Reconstitutes this deque from a stream (that is, deserializes it). - */ - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - - // Read in elements until trailing null sentinel found - Node h = null, t = null; - Object item; - while ((item = s.readObject()) != null) { - @SuppressWarnings("unchecked") - Node newNode = new Node<>((E) item); - if (h == null) - h = t = newNode; - else { - t.lazySetNext(newNode); - newNode.lazySetPrev(t); - t = newNode; - } - } - initHeadTail(h, t); - } - - private boolean casHead(Node cmp, Node val) { - return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); - } - - private boolean casTail(Node cmp, Node val) { - return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val); - } - - // Unsafe mechanics - - private static final Unsafe UNSAFE; - private static final long headOffset; - private static final long tailOffset; - static { - PREV_TERMINATOR = new Node<>(); - PREV_TERMINATOR.next = PREV_TERMINATOR; - NEXT_TERMINATOR = new Node<>(); - NEXT_TERMINATOR.prev = NEXT_TERMINATOR; - try { - UNSAFE = getUnsafe(); - Class k = FastConcurrentDirectDeque.class; - headOffset = UNSAFE.objectFieldOffset - (k.getDeclaredField("head")); - tailOffset = UNSAFE.objectFieldOffset - (k.getDeclaredField("tail")); - } catch (Exception e) { - throw new Error(e); - } - } - - private static Unsafe getUnsafe() { - if (System.getSecurityManager() != null) { - return new PrivilegedAction() { - public Unsafe run() { - return getUnsafe0(); - } - }.run(); - } - return getUnsafe0(); - } - - private static Unsafe getUnsafe0() { - try { - Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); - theUnsafe.setAccessible(true); - return (Unsafe) theUnsafe.get(null); - } catch (Throwable t) { - throw new RuntimeException("JDK did not allow accessing unsafe", t); - } - } -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/lru/LRUCache.java b/security/plugins/src/main/java/org/jboss/as/security/lru/LRUCache.java deleted file mode 100644 index faa3f134efb8..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/lru/LRUCache.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jboss.as.security.lru; - -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Iterator; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; - -/** - * A non-blocking cache where entries are indexed by a key. - *

- *

To reduce contention, entry allocation and eviction execute in a sampling - * fashion (entry hits modulo N). Eviction follows an LRU approach (oldest sampled - * entries are removed first) when the cache is out of capacity.

- *

- * - * @author Jason T. Greene - */ -public class LRUCache extends AbstractMap implements ConcurrentMap { - private static final int SAMPLE_INTERVAL = 5; - - /** - * Max active entries that are present in the cache. - */ - private final int maxEntries; - - private final ConcurrentHashMap> cache; - private final ConcurrentDirectDeque> accessQueue; - private final RemoveCallback removeCallback; - - public LRUCache(int maxEntries) { - this(maxEntries, null); - } - - public LRUCache(int maxEntries, RemoveCallback removeCallback) { - this.cache = new ConcurrentHashMap<>(); - this.accessQueue = ConcurrentDirectDeque.newInstance(); - this.maxEntries = maxEntries; - this.removeCallback = removeCallback; - } - - public V put(K key, V newValue) { - return put(key, newValue, false); - } - - public V put(K key, V newValue, boolean ifAbsent) { - CacheEntry entry = cache.get(key); - V old = null; - if (entry == null) { - entry = new CacheEntry<>(key, newValue); - CacheEntry result = cache.putIfAbsent(key, entry); - if (result != null) { - return this.put(key, newValue); - } - - bumpAccess(entry); - } else { - old = entry.getValue(); - if (ifAbsent) { - return old; - } - entry.setValue(newValue); - if (entry.hit() % SAMPLE_INTERVAL == 0) { - bumpAccess(entry); - } - } - - if (cache.size() > maxEntries) { - //remove the oldest - CacheEntry oldest = accessQueue.poll(); - if (oldest != entry) { - this.remove(oldest.key()); - } - } - - return old; - } - - public V replace(K key, V newValue) { - CacheEntry cacheEntry = get0(key); - if (cacheEntry == null) return null; - - bumpAccess(cacheEntry); - V old = cacheEntry.getValue(); - cacheEntry.setValue(newValue); - if (removeCallback != null) { - removeCallback.afterRemove(key, old); - } - return old; - } - - public boolean replace(K key, V oldValue, V newValue) { - CacheEntry cacheEntry = get0(key); - if (cacheEntry == null || cacheEntry.getValue() != oldValue) { - return false; - } - - - boolean ret = cacheEntry.setValue(oldValue, newValue); - if (ret) { - bumpAccess(cacheEntry); - } - - if (removeCallback != null) { - removeCallback.afterRemove(key, oldValue); - } - - return ret; - } - - public V get(Object key) { - CacheEntry cacheEntry = get0(key); - if (cacheEntry == null) return null; - - return cacheEntry.getValue(); - } - - private CacheEntry get0(Object key) { - @SuppressWarnings("SuspiciousMethodCalls") - CacheEntry cacheEntry = cache.get(key); - if (cacheEntry == null) { - return null; - } - - if (cacheEntry.hit() % SAMPLE_INTERVAL == 0) { - bumpAccess(cacheEntry); - } - return cacheEntry; - } - - private void bumpAccess(CacheEntry cacheEntry) { - Object prevToken = cacheEntry.claimToken(); - if (prevToken == Boolean.FALSE) - return; - - if (prevToken != null) { - accessQueue.removeToken(prevToken); - } - - Object token = null; - try { - token = accessQueue.offerLastAndReturnToken(cacheEntry); - } catch (Throwable t) { - // In case of disaster (OOME), we need to release the claim, so leave it aas null - } - - if (!cacheEntry.setToken(token) && token != null) { // Always set if null - accessQueue.removeToken(token); - } - } - - public boolean remove(Object key, Object value) { - CacheEntry toRemove = cache.get(key); - if (toRemove == null || toRemove.getValue() != value || !cache.remove(key, toRemove)) { - return false; - } - Object old = toRemove.killToken(); - if (old != null) { - accessQueue.removeToken(old); - } - return true; - } - - public V remove(Object key) { - CacheEntry remove = cache.remove(key); - if (remove == null) { - return null; - } - Object old = remove.killToken(); - if (old != null) { - accessQueue.removeToken(old); - } - if (removeCallback != null) { - removeCallback.afterRemove(remove.key(), remove.getValue()); - } - return remove.getValue(); - } - - public void clear() { - if (removeCallback == null) { - cache.clear(); - accessQueue.clear(); - } else { - for (Iterator> iter = entrySet().iterator(); iter.hasNext();) { - iter.next(); - iter.remove(); - } - } - } - - public int size() { - return cache.size(); - } - - @Override - public Set> entrySet() { - return new WrappedEntrySet(cache.entrySet()); - } - - @Override - public V putIfAbsent(K key, V value) { - return put(key, value, true); - } - - public static final class CacheEntry { - private static final Object CLAIM_TOKEN = new Object(); - private static final Object TOKEN_AVAILABLE = new Object(); - private static final Object DEAD_TOKEN = new Object(); - - private static final AtomicIntegerFieldUpdater hitsUpdater = AtomicIntegerFieldUpdater.newUpdater(CacheEntry.class, "hits"); - private static final AtomicReferenceFieldUpdater tokenUpdater = AtomicReferenceFieldUpdater.newUpdater(CacheEntry.class, Object.class, "tokenState"); - private static final AtomicReferenceFieldUpdater valueUpdater = AtomicReferenceFieldUpdater.newUpdater(CacheEntry.class, Object.class, "value"); - - private final K key; - private volatile V value; - private volatile int hits = 1; - - @SuppressWarnings("UnusedDeclaration") - private volatile Object tokenState = TOKEN_AVAILABLE; - private volatile Object accessToken; - - private CacheEntry(K key, V value) { - this.key = key; - this.value = value; - } - - public V setValue(final V value) { - V old = this.value; - this.value = value; - return old; - } - - public boolean setValue(final V oldValue, V newValue) { - return valueUpdater.compareAndSet(this, oldValue, newValue); - } - - public V getValue() { - return value; - } - - public int hit() { - for (; ; ) { - int i = hits; - - if (hitsUpdater.weakCompareAndSet(this, i, ++i)) { - return i; - } - - } - } - - public K key() { - return key; - } - - Object claimToken() { - for (;;) { - if (tokenState == DEAD_TOKEN) { - return Boolean.FALSE; - } - if (tokenUpdater.compareAndSet(this, TOKEN_AVAILABLE, CLAIM_TOKEN)) { - return accessToken; - } - } - } - - Object killToken() { - Object old = claimToken(); - tokenState = DEAD_TOKEN; - return old; - } - - boolean setToken(Object token) { - this.accessToken = token; - this.tokenState = TOKEN_AVAILABLE; - return true; - } - - public String toString() { - return key.toString(); - } - } - - private class WrappedEntrySet extends AbstractSet> { - private Set>> set; - - public WrappedEntrySet(Set>> set) { - this.set = set; - } - - public Iterator> iterator() { - return new WrappedIterator(set.iterator()); - } - - @Override - public int size() { - return set.size(); - } - - @Override - public boolean contains(Object o) { - if (!(o instanceof Entry)) - return false; - Entry e = (Entry)o; - V v = LRUCache.this.get(e.getKey()); - return v != null && v.equals(e.getValue()); - } - - @Override - public boolean remove(Object o) { - if (!(o instanceof Entry)) - return false; - Entry e = (Entry)o; - return LRUCache.this.remove(e.getKey()) != null; - } - - public boolean isEmpty() { - return LRUCache.this.isEmpty(); - } - - public void clear() { - LRUCache.this.clear(); - } - } - - private class WrappedIterator implements Iterator> { - private final Iterator>> iterator; - private CacheEntry last; - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public Entry next() { - final Entry> next = iterator.next(); - last = next.getValue(); - - return new Entry() { - @Override - public K getKey() { - return next.getKey(); - } - - @Override - public V getValue() { - return next.getValue().getValue(); - } - - @Override - public V setValue(V value) { - return next.getValue().setValue(value); - } - }; - } - - @Override - public void remove() { - if (last == null) { - throw new IllegalStateException("next() not called"); - } - LRUCache.this.remove(last.key()); - } - - public WrappedIterator(Iterator>> iterator) { - this.iterator = iterator; - } - } -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/lru/PortableConcurrentDirectDeque.java b/security/plugins/src/main/java/org/jboss/as/security/lru/PortableConcurrentDirectDeque.java deleted file mode 100644 index ee2d63893492..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/lru/PortableConcurrentDirectDeque.java +++ /dev/null @@ -1,1476 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014 Red Hat, Inc., and individual contributors - * as indicated by the @author tags. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Written by Doug Lea and Martin Buchholz with assistance from members of - * JCP JSR-166 Expert Group and released to the public domain, as explained - * at http://creativecommons.org/publicdomain/zero/1.0/ - */ - -package org.jboss.as.security.lru; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Deque; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; - -/** - * A modified version of ConcurrentLinkedDequeue which includes direct - * removal and is portable accross all JVMs. This is only a fallback if - * the JVM does not offer access to Unsafe. - * - * More specifically, an unbounded concurrent {@linkplain java.util.Deque deque} based on linked nodes. - * Concurrent insertion, removal, and access operations execute safely - * across multiple threads. - * A {@code ConcurrentLinkedDeque} is an appropriate choice when - * many threads will share access to a common collection. - * Like most other concurrent collection implementations, this class - * does not permit the use of {@code null} elements. - * - *

Iterators are weakly consistent, returning elements - * reflecting the state of the deque at some point at or since the - * creation of the iterator. They do not throw {@link - * java.util.ConcurrentModificationException - * ConcurrentModificationException}, and may proceed concurrently with - * other operations. - * - *

Beware that, unlike in most collections, the {@code size} method - * is NOT a constant-time operation. Because of the - * asynchronous nature of these deques, determining the current number - * of elements requires a traversal of the elements, and so may report - * inaccurate results if this collection is modified during traversal. - * Additionally, the bulk operations {@code addAll}, - * {@code removeAll}, {@code retainAll}, {@code containsAll}, - * {@code equals}, and {@code toArray} are not guaranteed - * to be performed atomically. For example, an iterator operating - * concurrently with an {@code addAll} operation might view only some - * of the added elements. - * - *

This class and its iterator implement all of the optional - * methods of the {@link java.util.Deque} and {@link java.util.Iterator} interfaces. - * - *

Memory consistency effects: As with other concurrent collections, - * actions in a thread prior to placing an object into a - * {@code ConcurrentLinkedDeque} - * happen-before - * actions subsequent to the access or removal of that element from - * the {@code ConcurrentLinkedDeque} in another thread. - * - *

This class is a member of the - * - * Java Collections Framework. - * - * @since 1.7 - * @author Doug Lea - * @author Martin Buchholz - * @author Jason T. Grene - * @param the type of elements held in this collection - */ - -public class PortableConcurrentDirectDeque - extends ConcurrentDirectDeque implements Deque, java.io.Serializable { - - /* - * This is an implementation of a concurrent lock-free deque - * supporting interior removes but not interior insertions, as - * required to support the entire Deque interface. - * - * We extend the techniques developed for ConcurrentLinkedQueue and - * LinkedTransferQueue (see the internal docs for those classes). - * Understanding the ConcurrentLinkedQueue implementation is a - * prerequisite for understanding the implementation of this class. - * - * The data structure is a symmetrical doubly-linked "GC-robust" - * linked list of nodes. We minimize the number of volatile writes - * using two techniques: advancing multiple hops with a single CAS - * and mixing volatile and non-volatile writes of the same memory - * locations. - * - * A node contains the expected E ("item") and links to predecessor - * ("prev") and successor ("next") nodes: - * - * class Node { volatile Node prev, next; volatile E item; } - * - * A node p is considered "live" if it contains a non-null item - * (p.item != null). When an item is CASed to null, the item is - * atomically logically deleted from the collection. - * - * At any time, there is precisely one "first" node with a null - * prev reference that terminates any chain of prev references - * starting at a live node. Similarly there is precisely one - * "last" node terminating any chain of next references starting at - * a live node. The "first" and "last" nodes may or may not be live. - * The "first" and "last" nodes are always mutually reachable. - * - * A new element is added atomically by CASing the null prev or - * next reference in the first or last node to a fresh node - * containing the element. The element's node atomically becomes - * "live" at that point. - * - * A node is considered "active" if it is a live node, or the - * first or last node. Active nodes cannot be unlinked. - * - * A "self-link" is a next or prev reference that is the same node: - * p.prev == p or p.next == p - * Self-links are used in the node unlinking process. Active nodes - * never have self-links. - * - * A node p is active if and only if: - * - * p.item != null || - * (p.prev == null && p.next != p) || - * (p.next == null && p.prev != p) - * - * The deque object has two node references, "head" and "tail". - * The head and tail are only approximations to the first and last - * nodes of the deque. The first node can always be found by - * following prev pointers from head; likewise for tail. However, - * it is permissible for head and tail to be referring to deleted - * nodes that have been unlinked and so may not be reachable from - * any live node. - * - * There are 3 stages of node deletion; - * "logical deletion", "unlinking", and "gc-unlinking". - * - * 1. "logical deletion" by CASing item to null atomically removes - * the element from the collection, and makes the containing node - * eligible for unlinking. - * - * 2. "unlinking" makes a deleted node unreachable from active - * nodes, and thus eventually reclaimable by GC. Unlinked nodes - * may remain reachable indefinitely from an iterator. - * - * Physical node unlinking is merely an optimization (albeit a - * critical one), and so can be performed at our convenience. At - * any time, the set of live nodes maintained by prev and next - * links are identical, that is, the live nodes found via next - * links from the first node is equal to the elements found via - * prev links from the last node. However, this is not true for - * nodes that have already been logically deleted - such nodes may - * be reachable in one direction only. - * - * 3. "gc-unlinking" takes unlinking further by making active - * nodes unreachable from deleted nodes, making it easier for the - * GC to reclaim future deleted nodes. This step makes the data - * structure "gc-robust", as first described in detail by Boehm - * (http://portal.acm.org/citation.cfm?doid=503272.503282). - * - * GC-unlinked nodes may remain reachable indefinitely from an - * iterator, but unlike unlinked nodes, are never reachable from - * head or tail. - * - * Making the data structure GC-robust will eliminate the risk of - * unbounded memory retention with conservative GCs and is likely - * to improve performance with generational GCs. - * - * When a node is dequeued at either end, e.g. via poll(), we would - * like to break any references from the node to active nodes. We - * develop further the use of self-links that was very effective in - * other concurrent collection classes. The idea is to replace - * prev and next pointers with special values that are interpreted - * to mean off-the-list-at-one-end. These are approximations, but - * good enough to preserve the properties we want in our - * traversals, e.g. we guarantee that a traversal will never visit - * the same element twice, but we don't guarantee whether a - * traversal that runs out of elements will be able to see more - * elements later after enqueues at that end. Doing gc-unlinking - * safely is particularly tricky, since any node can be in use - * indefinitely (for example by an iterator). We must ensure that - * the nodes pointed at by head/tail never get gc-unlinked, since - * head/tail are needed to get "back on track" by other nodes that - * are gc-unlinked. gc-unlinking accounts for much of the - * implementation complexity. - * - * Since neither unlinking nor gc-unlinking are necessary for - * correctness, there are many implementation choices regarding - * frequency (eagerness) of these operations. Since volatile - * reads are likely to be much cheaper than CASes, saving CASes by - * unlinking multiple adjacent nodes at a time may be a win. - * gc-unlinking can be performed rarely and still be effective, - * since it is most important that long chains of deleted nodes - * are occasionally broken. - * - * The actual representation we use is that p.next == p means to - * goto the first node (which in turn is reached by following prev - * pointers from head), and p.next == null && p.prev == p means - * that the iteration is at an end and that p is a (static final) - * dummy node, NEXT_TERMINATOR, and not the last active node. - * Finishing the iteration when encountering such a TERMINATOR is - * good enough for read-only traversals, so such traversals can use - * p.next == null as the termination condition. When we need to - * find the last (active) node, for enqueueing a new node, we need - * to check whether we have reached a TERMINATOR node; if so, - * restart traversal from tail. - * - * The implementation is completely directionally symmetrical, - * except that most public methods that iterate through the list - * follow next pointers ("forward" direction). - * - * We believe (without full proof) that all single-element deque - * operations (e.g., addFirst, peekLast, pollLast) are linearizable - * (see Herlihy and Shavit's book). However, some combinations of - * operations are known not to be linearizable. In particular, - * when an addFirst(A) is racing with pollFirst() removing B, it is - * possible for an observer iterating over the elements to observe - * A B C and subsequently observe A C, even though no interior - * removes are ever performed. Nevertheless, iterators behave - * reasonably, providing the "weakly consistent" guarantees. - * - * Empirically, microbenchmarks suggest that this class adds about - * 40% overhead relative to ConcurrentLinkedQueue, which feels as - * good as we can hope for. - */ - - private static final long serialVersionUID = 876323262645176354L; - - /** - * A node from which the first node on list (that is, the unique node p - * with p.prev == null && p.next != p) can be reached in O(1) time. - * Invariants: - * - the first node is always O(1) reachable from head via prev links - * - all live nodes are reachable from the first node via succ() - * - head != null - * - (tmp = head).next != tmp || tmp != head - * - head is never gc-unlinked (but may be unlinked) - * Non-invariants: - * - head.item may or may not be null - * - head may not be reachable from the first or last node, or from tail - */ - private transient volatile Node head; - - /** - * A node from which the last node on list (that is, the unique node p - * with p.next == null && p.prev != p) can be reached in O(1) time. - * Invariants: - * - the last node is always O(1) reachable from tail via next links - * - all live nodes are reachable from the last node via pred() - * - tail != null - * - tail is never gc-unlinked (but may be unlinked) - * Non-invariants: - * - tail.item may or may not be null - * - tail may not be reachable from the first or last node, or from head - */ - private transient volatile Node tail; - - private static final AtomicReferenceFieldUpdater headUpdater = AtomicReferenceFieldUpdater.newUpdater(PortableConcurrentDirectDeque.class, Node.class, "head"); - private static final AtomicReferenceFieldUpdater tailUpdater = AtomicReferenceFieldUpdater.newUpdater(PortableConcurrentDirectDeque.class, Node.class, "tail"); - - private static final Node PREV_TERMINATOR, NEXT_TERMINATOR; - - @SuppressWarnings("unchecked") - Node prevTerminator() { - return (Node) PREV_TERMINATOR; - } - - @SuppressWarnings("unchecked") - Node nextTerminator() { - return (Node) NEXT_TERMINATOR; - } - - static final class Node { - private static final AtomicReferenceFieldUpdater prevUpdater = AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "prev"); - private static final AtomicReferenceFieldUpdater nextUpdater = AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "next"); - private static final AtomicReferenceFieldUpdater itemUpdater = AtomicReferenceFieldUpdater.newUpdater(Node.class, Object.class, "item"); - - - volatile Node prev; - volatile E item; - volatile Node next; - - Node() { // default constructor for NEXT_TERMINATOR, PREV_TERMINATOR - } - - /** - * Constructs a new node. Uses relaxed write because item can - * only be seen after publication via casNext or casPrev. - */ - Node(E item) { - this.item = item; - } - - boolean casItem(E cmp, E val) { - return itemUpdater.compareAndSet(this, cmp, val); - } - - void lazySetNext(Node val) { - next = val; - } - - boolean casNext(Node cmp, Node val) { - return nextUpdater.compareAndSet(this, cmp, val); - } - - void lazySetPrev(Node val) { - prev = val; - } - - boolean casPrev(Node cmp, Node val) { - return prevUpdater.compareAndSet(this, cmp, val); - } - } - - /** - * Links e as first element. - */ - private Node linkFirst(E e) { - checkNotNull(e); - final Node newNode = new Node<>(e); - - restartFromHead: - for (;;) - for (Node h = head, p = h, q;;) { - if ((q = p.prev) != null && - (q = (p = q).prev) != null) - // Check for head updates every other hop. - // If p == q, we are sure to follow head instead. - p = (h != (h = head)) ? h : q; - else if (p.next == p) // PREV_TERMINATOR - continue restartFromHead; - else { - // p is first node - newNode.lazySetNext(p); // CAS piggyback - if (p.casPrev(null, newNode)) { - // Successful CAS is the linearization point - // for e to become an element of this deque, - // and for newNode to become "live". - if (p != h) // hop two nodes at a time - casHead(h, newNode); // Failure is OK. - return newNode; - } - // Lost CAS race to another thread; re-read prev - } - } - } - - /** - * Links e as last element. - */ - private Node linkLast(E e) { - checkNotNull(e); - final Node newNode = new Node<>(e); - - restartFromTail: - for (;;) - for (Node t = tail, p = t, q;;) { - if ((q = p.next) != null && - (q = (p = q).next) != null) - // Check for tail updates every other hop. - // If p == q, we are sure to follow tail instead. - p = (t != (t = tail)) ? t : q; - else if (p.prev == p) // NEXT_TERMINATOR - continue restartFromTail; - else { - // p is last node - newNode.lazySetPrev(p); // CAS piggyback - if (p.casNext(null, newNode)) { - // Successful CAS is the linearization point - // for e to become an element of this deque, - // and for newNode to become "live". - if (p != t) // hop two nodes at a time - casTail(t, newNode); // Failure is OK. - return newNode; - } - // Lost CAS race to another thread; re-read next - } - } - } - - private static final int HOPS = 2; - - /** - * Unlinks non-null node x. - */ - void unlink(Node x) { - // assert x != null; - // assert x.item == null; - // assert x != PREV_TERMINATOR; - // assert x != NEXT_TERMINATOR; - - final Node prev = x.prev; - final Node next = x.next; - if (prev == null) { - unlinkFirst(x, next); - } else if (next == null) { - unlinkLast(x, prev); - } else { - // Unlink interior node. - // - // This is the common case, since a series of polls at the - // same end will be "interior" removes, except perhaps for - // the first one, since end nodes cannot be unlinked. - // - // At any time, all active nodes are mutually reachable by - // following a sequence of either next or prev pointers. - // - // Our strategy is to find the unique active predecessor - // and successor of x. Try to fix up their links so that - // they point to each other, leaving x unreachable from - // active nodes. If successful, and if x has no live - // predecessor/successor, we additionally try to gc-unlink, - // leaving active nodes unreachable from x, by rechecking - // that the status of predecessor and successor are - // unchanged and ensuring that x is not reachable from - // tail/head, before setting x's prev/next links to their - // logical approximate replacements, self/TERMINATOR. - Node activePred, activeSucc; - boolean isFirst, isLast; - int hops = 1; - - // Find active predecessor - for (Node p = prev; ; ++hops) { - if (p.item != null) { - activePred = p; - isFirst = false; - break; - } - Node q = p.prev; - if (q == null) { - if (p.next == p) - return; - activePred = p; - isFirst = true; - break; - } - else if (p == q) - return; - else - p = q; - } - - // Find active successor - for (Node p = next; ; ++hops) { - if (p.item != null) { - activeSucc = p; - isLast = false; - break; - } - Node q = p.next; - if (q == null) { - if (p.prev == p) - return; - activeSucc = p; - isLast = true; - break; - } - else if (p == q) - return; - else - p = q; - } - - // TODO: better HOP heuristics - if (hops < HOPS - // always squeeze out interior deleted nodes - && (isFirst | isLast)) - return; - - // Squeeze out deleted nodes between activePred and - // activeSucc, including x. - skipDeletedSuccessors(activePred); - skipDeletedPredecessors(activeSucc); - - // Try to gc-unlink, if possible - if ((isFirst | isLast) && - - // Recheck expected state of predecessor and successor - (activePred.next == activeSucc) && - (activeSucc.prev == activePred) && - (isFirst ? activePred.prev == null : activePred.item != null) && - (isLast ? activeSucc.next == null : activeSucc.item != null)) { - - updateHead(); // Ensure x is not reachable from head - updateTail(); // Ensure x is not reachable from tail - - // Finally, actually gc-unlink - x.lazySetPrev(isFirst ? prevTerminator() : x); - x.lazySetNext(isLast ? nextTerminator() : x); - } - } - } - - /** - * Unlinks non-null first node. - */ - private void unlinkFirst(Node first, Node next) { - // assert first != null; - // assert next != null; - // assert first.item == null; - for (Node o = null, p = next, q;;) { - if (p.item != null || (q = p.next) == null) { - if (o != null && p.prev != p && first.casNext(next, p)) { - skipDeletedPredecessors(p); - if (first.prev == null && - (p.next == null || p.item != null) && - p.prev == first) { - - updateHead(); // Ensure o is not reachable from head - updateTail(); // Ensure o is not reachable from tail - - // Finally, actually gc-unlink - o.lazySetNext(o); - o.lazySetPrev(prevTerminator()); - } - } - return; - } - else if (p == q) - return; - else { - o = p; - p = q; - } - } - } - - /** - * Unlinks non-null last node. - */ - private void unlinkLast(Node last, Node prev) { - // assert last != null; - // assert prev != null; - // assert last.item == null; - for (Node o = null, p = prev, q;;) { - if (p.item != null || (q = p.prev) == null) { - if (o != null && p.next != p && last.casPrev(prev, p)) { - skipDeletedSuccessors(p); - if (last.next == null && - (p.prev == null || p.item != null) && - p.next == last) { - - updateHead(); // Ensure o is not reachable from head - updateTail(); // Ensure o is not reachable from tail - - // Finally, actually gc-unlink - o.lazySetPrev(o); - o.lazySetNext(nextTerminator()); - } - } - return; - } - else if (p == q) - return; - else { - o = p; - p = q; - } - } - } - - /** - * Guarantees that any node which was unlinked before a call to - * this method will be unreachable from head after it returns. - * Does not guarantee to eliminate slack, only that head will - * point to a node that was active while this method was running. - */ - private void updateHead() { - // Either head already points to an active node, or we keep - // trying to cas it to the first node until it does. - Node h, p, q; - restartFromHead: - while ((h = head).item == null && (p = h.prev) != null) { - for (;;) { - if ((q = p.prev) == null || - (q = (p = q).prev) == null) { - // It is possible that p is PREV_TERMINATOR, - // but if so, the CAS is guaranteed to fail. - if (casHead(h, p)) - return; - else - continue restartFromHead; - } - else if (h != head) - continue restartFromHead; - else - p = q; - } - } - } - - /** - * Guarantees that any node which was unlinked before a call to - * this method will be unreachable from tail after it returns. - * Does not guarantee to eliminate slack, only that tail will - * point to a node that was active while this method was running. - */ - private void updateTail() { - // Either tail already points to an active node, or we keep - // trying to cas it to the last node until it does. - Node t, p, q; - restartFromTail: - while ((t = tail).item == null && (p = t.next) != null) { - for (;;) { - if ((q = p.next) == null || - (q = (p = q).next) == null) { - // It is possible that p is NEXT_TERMINATOR, - // but if so, the CAS is guaranteed to fail. - if (casTail(t, p)) - return; - else - continue restartFromTail; - } - else if (t != tail) - continue restartFromTail; - else - p = q; - } - } - } - - private void skipDeletedPredecessors(Node x) { - whileActive: - do { - Node prev = x.prev; - // assert prev != null; - // assert x != NEXT_TERMINATOR; - // assert x != PREV_TERMINATOR; - Node p = prev; - findActive: - for (;;) { - if (p.item != null) - break findActive; - Node q = p.prev; - if (q == null) { - if (p.next == p) - continue whileActive; - break findActive; - } - else if (p == q) - continue whileActive; - else - p = q; - } - - // found active CAS target - if (prev == p || x.casPrev(prev, p)) - return; - - } while (x.item != null || x.next == null); - } - - private void skipDeletedSuccessors(Node x) { - whileActive: - do { - Node next = x.next; - // assert next != null; - // assert x != NEXT_TERMINATOR; - // assert x != PREV_TERMINATOR; - Node p = next; - findActive: - for (;;) { - if (p.item != null) - break findActive; - Node q = p.next; - if (q == null) { - if (p.prev == p) - continue whileActive; - break findActive; - } - else if (p == q) - continue whileActive; - else - p = q; - } - - // found active CAS target - if (next == p || x.casNext(next, p)) - return; - - } while (x.item != null || x.prev == null); - } - - /** - * Returns the successor of p, or the first node if p.next has been - * linked to self, which will only be true if traversing with a - * stale pointer that is now off the list. - */ - final Node succ(Node p) { - // TODO: should we skip deleted nodes here? - Node q = p.next; - return (p == q) ? first() : q; - } - - /** - * Returns the predecessor of p, or the last node if p.prev has been - * linked to self, which will only be true if traversing with a - * stale pointer that is now off the list. - */ - final Node pred(Node p) { - Node q = p.prev; - return (p == q) ? last() : q; - } - - /** - * Returns the first node, the unique node p for which: - * p.prev == null && p.next != p - * The returned node may or may not be logically deleted. - * Guarantees that head is set to the returned node. - */ - Node first() { - restartFromHead: - for (;;) - for (Node h = head, p = h, q;;) { - if ((q = p.prev) != null && - (q = (p = q).prev) != null) - // Check for head updates every other hop. - // If p == q, we are sure to follow head instead. - p = (h != (h = head)) ? h : q; - else if (p == h - // It is possible that p is PREV_TERMINATOR, - // but if so, the CAS is guaranteed to fail. - || casHead(h, p)) - return p; - else - continue restartFromHead; - } - } - - /** - * Returns the last node, the unique node p for which: - * p.next == null && p.prev != p - * The returned node may or may not be logically deleted. - * Guarantees that tail is set to the returned node. - */ - Node last() { - restartFromTail: - for (;;) - for (Node t = tail, p = t, q;;) { - if ((q = p.next) != null && - (q = (p = q).next) != null) - // Check for tail updates every other hop. - // If p == q, we are sure to follow tail instead. - p = (t != (t = tail)) ? t : q; - else if (p == t - // It is possible that p is NEXT_TERMINATOR, - // but if so, the CAS is guaranteed to fail. - || casTail(t, p)) - return p; - else - continue restartFromTail; - } - } - - // Minor convenience utilities - - /** - * Throws NullPointerException if argument is null. - * - * @param v the element - */ - private static void checkNotNull(Object v) { - if (v == null) - throw new NullPointerException(); - } - - /** - * Returns element unless it is null, in which case throws - * NoSuchElementException. - * - * @param v the element - * @return the element - */ - private E screenNullResult(E v) { - if (v == null) - throw new NoSuchElementException(); - return v; - } - - /** - * Creates an array list and fills it with elements of this list. - * Used by toArray. - * - * @return the arrayList - */ - private ArrayList toArrayList() { - ArrayList list = new ArrayList<>(); - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null) - list.add(item); - } - return list; - } - - /** - * Constructs an empty deque. - */ - public PortableConcurrentDirectDeque() { - head = tail = new Node<>(null); - } - - /** - * Constructs a deque initially containing the elements of - * the given collection, added in traversal order of the - * collection's iterator. - * - * @param c the collection of elements to initially contain - * @throws NullPointerException if the specified collection or any - * of its elements are null - */ - public PortableConcurrentDirectDeque(Collection c) { - // Copy c into a private chain of Nodes - Node h = null, t = null; - for (E e : c) { - checkNotNull(e); - Node newNode = new Node<>(e); - if (h == null) - h = t = newNode; - else { - t.lazySetNext(newNode); - newNode.lazySetPrev(t); - t = newNode; - } - } - initHeadTail(h, t); - } - - /** - * Initializes head and tail, ensuring invariants hold. - */ - private void initHeadTail(Node h, Node t) { - if (h == t) { - if (h == null) - h = t = new Node<>(null); - else { - // Avoid edge case of a single Node with non-null item. - Node newNode = new Node<>(null); - t.lazySetNext(newNode); - newNode.lazySetPrev(t); - t = newNode; - } - } - head = h; - tail = t; - } - - /** - * Inserts the specified element at the front of this deque. - * As the deque is unbounded, this method will never throw - * {@link IllegalStateException}. - * - * @throws NullPointerException if the specified element is null - */ - public void addFirst(E e) { - linkFirst(e); - } - - /** - * Inserts the specified element at the end of this deque. - * As the deque is unbounded, this method will never throw - * {@link IllegalStateException}. - * - *

This method is equivalent to {@link #add}. - * - * @throws NullPointerException if the specified element is null - */ - public void addLast(E e) { - linkLast(e); - } - - /** - * Inserts the specified element at the front of this deque. - * As the deque is unbounded, this method will never return {@code false}. - * - * @return {@code true} (as specified by {@link java.util.Deque#offerFirst}) - * @throws NullPointerException if the specified element is null - */ - public boolean offerFirst(E e) { - linkFirst(e); - return true; - } - - public Object offerFirstAndReturnToken(E e) { - return linkFirst(e); - } - - public Object offerLastAndReturnToken(E e) { - return linkLast(e); - } - - @SuppressWarnings("unchecked") - public void removeToken(Object token) { - if (!(token instanceof Node)) { - throw new IllegalArgumentException(); - } - - Node node = (Node) (token); - for (;;) { - Object item = node.item; - if (item == null) { - break; - } - if (node.casItem(item, null)) { - unlink(node); - break; - } - } - } - - /** - * Inserts the specified element at the end of this deque. - * As the deque is unbounded, this method will never return {@code false}. - * - *

This method is equivalent to {@link #add}. - * - * @return {@code true} (as specified by {@link java.util.Deque#offerLast}) - * @throws NullPointerException if the specified element is null - */ - public boolean offerLast(E e) { - linkLast(e); - return true; - } - - public E peekFirst() { - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null) - return item; - } - return null; - } - - public E peekLast() { - for (Node p = last(); p != null; p = pred(p)) { - E item = p.item; - if (item != null) - return item; - } - return null; - } - - /** - * @throws java.util.NoSuchElementException {@inheritDoc} - */ - public E getFirst() { - return screenNullResult(peekFirst()); - } - - /** - * @throws java.util.NoSuchElementException {@inheritDoc} - */ - public E getLast() { - return screenNullResult(peekLast()); - } - - public E pollFirst() { - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null && p.casItem(item, null)) { - unlink(p); - return item; - } - } - return null; - } - - public E pollLast() { - for (Node p = last(); p != null; p = pred(p)) { - E item = p.item; - if (item != null && p.casItem(item, null)) { - unlink(p); - return item; - } - } - return null; - } - - /** - * @throws java.util.NoSuchElementException {@inheritDoc} - */ - public E removeFirst() { - return screenNullResult(pollFirst()); - } - - /** - * @throws java.util.NoSuchElementException {@inheritDoc} - */ - public E removeLast() { - return screenNullResult(pollLast()); - } - - // *** Queue and stack methods *** - - /** - * Inserts the specified element at the tail of this deque. - * As the deque is unbounded, this method will never return {@code false}. - * - * @return {@code true} (as specified by {@link java.util.Queue#offer}) - * @throws NullPointerException if the specified element is null - */ - public boolean offer(E e) { - return offerLast(e); - } - - /** - * Inserts the specified element at the tail of this deque. - * As the deque is unbounded, this method will never throw - * {@link IllegalStateException} or return {@code false}. - * - * @return {@code true} (as specified by {@link java.util.Collection#add}) - * @throws NullPointerException if the specified element is null - */ - public boolean add(E e) { - return offerLast(e); - } - - public E poll() { - return pollFirst(); - } - public E remove() { - return removeFirst(); - } - public E peek() { - return peekFirst(); - } - public E element() { - return getFirst(); - } - public void push(E e) { - addFirst(e); - } - public E pop() { - return removeFirst(); - } - - /** - * Removes the first element {@code e} such that - * {@code o.equals(e)}, if such an element exists in this deque. - * If the deque does not contain the element, it is unchanged. - * - * @param o element to be removed from this deque, if present - * @return {@code true} if the deque contained the specified element - * @throws NullPointerException if the specified element is null - */ - public boolean removeFirstOccurrence(Object o) { - checkNotNull(o); - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null && o.equals(item) && p.casItem(item, null)) { - unlink(p); - return true; - } - } - return false; - } - - /** - * Removes the last element {@code e} such that - * {@code o.equals(e)}, if such an element exists in this deque. - * If the deque does not contain the element, it is unchanged. - * - * @param o element to be removed from this deque, if present - * @return {@code true} if the deque contained the specified element - * @throws NullPointerException if the specified element is null - */ - public boolean removeLastOccurrence(Object o) { - checkNotNull(o); - for (Node p = last(); p != null; p = pred(p)) { - E item = p.item; - if (item != null && o.equals(item) && p.casItem(item, null)) { - unlink(p); - return true; - } - } - return false; - } - - /** - * Returns {@code true} if this deque contains at least one - * element {@code e} such that {@code o.equals(e)}. - * - * @param o element whose presence in this deque is to be tested - * @return {@code true} if this deque contains the specified element - */ - public boolean contains(Object o) { - if (o == null) return false; - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null && o.equals(item)) - return true; - } - return false; - } - - /** - * Returns {@code true} if this collection contains no elements. - * - * @return {@code true} if this collection contains no elements - */ - public boolean isEmpty() { - return peekFirst() == null; - } - - /** - * Returns the number of elements in this deque. If this deque - * contains more than {@code Integer.MAX_VALUE} elements, it - * returns {@code Integer.MAX_VALUE}. - * - *

Beware that, unlike in most collections, this method is - * NOT a constant-time operation. Because of the - * asynchronous nature of these deques, determining the current - * number of elements requires traversing them all to count them. - * Additionally, it is possible for the size to change during - * execution of this method, in which case the returned result - * will be inaccurate. Thus, this method is typically not very - * useful in concurrent applications. - * - * @return the number of elements in this deque - */ - public int size() { - int count = 0; - for (Node p = first(); p != null; p = succ(p)) - if (p.item != null) - // Collection.size() spec says to max out - if (++count == Integer.MAX_VALUE) - break; - return count; - } - - /** - * Removes the first element {@code e} such that - * {@code o.equals(e)}, if such an element exists in this deque. - * If the deque does not contain the element, it is unchanged. - * - * @param o element to be removed from this deque, if present - * @return {@code true} if the deque contained the specified element - * @throws NullPointerException if the specified element is null - */ - public boolean remove(Object o) { - return removeFirstOccurrence(o); - } - - /** - * Appends all of the elements in the specified collection to the end of - * this deque, in the order that they are returned by the specified - * collection's iterator. Attempts to {@code addAll} of a deque to - * itself result in {@code IllegalArgumentException}. - * - * @param c the elements to be inserted into this deque - * @return {@code true} if this deque changed as a result of the call - * @throws NullPointerException if the specified collection or any - * of its elements are null - * @throws IllegalArgumentException if the collection is this deque - */ - public boolean addAll(Collection c) { - if (c == this) - // As historically specified in AbstractQueue#addAll - throw new IllegalArgumentException(); - - // Copy c into a private chain of Nodes - Node beginningOfTheEnd = null, last = null; - for (E e : c) { - checkNotNull(e); - Node newNode = new Node<>(e); - if (beginningOfTheEnd == null) - beginningOfTheEnd = last = newNode; - else { - last.lazySetNext(newNode); - newNode.lazySetPrev(last); - last = newNode; - } - } - if (beginningOfTheEnd == null) - return false; - - // Atomically append the chain at the tail of this collection - restartFromTail: - for (;;) - for (Node t = tail, p = t, q;;) { - if ((q = p.next) != null && - (q = (p = q).next) != null) - // Check for tail updates every other hop. - // If p == q, we are sure to follow tail instead. - p = (t != (t = tail)) ? t : q; - else if (p.prev == p) // NEXT_TERMINATOR - continue restartFromTail; - else { - // p is last node - beginningOfTheEnd.lazySetPrev(p); // CAS piggyback - if (p.casNext(null, beginningOfTheEnd)) { - // Successful CAS is the linearization point - // for all elements to be added to this deque. - if (!casTail(t, last)) { - // Try a little harder to update tail, - // since we may be adding many elements. - t = tail; - if (last.next == null) - casTail(t, last); - } - return true; - } - // Lost CAS race to another thread; re-read next - } - } - } - - /** - * Removes all of the elements from this deque. - */ - public void clear() { - while (pollFirst() != null) { } - } - - /** - * Returns an array containing all of the elements in this deque, in - * proper sequence (from first to last element). - * - *

The returned array will be "safe" in that no references to it are - * maintained by this deque. (In other words, this method must allocate - * a new array). The caller is thus free to modify the returned array. - * - *

This method acts as bridge between array-based and collection-based - * APIs. - * - * @return an array containing all of the elements in this deque - */ - public Object[] toArray() { - return toArrayList().toArray(); - } - - /** - * Returns an array containing all of the elements in this deque, - * in proper sequence (from first to last element); the runtime - * type of the returned array is that of the specified array. If - * the deque fits in the specified array, it is returned therein. - * Otherwise, a new array is allocated with the runtime type of - * the specified array and the size of this deque. - * - *

If this deque fits in the specified array with room to spare - * (i.e., the array has more elements than this deque), the element in - * the array immediately following the end of the deque is set to - * {@code null}. - * - *

Like the {@link #toArray()} method, this method acts as - * bridge between array-based and collection-based APIs. Further, - * this method allows precise control over the runtime type of the - * output array, and may, under certain circumstances, be used to - * save allocation costs. - * - *

Suppose {@code x} is a deque known to contain only strings. - * The following code can be used to dump the deque into a newly - * allocated array of {@code String}: - * - *

 {@code String[] y = x.toArray(new String[0]);}
- * - * Note that {@code toArray(new Object[0])} is identical in function to - * {@code toArray()}. - * - * @param a the array into which the elements of the deque are to - * be stored, if it is big enough; otherwise, a new array of the - * same runtime type is allocated for this purpose - * @return an array containing all of the elements in this deque - * @throws ArrayStoreException if the runtime type of the specified array - * is not a supertype of the runtime type of every element in - * this deque - * @throws NullPointerException if the specified array is null - */ - public T[] toArray(T[] a) { - return toArrayList().toArray(a); - } - - /** - * Returns an iterator over the elements in this deque in proper sequence. - * The elements will be returned in order from first (head) to last (tail). - * - *

The returned iterator is a "weakly consistent" iterator that - * will never throw {@link java.util.ConcurrentModificationException - * ConcurrentModificationException}, and guarantees to traverse - * elements as they existed upon construction of the iterator, and - * may (but is not guaranteed to) reflect any modifications - * subsequent to construction. - * - * @return an iterator over the elements in this deque in proper sequence - */ - public Iterator iterator() { - return new Itr(); - } - - /** - * Returns an iterator over the elements in this deque in reverse - * sequential order. The elements will be returned in order from - * last (tail) to first (head). - * - *

The returned iterator is a "weakly consistent" iterator that - * will never throw {@link java.util.ConcurrentModificationException - * ConcurrentModificationException}, and guarantees to traverse - * elements as they existed upon construction of the iterator, and - * may (but is not guaranteed to) reflect any modifications - * subsequent to construction. - * - * @return an iterator over the elements in this deque in reverse order - */ - public Iterator descendingIterator() { - return new DescendingItr(); - } - - private abstract class AbstractItr implements Iterator { - /** - * Next node to return item for. - */ - private Node nextNode; - - /** - * nextItem holds on to item fields because once we claim - * that an element exists in hasNext(), we must return it in - * the following next() call even if it was in the process of - * being removed when hasNext() was called. - */ - private E nextItem; - - /** - * Node returned by most recent call to next. Needed by remove. - * Reset to null if this element is deleted by a call to remove. - */ - private Node lastRet; - - abstract Node startNode(); - abstract Node nextNode(Node p); - - AbstractItr() { - advance(); - } - - /** - * Sets nextNode and nextItem to next valid node, or to null - * if no such. - */ - private void advance() { - lastRet = nextNode; - - Node p = (nextNode == null) ? startNode() : nextNode(nextNode); - for (;; p = nextNode(p)) { - if (p == null) { - // p might be active end or TERMINATOR node; both are OK - nextNode = null; - nextItem = null; - break; - } - E item = p.item; - if (item != null) { - nextNode = p; - nextItem = item; - break; - } - } - } - - public boolean hasNext() { - return nextItem != null; - } - - public E next() { - E item = nextItem; - if (item == null) throw new NoSuchElementException(); - advance(); - return item; - } - - public void remove() { - Node l = lastRet; - if (l == null) throw new IllegalStateException(); - l.item = null; - unlink(l); - lastRet = null; - } - } - - /** Forward iterator */ - private class Itr extends AbstractItr { - Node startNode() { - return first(); - } - Node nextNode(Node p) { - return succ(p); - } - } - - /** Descending iterator */ - private class DescendingItr extends AbstractItr { - Node startNode() { - return last(); - } - Node nextNode(Node p) { - return pred(p); - } - } - - /** - * Saves this deque to a stream (that is, serializes it). - * - * @serialData All of the elements (each an {@code E}) in - * the proper order, followed by a null - */ - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - - // Write out any hidden stuff - s.defaultWriteObject(); - - // Write out all elements in the proper order. - for (Node p = first(); p != null; p = succ(p)) { - E item = p.item; - if (item != null) - s.writeObject(item); - } - - // Use trailing null as sentinel - s.writeObject(null); - } - - /** - * Reconstitutes this deque from a stream (that is, deserializes it). - */ - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - - // Read in elements until trailing null sentinel found - Node h = null, t = null; - Object item; - while ((item = s.readObject()) != null) { - @SuppressWarnings("unchecked") - Node newNode = new Node<>((E) item); - if (h == null) - h = t = newNode; - else { - t.lazySetNext(newNode); - newNode.lazySetPrev(t); - t = newNode; - } - } - initHeadTail(h, t); - } - - private boolean casHead(Node cmp, Node val) { - return headUpdater.compareAndSet(this, cmp, val); - } - - private boolean casTail(Node cmp, Node val) { - return tailUpdater.compareAndSet(this, cmp, val); - } - - // Unsafe mechanics - - static { - PREV_TERMINATOR = new Node<>(); - PREV_TERMINATOR.next = PREV_TERMINATOR; - NEXT_TERMINATOR = new Node<>(); - NEXT_TERMINATOR.prev = NEXT_TERMINATOR; - } -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/lru/RemoveCallback.java b/security/plugins/src/main/java/org/jboss/as/security/lru/RemoveCallback.java deleted file mode 100644 index 56b9965c3439..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/lru/RemoveCallback.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.jboss.as.security.lru; - -/** - * Allows an LRU Cache to get a callback after a removal has occurred. - * - * @author Jason T. Greene - */ -public interface RemoveCallback { - void afterRemove(K key, V value); -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/plugins/AuthenticationCacheFactory.java b/security/plugins/src/main/java/org/jboss/as/security/plugins/AuthenticationCacheFactory.java deleted file mode 100644 index e4aba6a78e0f..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/plugins/AuthenticationCacheFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.security.plugins; - -import java.security.Principal; -import java.util.concurrent.ConcurrentMap; - -import org.jboss.security.authentication.JBossCachedAuthenticationManager.DomainInfo; - -/** - * Factory that creates default {@code ConcurrentMap}s for authentication cache. - * - * @author Eduardo Martins - */ -public interface AuthenticationCacheFactory { - - /** - * Returns a cache implementation - * - * @return cache implementation - */ - ConcurrentMap getCache(); -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/plugins/DefaultAuthenticationCacheFactory.java b/security/plugins/src/main/java/org/jboss/as/security/plugins/DefaultAuthenticationCacheFactory.java deleted file mode 100644 index 00e5c6addd4b..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/plugins/DefaultAuthenticationCacheFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2011, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.security.plugins; - -import java.security.Principal; -import java.util.concurrent.ConcurrentMap; - -import org.jboss.as.security.lru.LRUCache; -import org.jboss.security.authentication.JBossCachedAuthenticationManager.DomainInfo; - -/** - * Factory that creates default {@code ConcurrentMap}s for authentication cache. - * - * @author Marcus Moyses - */ -public class DefaultAuthenticationCacheFactory implements AuthenticationCacheFactory { - - /** - * Returns a default cache implementation - * - * @return cache implementation - */ - public ConcurrentMap getCache() { - return new LRUCache<>(1000, (key, value) -> { - if (value != null) { - value.logout(); - } - }); - } -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/plugins/JNDIBasedSecurityManagement.java b/security/plugins/src/main/java/org/jboss/as/security/plugins/JNDIBasedSecurityManagement.java deleted file mode 100644 index 508579464813..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/plugins/JNDIBasedSecurityManagement.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2010, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.security.plugins; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.security.Principal; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.security.auth.callback.CallbackHandler; - -import org.jboss.as.security._private.SecurityLogger; -import org.jboss.modules.ModuleLoader; -import org.jboss.security.AuthenticationManager; -import org.jboss.security.AuthorizationManager; -import org.jboss.security.CacheableManager; -import org.jboss.security.ISecurityManagement; -import org.jboss.security.JSSESecurityDomain; -import org.jboss.security.SecurityConstants; -import org.jboss.security.audit.AuditManager; -import org.jboss.security.identitytrust.IdentityTrustManager; -import org.jboss.security.mapping.MappingManager; - -/** - * JNDI based implementation of {@code ISecurityManagement} - * - * @author Anil.Saldhana@redhat.com - * @author Marcus Moyses - */ -public class JNDIBasedSecurityManagement implements ISecurityManagement { - - private static final long serialVersionUID = 1924631329555621041L; - - private transient ConcurrentHashMap securityMgrMap = new ConcurrentHashMap(); - private transient ConcurrentHashMap authMgrMap = new ConcurrentHashMap(); - private transient ConcurrentHashMap authzMgrMap = new ConcurrentHashMap(); - private transient ConcurrentHashMap auditMgrMap = new ConcurrentHashMap(); - private transient ConcurrentHashMap idmMgrMap = new ConcurrentHashMap(); - private transient ConcurrentHashMap mappingMgrMap = new ConcurrentHashMap(); - private transient ConcurrentHashMap jsseMap = new ConcurrentHashMap(); - - private String authenticationManagerClassName; - private boolean deepCopySubjectMode; - private String callbackHandlerClassName; - private String authorizationManagerClassName; - private String auditManagerClassName; - private String identityTrustManagerClassName; - private String mappingManagerClassName; - private ModuleLoader loader; - - // creating a singleton - public JNDIBasedSecurityManagement(ModuleLoader loader) { - this.loader = loader; - } - - public ConcurrentHashMap getSecurityManagerMap() { - return securityMgrMap; - } - - /** {@inheritDoc} */ - public AuditManager getAuditManager(String securityDomain) { - AuditManager am = null; - try { - am = auditMgrMap.get(securityDomain); - if (am == null) { - am = (AuditManager) lookUpJNDI(securityDomain + "/auditMgr"); - auditMgrMap.put(securityDomain, am); - } - } catch (Exception e) { - SecurityLogger.ROOT_LOGGER.tracef(e, "Exception getting AuditManager for domain=%s", securityDomain); - } - return am; - } - - /** {@inheritDoc} */ - public AuthenticationManager getAuthenticationManager(String securityDomain) { - AuthenticationManager am = null; - try { - am = authMgrMap.get(securityDomain); - if (am == null) { - am = (AuthenticationManager) lookUpJNDI(securityDomain + "/authenticationMgr"); - authMgrMap.put(securityDomain, am); - } - } catch (Exception e) { - SecurityLogger.ROOT_LOGGER.tracef(e, "Exception getting AuthenticationManager for domain=%s", securityDomain); - } - return am; - } - - /** {@inheritDoc} */ - public AuthorizationManager getAuthorizationManager(String securityDomain) { - AuthorizationManager am = null; - try { - am = authzMgrMap.get(securityDomain); - if (am == null) { - am = (AuthorizationManager) lookUpJNDI(securityDomain + "/authorizationMgr"); - authzMgrMap.put(securityDomain, am); - } - } catch (Exception e) { - SecurityLogger.ROOT_LOGGER.tracef(e, "Exception getting AuthorizationManager for domain=%s", securityDomain); - } - return am; - } - - /** {@inheritDoc} */ - public IdentityTrustManager getIdentityTrustManager(String securityDomain) { - IdentityTrustManager itm = null; - try { - itm = idmMgrMap.get(securityDomain); - if (itm == null) { - itm = (IdentityTrustManager) lookUpJNDI(securityDomain + "/identityTrustMgr"); - idmMgrMap.put(securityDomain, itm); - } - } catch (Exception e) { - SecurityLogger.ROOT_LOGGER.tracef(e, "Exception getting IdentityTrustManager for domain=%s" + securityDomain); - } - return itm; - } - - /** {@inheritDoc} */ - public MappingManager getMappingManager(String securityDomain) { - MappingManager mm = null; - try { - mm = mappingMgrMap.get(securityDomain); - if (mm == null) { - mm = (MappingManager) lookUpJNDI(securityDomain + "/mappingMgr"); - mappingMgrMap.put(securityDomain, mm); - } - } catch (Exception e) { - SecurityLogger.ROOT_LOGGER.tracef(e, "Exception getting MappingManager for domain=%s", securityDomain); - } - return mm; - } - - /** {@inheritDoc} */ - public JSSESecurityDomain getJSSE(String securityDomain) { - JSSESecurityDomain jsse = null; - try { - jsse = jsseMap.get(securityDomain); - if (jsse == null) { - jsse = (JSSESecurityDomain) lookUpJNDI(securityDomain + "/jsse"); - jsseMap.put(securityDomain, jsse); - } - } catch (Exception e) { - SecurityLogger.ROOT_LOGGER.tracef(e, "Exception getting JSSESecurityDomain for domain=%s", securityDomain); - } - return jsse; - } - - public String getAuthenticationManagerClassName() { - return authenticationManagerClassName; - } - - public void setAuthenticationManagerClassName(String authenticationManagerClassName) { - this.authenticationManagerClassName = authenticationManagerClassName; - } - - public boolean isDeepCopySubjectMode() { - return deepCopySubjectMode; - } - - public void setDeepCopySubjectMode(boolean deepCopySubjectMode) { - this.deepCopySubjectMode = deepCopySubjectMode; - } - - public String getCallbackHandlerClassName() { - return callbackHandlerClassName; - } - - public void setCallbackHandlerClassName(String callbackHandlerClassName) { - this.callbackHandlerClassName = callbackHandlerClassName; - } - - public String getAuthorizationManagerClassName() { - return authorizationManagerClassName; - } - - public void setAuthorizationManagerClassName(String authorizationManagerClassName) { - this.authorizationManagerClassName = authorizationManagerClassName; - } - - public String getAuditManagerClassName() { - return auditManagerClassName; - } - - public void setAuditManagerClassName(String auditManagerClassName) { - this.auditManagerClassName = auditManagerClassName; - } - - public String getIdentityTrustManagerClassName() { - return identityTrustManagerClassName; - } - - public void setIdentityTrustManagerClassName(String identityTrustManagerClassName) { - this.identityTrustManagerClassName = identityTrustManagerClassName; - } - - public String getMappingManagerClassName() { - return mappingManagerClassName; - } - - public void setMappingManagerClassName(String mappingManagerClassName) { - this.mappingManagerClassName = mappingManagerClassName; - } - - /** - * Removes one security domain from the maps - * - * @param securityDomain name of the security domain - */ - public void removeSecurityDomain(String securityDomain) { - securityMgrMap.remove(securityDomain); - auditMgrMap.remove(securityDomain); - authMgrMap.remove(securityDomain); - authzMgrMap.remove(securityDomain); - idmMgrMap.remove(securityDomain); - mappingMgrMap.remove(securityDomain); - jsseMap.remove(securityDomain); - } - - /** - * Lookup a context in JNDI - * - * @param contextName the context - * @return the Object found at the context or null if there is nothing bound - */ - private Object lookUpJNDI(String contextName) { - Object result = null; - try { - Context ctx = new InitialContext(); - if (contextName.startsWith(SecurityConstants.JAAS_CONTEXT_ROOT)) - result = ctx.lookup(contextName); - else - result = ctx.lookup(SecurityConstants.JAAS_CONTEXT_ROOT + contextName); - } catch (Exception e) { - SecurityLogger.ROOT_LOGGER.tracef("Look up of JNDI for %s failed with %s", contextName, e.getLocalizedMessage()); - return null; - } - return result; - } - - /** - * Creates a {@code SecurityDomainContext} - * - * @param securityDomain name of the security domain - * @param cacheFactory creates a cache implementation - * @return an instance of {@code SecurityDomainContext} - * @throws Exception if an error occurs during creation - */ - public SecurityDomainContext createSecurityDomainContext(String securityDomain, AuthenticationCacheFactory cacheFactory) throws Exception { - return createSecurityDomainContext(securityDomain, cacheFactory, null); - } - - /** - * Creates a {@code SecurityDomainContext} optionally including a {@link JSSESecurityDomain} - * - * @param securityDomain name of the security domain. Cannot be {@code null} - * @param cacheFactory creates a cache implementation. Cannot be {@code null} - * @param jsseSecurityDomain a JSSE security domain. May be {@code null} - * @return an instance of {@code SecurityDomainContext} - * @throws Exception if an error occurs during creation - */ - public SecurityDomainContext createSecurityDomainContext(String securityDomain, - AuthenticationCacheFactory cacheFactory, - JSSESecurityDomain jsseSecurityDomain) throws Exception { - SecurityLogger.ROOT_LOGGER.debugf("Creating SDC for domain = %s", securityDomain); - AuthenticationManager am = createAuthenticationManager(securityDomain); - if (cacheFactory != null && am instanceof CacheableManager) { - // create authentication cache - final Map cache = cacheFactory.getCache(); - if (cache != null) { - @SuppressWarnings({ "unchecked", "rawtypes" }) - CacheableManager cm = (CacheableManager) am; - cm.setCache(cache); - } - } - - // set DeepCopySubject option if supported - if (deepCopySubjectMode) { - setDeepCopySubjectMode(am); - } - - return new SecurityDomainContext(am, - createAuthorizationManager(securityDomain), - createAuditManager(securityDomain), - createIdentityTrustManager(securityDomain), createMappingManager(securityDomain), - jsseSecurityDomain); - } - - /** - * Creates an {@code AuthenticationManager} - * - * @param securityDomain name of the security domain - * @return an instance of {@code AuthenticationManager} - * @throws Exception if creation fails - */ - private AuthenticationManager createAuthenticationManager(String securityDomain) throws Exception { - int i = callbackHandlerClassName.lastIndexOf(":"); - if (i == -1) - throw SecurityLogger.ROOT_LOGGER.missingModuleName("default-callback-handler-class-name attribute"); - String moduleSpec = callbackHandlerClassName.substring(0, i); - String className = callbackHandlerClassName.substring(i + 1); - Class callbackHandlerClazz = SecurityActions.getModuleClassLoader(loader, moduleSpec).loadClass(className); - CallbackHandler ch = (CallbackHandler) callbackHandlerClazz.newInstance(); - - i = authenticationManagerClassName.lastIndexOf(":"); - if (i == -1) - throw SecurityLogger.ROOT_LOGGER.missingModuleName("authentication-manager-class-name attribute"); - moduleSpec = authenticationManagerClassName.substring(0, i); - className = authenticationManagerClassName.substring(i + 1); - Class clazz = SecurityActions.getModuleClassLoader(loader, moduleSpec).loadClass(className); - Constructor ctr = clazz.getConstructor(new Class[] { String.class, CallbackHandler.class }); - return (AuthenticationManager) ctr.newInstance(new Object[] { securityDomain, ch }); - } - - /** - * Creates an {@code AuthorizationManager} - * - * @param securityDomain name of the security domain - * @return an instance of {@code AuthorizationManager} - * @throws Exception if creation fails - */ - private AuthorizationManager createAuthorizationManager(String securityDomain) throws Exception { - int i = authorizationManagerClassName.lastIndexOf(":"); - if (i == -1) - throw SecurityLogger.ROOT_LOGGER.missingModuleName("authorization manager class"); - String moduleSpec = authorizationManagerClassName.substring(0, i); - String className = authorizationManagerClassName.substring(i + 1); - Class clazz = SecurityActions.getModuleClassLoader(loader, moduleSpec).loadClass(className); - Constructor ctr = clazz.getConstructor(new Class[] { String.class }); - return (AuthorizationManager) ctr.newInstance(new Object[] { securityDomain }); - } - - /** - * Creates an {@code AuditManager} - * - * @param securityDomain name of the security domain - * @return an instance of {@code AuditManager} - * @throws Exception if creation fails - */ - private AuditManager createAuditManager(String securityDomain) throws Exception { - int i = auditManagerClassName.lastIndexOf(":"); - if (i == -1) - throw SecurityLogger.ROOT_LOGGER.missingModuleName("audit manager class"); - String moduleSpec = auditManagerClassName.substring(0, i); - String className = auditManagerClassName.substring(i + 1); - Class clazz = SecurityActions.getModuleClassLoader(loader, moduleSpec).loadClass(className); - Constructor ctr = clazz.getConstructor(new Class[] { String.class }); - return (AuditManager) ctr.newInstance(new Object[] { securityDomain }); - } - - /** - * Creates an {@code IdentityTrustManager} - * - * @param securityDomain name of the security domain - * @return an instance of {@code IdentityTrustManager} - * @throws Exception if creation fails - */ - private IdentityTrustManager createIdentityTrustManager(String securityDomain) throws Exception { - int i = identityTrustManagerClassName.lastIndexOf(":"); - if (i == -1) - throw SecurityLogger.ROOT_LOGGER.missingModuleName("identity trust manager class"); - String moduleSpec = identityTrustManagerClassName.substring(0, i); - String className = identityTrustManagerClassName.substring(i + 1); - Class clazz = SecurityActions.getModuleClassLoader(loader, moduleSpec).loadClass(className); - Constructor ctr = clazz.getConstructor(new Class[] { String.class }); - return (IdentityTrustManager) ctr.newInstance(new Object[] { securityDomain }); - } - - /** - * Creates an {@code MappingManager} - * - * @param securityDomain name of the security domain - * @return an instance of {@code MappingManager} - * @throws Exception if creation fails - */ - private MappingManager createMappingManager(String securityDomain) throws Exception { - int i = mappingManagerClassName.lastIndexOf(":"); - if (i == -1) - throw SecurityLogger.ROOT_LOGGER.missingModuleName("mapping manager class"); - String moduleSpec = mappingManagerClassName.substring(0, i); - String className = mappingManagerClassName.substring(i + 1); - Class clazz = SecurityActions.getModuleClassLoader(loader, moduleSpec).loadClass(className); - Constructor ctr = clazz.getConstructor(new Class[] { String.class }); - return (MappingManager) ctr.newInstance(new Object[] { securityDomain }); - } - - /** - * Use reflection to attempt to set the deep copy subject mode on the {@code AuthenticationManager} - * - * @param authenticationManager the {@code AuthenticationManager} - */ - private static void setDeepCopySubjectMode(AuthenticationManager authenticationManager) { - try { - Class[] argsType = { Boolean.class }; - Method m = authenticationManager.getClass().getMethod("setDeepCopySubjectOption", argsType); - Object[] deepCopyArgs = { Boolean.TRUE }; - m.invoke(authenticationManager, deepCopyArgs); - } catch (Exception e) { - SecurityLogger.ROOT_LOGGER.tracef("Optional setDeepCopySubjectMode failed: %s", e.getLocalizedMessage()); - } - } - -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/plugins/ModuleClassLoaderLocator.java b/security/plugins/src/main/java/org/jboss/as/security/plugins/ModuleClassLoaderLocator.java deleted file mode 100644 index 0aabaf6b38ac..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/plugins/ModuleClassLoaderLocator.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2011, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.as.security.plugins; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.security.SecureClassLoader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.jboss.as.security._private.SecurityLogger; -import org.jboss.modules.ModuleLoadException; -import org.jboss.modules.ModuleLoader; -import org.jboss.security.plugins.ClassLoaderLocator; -import org.wildfly.security.manager.WildFlySecurityManager; - -/** - * An implementation of {@code ClassLoaderLocator} that is based on JBoss Modules. - * - * @author anil saldhana - * @author Stefan Guilhen - */ -public class ModuleClassLoaderLocator implements ClassLoaderLocator { - private final ModuleLoader moduleLoader; - - private final Map, ClassLoader>> combinedClassLoaders; - public ModuleClassLoaderLocator(ModuleLoader loader) { - this.moduleLoader = loader; - this.combinedClassLoaders = new ConcurrentHashMap<>(); - } - - @Override - public ClassLoader get(String key) { - return this.get(Collections.singletonList(key)); - } - - @Override - public ClassLoader get(List modules) { - // TCCL is usually a deployment ModuleClassLoader - final ClassLoader TCCL = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); - return combinedClassLoaders.computeIfAbsent(TCCL, cl -> new ConcurrentHashMap<>()).computeIfAbsent(modules, ms -> { - List classLoaders = new ArrayList<>(); - try { - for (String module : modules) { - if (module != null && !module.isEmpty()) { - classLoaders.add(SecurityActions.getModuleClassLoader(moduleLoader, module)); - } - } - classLoaders.add(TCCL); - /** - * A Login Module can be in a custom user module. - * The local resources (such as users.properties) can be present in a web deployment, - * whose CL is available on the TCCL. - */ - } catch (ModuleLoadException e) { - throw SecurityLogger.ROOT_LOGGER.runtimeException(e); - } - return SecurityActions.createCombinedClassLoader(classLoaders); - }); - } - - public void clearCache() { - combinedClassLoaders.clear(); - } - - /** A Classloader that takes a list of Classloaders to delegate to */ - public static class CombinedClassLoader extends SecureClassLoader{ - private List classLoaders; - - public CombinedClassLoader(List classLoaders){ - this.classLoaders = classLoaders; - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - for (ClassLoader loader : classLoaders) { - try { - return loader.loadClass(name); - } catch(ClassNotFoundException ce){ - // do nothing, see if another loader can do this. - } - } - throw new ClassNotFoundException(name); - } - - @Override - public URL getResource(String name) { - URL resource = null; - for (ClassLoader loader : classLoaders) { - resource = loader.getResource(name); - if(resource != null){ - break; - } - } - return resource; - } - - @Override - public InputStream getResourceAsStream(String name) { - InputStream is = null; - for (ClassLoader loader : classLoaders) { - is = loader.getResourceAsStream(name); - if (is != null) { - break; - } - } - return is; - } - - @Override - public Enumeration getResources(String name) throws IOException { - List combinedList = new ArrayList<>(); - for (ClassLoader loader : classLoaders) { - combinedList.addAll(Collections.list(loader.getResources(name))); - } - return Collections.enumeration(combinedList); - } - } -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/plugins/SecurityActions.java b/security/plugins/src/main/java/org/jboss/as/security/plugins/SecurityActions.java deleted file mode 100644 index 1ea70f81aca9..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/plugins/SecurityActions.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2010, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.security.plugins; - -import static java.security.AccessController.doPrivileged; - -import java.security.Principal; -import java.security.PrivilegedAction; -import java.util.List; - -import org.jboss.as.security.plugins.ModuleClassLoaderLocator.CombinedClassLoader; -import org.jboss.modules.Module; -import org.jboss.modules.ModuleClassLoader; -import org.jboss.modules.ModuleIdentifier; -import org.jboss.modules.ModuleLoadException; -import org.jboss.modules.ModuleLoader; -import org.jboss.security.SecurityContext; -import org.jboss.security.SecurityContextAssociation; -import org.wildfly.security.manager.WildFlySecurityManager; -import org.wildfly.security.manager.action.GetModuleClassLoaderAction; - -/** - * Privileged blocks for this package - * - * @author Marcus Moyses - */ -class SecurityActions { - - static ModuleClassLoader getModuleClassLoader(final ModuleLoader loader, final String moduleSpec) throws ModuleLoadException { - final Module module = loader.loadModule(ModuleIdentifier.fromString(moduleSpec)); - return WildFlySecurityManager.isChecking() ? doPrivileged(new GetModuleClassLoaderAction(module)) : module.getClassLoader(); - } - - static SecurityContext getSecurityContext() { - if (WildFlySecurityManager.isChecking()) { - return doPrivileged(new PrivilegedAction() { - public SecurityContext run() { - return SecurityContextAssociation.getSecurityContext(); - } - }); - } else { - return SecurityContextAssociation.getSecurityContext(); - } - } - - static Principal getPrincipal() { - if (WildFlySecurityManager.isChecking()) { - return doPrivileged(new PrivilegedAction() { - public Principal run() { - Principal principal = null; - SecurityContext sc = getSecurityContext(); - if (sc != null) { - principal = sc.getUtil().getUserPrincipal(); - } - return principal; - } - }); - } else { - Principal principal = null; - SecurityContext sc = getSecurityContext(); - if (sc != null) { - principal = sc.getUtil().getUserPrincipal(); - } - return principal; - } - } - - static Object getCredential() { - if (WildFlySecurityManager.isChecking()) { - return doPrivileged(new PrivilegedAction() { - public Object run() { - Object credential = null; - SecurityContext sc = getSecurityContext(); - if (sc != null) { - credential = sc.getUtil().getCredential(); - } - return credential; - } - }); - } else { - Object credential = null; - SecurityContext sc = getSecurityContext(); - if (sc != null) { - credential = sc.getUtil().getCredential(); - } - return credential; - } - } - - /** - * Returns the ModuleClassLoaderLocator.CombinedClassLoader instance with consideration of security manager enabled - * - * @param classLoaders the delegated ClassLoaders - * @return the ModuleClassLoaderLocator.CombinedClassLoader instance - */ - static ModuleClassLoaderLocator.CombinedClassLoader createCombinedClassLoader(final List classLoaders) { - if (WildFlySecurityManager.isChecking()) { - return doPrivileged(new PrivilegedAction() { - @Override - public CombinedClassLoader run() { - return new ModuleClassLoaderLocator.CombinedClassLoader(classLoaders); - } - }); - } else { - return new ModuleClassLoaderLocator.CombinedClassLoader(classLoaders); - } - } - -} \ No newline at end of file diff --git a/security/plugins/src/main/java/org/jboss/as/security/plugins/SecurityDomainContext.java b/security/plugins/src/main/java/org/jboss/as/security/plugins/SecurityDomainContext.java deleted file mode 100644 index b9ebfe5dfaf1..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/plugins/SecurityDomainContext.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2010, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.security.plugins; - -import javax.security.auth.Subject; -import javax.security.jacc.PolicyContext; -import javax.security.jacc.PolicyContextException; - -import org.jboss.security.AuthenticationManager; -import org.jboss.security.AuthorizationManager; -import org.jboss.security.JSSESecurityDomain; -import org.jboss.security.audit.AuditManager; -import org.jboss.security.identitytrust.IdentityTrustManager; -import org.jboss.security.mapping.MappingManager; - -/** - * An encapsulation of the JNDI security context information - * - * @author Scott.Stark@jboss.org - * @author Anil.Saldhana@jboss.org - * @author Marcus Moyses - */ -public final class SecurityDomainContext { - - private final AuthenticationManager authenticationMgr; - private final AuthorizationManager authorizationMgr; - private final AuditManager auditMgr; - private final MappingManager mappingMgr; - private final IdentityTrustManager identityTrustMgr; - private final JSSESecurityDomain jsseSecurityDomain; - - private static final String SUBJECT_CONTEXT_KEY = "javax.security.auth.Subject.container"; - - public SecurityDomainContext(AuthenticationManager authenticationMgr, - AuthorizationManager authorizationMgr, - AuditManager auditMgr, - IdentityTrustManager identityTrustMgr, MappingManager mappingMgr, - JSSESecurityDomain jsseSecurityDomain) { - this.authenticationMgr = authenticationMgr; - this.authorizationMgr = authorizationMgr; - this.auditMgr = auditMgr; - this.mappingMgr = mappingMgr; - this.identityTrustMgr = identityTrustMgr; - this.jsseSecurityDomain = jsseSecurityDomain; - } - - public Subject getSubject() { - Subject subject = null; - try { - subject = (Subject) PolicyContext.getContext(SUBJECT_CONTEXT_KEY); - } catch (PolicyContextException pce) { - } - return subject; - } - - public AuthenticationManager getAuthenticationManager() { - return authenticationMgr; - } - - public AuthorizationManager getAuthorizationManager() { - return authorizationMgr; - } - - public AuditManager getAuditManager() { - return auditMgr; - } - - public MappingManager getMappingManager() { - return mappingMgr; - } - - public IdentityTrustManager getIdentityTrustManager() { - return identityTrustMgr; - } - - public JSSESecurityDomain getJSSE() { - return jsseSecurityDomain; - } -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemoteConnection.java b/security/plugins/src/main/java/org/jboss/as/security/remoting/RemoteConnection.java deleted file mode 100644 index 58c5fe651f9b..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemoteConnection.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2017, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 2110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.security.remoting; - -import javax.net.ssl.SSLSession; - -import org.wildfly.security.auth.server.SecurityIdentity; - -/** - * Represents a remote connection to the application server, either via remoting or via Jakarta Enterprise Beans over HTTP - * - * @author Stuart Douglas - */ -public interface RemoteConnection { - - - SSLSession getSslSession(); - - SecurityIdentity getSecurityIdentity(); -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingConnectionCredential.java b/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingConnectionCredential.java deleted file mode 100644 index 25a753910823..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingConnectionCredential.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * - * * JBoss, Home of Professional Open Source. - * * Copyright 2013, Red Hat, Inc., and individual contributors - * * as indicated by the @author tags. See the copyright.txt file in the - * * distribution for a full listing of individual contributors. - * * - * * This is free software; you can redistribute it and/or modify it - * * under the terms of the GNU Lesser General Public License as - * * published by the Free Software Foundation; either version 2.1 of - * * the License, or (at your option) any later version. - * * - * * This software is distributed in the hope that it will be useful, - * * but WITHOUT ANY WARRANTY; without even the implied warranty of - * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * * Lesser General Public License for more details. - * * - * * You should have received a copy of the GNU Lesser General Public - * * License along with this software; if not, write to the Free - * * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - * - */ - -package org.jboss.as.security.remoting; - -import java.security.Principal; -import java.util.Set; - -import javax.net.ssl.SSLSession; -import javax.security.auth.Subject; - -import org.jboss.as.core.security.RealmGroup; -import org.jboss.as.core.security.RealmRole; -import org.jboss.as.core.security.RealmUser; -import org.wildfly.common.Assert; -import org.wildfly.security.auth.server.SecurityIdentity; - -/** - * A Credential wrapping a remote connection. - * - * @author Darran Lofthouse - */ -public final class RemotingConnectionCredential { - - private final RemoteConnection connection; - private final SecurityIdentity securityIdentity; - private final Subject subject; - - public RemotingConnectionCredential(final RemoteConnection connection, final SecurityIdentity securityIdentity) { - Assert.checkNotNullParam("connection", connection); - Assert.checkNotNullParam("securityIdentity", securityIdentity); - this.connection = connection; - this.securityIdentity = securityIdentity; - Subject subject = new Subject(); - Set principals = subject.getPrincipals(); - principals.add(new RealmUser(securityIdentity.getPrincipal().getName())); - for (String role : securityIdentity.getRoles()) { - principals.add(new RealmGroup(role)); - principals.add(new RealmRole(role)); - } - this.subject = subject; - } - - SSLSession getSSLSession() { - return connection.getSslSession(); - } - - SecurityIdentity getSecurityIdentity() { - return securityIdentity; - } - - public Subject getSubject() { - return subject; - } - - @Override - public int hashCode() { - return connection.hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof RemotingConnectionCredential && equals((RemotingConnectionCredential) obj); - } - - public boolean equals(RemotingConnectionCredential obj) { - return connection.equals(obj.connection) && securityIdentity.equals(obj.securityIdentity); - } -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingContext.java b/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingContext.java deleted file mode 100644 index 5f000f2eb2c6..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingContext.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2011, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.security.remoting; - -import java.security.Permission; - -import javax.net.ssl.SSLSession; - -import org.jboss.remoting3.Connection; -import org.wildfly.security.auth.server.SecurityIdentity; - -/** - * A simple context to associate the Remoting Connection with the current thread. - * - * This association is used to make use of the user identity already authenticated on the connection. - * - * @author Darran Lofthouse - */ -public class RemotingContext { - - /** - * A {@link org.jboss.as.security.remoting.RemotingPermission} needed to clear a {@link org.jboss.as.security.remoting.RemotingContext}'s {@link org.jboss.remoting3.Connection}. The name of the permission is "{@code clearConnection}." - */ - private static final RemotingPermission CLEAR_CONNECTION = new RemotingPermission("clearConnection"); - /** - * A {@link org.jboss.as.security.remoting.RemotingPermission} needed to retrieve a {@link org.jboss.as.security.remoting.RemotingContext}'s {@link org.jboss.remoting3.Connection}. The name of the permission is "{@code getConnection}." - */ - private static final RemotingPermission GET_CONNECTION = new RemotingPermission("getConnection"); - /** - * A {@link org.jboss.as.security.remoting.RemotingPermission} needed to check if a {@link org.jboss.as.security.remoting.RemotingContext}'s {@link org.jboss.remoting3.Connection} is set. The name of the permission is "{@code isConnectionSet}." - */ - private static final RemotingPermission IS_CONNECTION_SET = new RemotingPermission("isConnectionSet"); - /** - * A {@link org.jboss.as.security.remoting.RemotingPermission} needed to set a {@link org.jboss.as.security.remoting.RemotingContext}'s {@link org.jboss.remoting3.Connection}. The name of the permission is "{@code setConnection}." - */ - private static final RemotingPermission SET_CONNECTION = new RemotingPermission("setConnection"); - - private static ThreadLocal connection = new ThreadLocal(); - - public static void setConnection(final Connection connection) { - checkPermission(SET_CONNECTION); - RemotingContext.connection.set(new RemotingRemoteConnection(connection)); - } - - public static void setConnection(final RemoteConnection connection) { - checkPermission(SET_CONNECTION); - RemotingContext.connection.set(connection); - } - public static void clear() { - checkPermission(CLEAR_CONNECTION); - - connection.set(null); - } - - public static Connection getConnection() { - checkPermission(GET_CONNECTION); - - RemoteConnection remoteConnection = connection.get(); - if(remoteConnection instanceof RemotingRemoteConnection) { - return ((RemotingRemoteConnection) remoteConnection).connection; - } - return null; - } - - public static RemoteConnection getRemoteConnection() { - checkPermission(GET_CONNECTION); - return connection.get(); - } - - public static boolean isSet() { - checkPermission(IS_CONNECTION_SET); - - return connection.get() != null; - } - - private static void checkPermission(final Permission permission) { - SecurityManager securityManager = System.getSecurityManager(); - if (securityManager != null) { - securityManager.checkPermission(permission); - } - } - - private static final class RemotingRemoteConnection implements RemoteConnection { - - final Connection connection; - - private RemotingRemoteConnection(Connection connection) { - this.connection = connection; - } - - @Override - public SSLSession getSslSession() { - return connection.getSslSession(); - } - - @Override - public SecurityIdentity getSecurityIdentity() { - return connection.getLocalIdentity(); - } - } - -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingLoginModule.java b/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingLoginModule.java deleted file mode 100644 index 4c392c39f1af..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingLoginModule.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2011, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.jboss.as.security.remoting; - -import java.io.IOException; -import java.security.Principal; -import java.security.acl.Group; -import java.util.Map; - -import javax.net.ssl.SSLPeerUnverifiedException; -import javax.net.ssl.SSLSession; -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.LoginException; - -import org.jboss.as.core.security.RealmUser; -import org.jboss.security.SimpleGroup; -import org.jboss.security.auth.callback.ObjectCallback; -import org.jboss.security.auth.spi.AbstractServerLoginModule; -import org.wildfly.security.auth.server.SecurityIdentity; - -/** - * A simple LoginModule to take the UserPrincipal from the inbound Remoting connection and to use it as an already authenticated - * user. - * - * Subsequent login modules can be chained after this module to load role information. - * - * @author Darran Lofthouse - */ -public class RemotingLoginModule extends AbstractServerLoginModule { - - /** - * If a {@link javax.security.cert.X509Certificate} is available from the client as a result of a {@link SSLSession} being established should - * this be used for the credential. - * - * Default = false. - */ - private static final String USE_CLIENT_CERT_OPTION = "useClientCert"; - - /** - * If a {@link java.security.cert.X509Certificate} is available from the client as a result of a {@link SSLSession} being established should - * this be used for the credential. - * - * Default = false. - */ - private static final String USE_NEW_CLIENT_CERT_OPTION = "useNewClientCert"; - - private static final String[] ALL_OPTIONS = new String[] { USE_CLIENT_CERT_OPTION, USE_NEW_CLIENT_CERT_OPTION }; - - private boolean useClientCert = false; - private boolean useNewClientCert = false; - private Principal identity; - - @Override - public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { - addValidOptions(ALL_OPTIONS); - super.initialize(subject, callbackHandler, sharedState, options); - - if (options.containsKey(USE_CLIENT_CERT_OPTION)) { - useClientCert = Boolean.parseBoolean(options.get(USE_CLIENT_CERT_OPTION).toString()); - } - if (options.containsKey(USE_NEW_CLIENT_CERT_OPTION)) { - useNewClientCert = Boolean.parseBoolean(options.get(USE_NEW_CLIENT_CERT_OPTION).toString()); - } - } - - @SuppressWarnings("unchecked") - @Override - public boolean login() throws LoginException { - if (super.login() == true) { - log.debug("super.login()==true"); - return true; - } - - Object credential = getCredential(); - if (credential instanceof RemotingConnectionCredential) { - final RemotingConnectionCredential remotingConnectionCredential = (RemotingConnectionCredential) credential; - SecurityIdentity localIdentity = remotingConnectionCredential.getSecurityIdentity(); - identity = new RealmUser(localIdentity.getPrincipal().getName()); - if (getUseFirstPass()) { - String userName = identity.getName(); - log.debugf("Storing username '%s'", userName); - // Add the username to the shared state map - sharedState.put("javax.security.auth.login.name", identity); - - if (useNewClientCert) { - SSLSession session = remotingConnectionCredential.getSSLSession(); - if (session != null) { - try { - credential = session.getPeerCertificates()[0]; - log.debug("Using new certificate as credential."); - } catch (SSLPeerUnverifiedException e) { - log.debugf("No peer certificate available for '%s'", userName); - } - } - } else if (useClientCert) { - SSLSession session = remotingConnectionCredential.getSSLSession(); - if (session != null) { - try { - credential = session.getPeerCertificateChain()[0]; - log.debug("Using certificate as credential."); - } catch (SSLPeerUnverifiedException e) { - log.debugf("No peer certificate available for '%s'", userName); - } - } - } - sharedState.put("javax.security.auth.login.password", credential); - } - loginOk = true; - return true; - } - - // We return false to allow the next module to attempt authentication, maybe a - // username and password has been supplied to a web auth. - return false; - } - - protected Object getCredential() throws LoginException { - NameCallback nc = new NameCallback("Alias: "); - ObjectCallback oc = new ObjectCallback("Credential: "); - Callback[] callbacks = { nc, oc }; - - try { - callbackHandler.handle(callbacks); - - return oc.getCredential(); - } catch (IOException ioe) { - LoginException le = new LoginException(); - le.initCause(ioe); - throw le; - } catch (UnsupportedCallbackException uce) { - LoginException le = new LoginException(); - le.initCause(uce); - throw le; - } - } - - @Override - protected Principal getIdentity() { - return identity; - } - - @Override - protected Group[] getRoleSets() throws LoginException { - Group roles = new SimpleGroup("Roles"); - Group callerPrincipal = new SimpleGroup("CallerPrincipal"); - Group[] groups = { roles, callerPrincipal }; - callerPrincipal.addMember(getIdentity()); - return groups; - } - -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingPermission.java b/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingPermission.java deleted file mode 100644 index 88906f53eff8..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/remoting/RemotingPermission.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2014, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.as.security.remoting; - -import java.security.BasicPermission; - - -/** - *

- * This class is for WildFly Security Remoting's permissions. A permission - * contains a name (also referred to as a "target name") but - * no actions list; you either have the named permission - * or you don't. - *

- * - *

- * The naming convention follows the hierarchical property naming convention. - * An asterisk may appear by itself, or if immediately preceded by a "." - * may appear at the end of the name, to signify a wildcard match. - *

- * - *

- * The target name is the name of the permission. The following table lists all the possible permission target names, - * and for each provides a description of what the permission allows. - *

- * - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Permission Target NameWhat the Permission Allows
clearConnectionClear a {@link org.jboss.as.security.remoting.RemotingContext}'s {@link org.jboss.remoting3.Connection}
getConnectionRetrieve a {@link org.jboss.as.security.remoting.RemotingContext}'s {@link org.jboss.remoting3.Connection}
isConnectionSetCheck if a {@link org.jboss.as.security.remoting.RemotingContext}'s {@link org.jboss.remoting3.Connection} is set
setConnectionSet a {@link org.jboss.as.security.remoting.RemotingContext}'s {@link org.jboss.remoting3.Connection}
- *

- * @author Eduardo Martins - */ -public class RemotingPermission extends BasicPermission { - /** - * Creates a new permission with the specified name. - * The name is the symbolic name of the permission, such as - * "getConnection". - * - * @param name the name of the permission. - * - * @throws NullPointerException if name is null. - * @throws IllegalArgumentException if name is empty. - */ - public RemotingPermission(String name) { - super(name); - } - - /** - * Creates a new permission object with the specified name. - * The name is the symbolic name of the permission, and the - * actions String is currently unused and should be null. - * - * @param name the name of the permission. - * @param actions should be null. - * - * @throws NullPointerException if name is null. - * @throws IllegalArgumentException if name is empty. - */ - public RemotingPermission(String name, String actions) { - super(name, actions); - } -} diff --git a/security/plugins/src/main/java/org/jboss/as/security/remoting/SecurityActions.java b/security/plugins/src/main/java/org/jboss/as/security/remoting/SecurityActions.java deleted file mode 100644 index 3c5bb0cea524..000000000000 --- a/security/plugins/src/main/java/org/jboss/as/security/remoting/SecurityActions.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2013, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.as.security.remoting; - -import java.security.AccessController; -import java.security.PrivilegedAction; - -import org.jboss.remoting3.Connection; -import org.wildfly.security.manager.WildFlySecurityManager; - -/** - * SecurityActions to manipulate the RemotingContext. - * - * @author Darran Lofthouse - */ -final class SecurityActions { - - private SecurityActions() { - } - - static Connection remotingContextGetConnection() { - return remotingContextAssociationActions().getConnection(); - } - - private static RemotingContextAssociationActions remotingContextAssociationActions() { - return ! WildFlySecurityManager.isChecking() ? RemotingContextAssociationActions.NON_PRIVILEGED - : RemotingContextAssociationActions.PRIVILEGED; - } - - private interface RemotingContextAssociationActions { - - Connection getConnection(); - - RemotingContextAssociationActions NON_PRIVILEGED = new RemotingContextAssociationActions() { - - public Connection getConnection() { - return RemotingContext.getConnection(); - } - }; - - RemotingContextAssociationActions PRIVILEGED = new RemotingContextAssociationActions() { - - private final PrivilegedAction GET_CONNECTION_ACTION = new PrivilegedAction() { - - public Connection run() { - return NON_PRIVILEGED.getConnection(); - } - - }; - - public Connection getConnection() { - return AccessController.doPrivileged(GET_CONNECTION_ACTION); - } - }; - - } - -} diff --git a/security/pom.xml b/security/pom.xml index a8198b95c589..ebfeb2cc8072 100644 --- a/security/pom.xml +++ b/security/pom.xml @@ -42,7 +42,6 @@ WildFly: Security Subsystem parent - plugins subsystem diff --git a/servlet-feature-pack/common/pom.xml b/servlet-feature-pack/common/pom.xml index 886330f194bf..854251d98b2d 100644 --- a/servlet-feature-pack/common/pom.xml +++ b/servlet-feature-pack/common/pom.xml @@ -322,17 +322,6 @@ - - ${project.groupId} - wildfly-security-plugins - - - * - * - - - - ${project.groupId} wildfly-undertow diff --git a/servlet-feature-pack/common/src/main/resources/license/servlet-feature-pack-common-licenses.xml b/servlet-feature-pack/common/src/main/resources/license/servlet-feature-pack-common-licenses.xml index 810c894deea9..5626ba65a4fd 100644 --- a/servlet-feature-pack/common/src/main/resources/license/servlet-feature-pack-common-licenses.xml +++ b/servlet-feature-pack/common/src/main/resources/license/servlet-feature-pack-common-licenses.xml @@ -203,17 +203,6 @@ - - ${project.groupId} - wildfly-security-plugins - - - GNU Lesser General Public License v2.1 or later - http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html - repo - - - ${project.groupId} wildfly-undertow diff --git a/servlet-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/security-plugins/main/module.xml b/servlet-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/security-plugins/main/module.xml deleted file mode 100644 index 0ac230388120..000000000000 --- a/servlet-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/security-plugins/main/module.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/testsuite/integration/basic/pom.xml b/testsuite/integration/basic/pom.xml index 99ab68d33b06..23bc0be21bfe 100644 --- a/testsuite/integration/basic/pom.xml +++ b/testsuite/integration/basic/pom.xml @@ -464,11 +464,6 @@ test - - ${project.groupId} - wildfly-security-plugins - test - io.opentelemetry opentelemetry-api From 0926141e8a969c86062b6b0f5c25e850f7303b54 Mon Sep 17 00:00:00 2001 From: Darran Lofthouse Date: Thu, 25 Nov 2021 20:52:58 +0000 Subject: [PATCH 11/11] [WFLY-15760] / [WFLY-13889] Remove the dependency on PicketBox from EJB3. --- .../modules/system/layers/base/org/jboss/as/ejb3/main/module.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/ejb3/main/module.xml b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/ejb3/main/module.xml index 87e95bc6160d..bd4e88e14ba8 100644 --- a/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/ejb3/main/module.xml +++ b/ee-feature-pack/common/src/main/resources/modules/system/layers/base/org/jboss/as/ejb3/main/module.xml @@ -103,7 +103,6 @@ -