[java-plugin-shibd] branch main updated: Address validation action and unit test.

Scott Cantor cantor.2 at osu.edu
Tue May 21 20:04:02 UTC 2024


This is an automated email from the git hooks/post-receive script.

scantor pushed a commit to branch main
in repository java-plugin-shibd.

View the commit online:
http://git.shibboleth.net/view/?p=java-plugin-shibd.git;a=commit;h=0919a6a624f54f09add1a3c712f86b7e856c1b2f

The following commit(s) were added to refs/heads/main by this push:
     new 0919a6a  Address validation action and unit test.
0919a6a is described below

commit 0919a6a624f54f09add1a3c712f86b7e856c1b2f
Author: Scott Cantor <cantor.2 at osu.edu>
AuthorDate: Tue May 21 16:03:59 2024 -0400

    Address validation action and unit test.
---
 .../idp/flows/sp/abstract/sp-abstract-beans.xml    |   8 ++
 .../src/main/java/net/shibboleth/sp/Agent.java     |  10 ++
 .../sp/authn/impl/ValidateAgentAddress.java        | 125 +++++++++++++++++++++
 .../java/net/shibboleth/sp/impl/BasicAgent.java    |  10 +-
 .../sp/authn/impl/ValidateAgentAddressTest.java    | 109 ++++++++++++++++++
 5 files changed, 254 insertions(+), 8 deletions(-)

diff --git a/sp-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/abstract/sp-abstract-beans.xml b/sp-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/abstract/sp-abstract-beans.xml
index 49ad8f5..f548136 100644
--- a/sp-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/abstract/sp-abstract-beans.xml
+++ b/sp-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/abstract/sp-abstract-beans.xml
@@ -30,5 +30,13 @@
     <bean id="ExtractUsernamePasswordFromBasicAuth"
         class="net.shibboleth.idp.authn.impl.ExtractUsernamePasswordFromBasicAuth" scope="prototype"
         p:httpServletRequestSupplier-ref="shibboleth.HttpServletRequestSupplier" />
+        
+    <bean id="InitializeAgentRequestContext"
+        class="net.shibboleth.sp.authn.impl.InitializeAgentRequestContext" scope="prototype"
+        p:agentResolver-ref="shibboleth.AgentResolver" />
+        
+    <bean id="ValidateAgentAddress"
+        class="net.shibboleth.sp.authn.impl.ValidateAgentAddress" scope="prototype"
+        p:httpServletRequestSupplier-ref="shibboleth.HttpServletRequestSupplier" />
 
 </beans>
diff --git a/sp-server-api/src/main/java/net/shibboleth/sp/Agent.java b/sp-server-api/src/main/java/net/shibboleth/sp/Agent.java
index d7680f4..04e4a3d 100644
--- a/sp-server-api/src/main/java/net/shibboleth/sp/Agent.java
+++ b/sp-server-api/src/main/java/net/shibboleth/sp/Agent.java
@@ -15,6 +15,7 @@
 
 package net.shibboleth.sp;
 
+import java.net.InetAddress;
 import java.util.Collection;
 import java.util.Set;
 
@@ -45,6 +46,15 @@ public interface Agent extends IdentifiedComponent {
      * @return set of address ranges
      */
     @Nonnull Set<IPRange> getAllowedAddressRanges();
+    
+    /**
+     * Returns true iff the supplied address matches one of the allowed ranges.
+     * 
+     * @param address address to test
+     * 
+     * @return true iff the supplied address matches one of the allowed ranges
+     */
+    boolean isAllowed(@Nonnull final InetAddress address);
 
     /**
      * Get the issuer value to use in various identity protocols when identifying this agent.
diff --git a/sp-server-impl/src/main/java/net/shibboleth/sp/authn/impl/ValidateAgentAddress.java b/sp-server-impl/src/main/java/net/shibboleth/sp/authn/impl/ValidateAgentAddress.java
new file mode 100644
index 0000000..ff93203
--- /dev/null
+++ b/sp-server-impl/src/main/java/net/shibboleth/sp/authn/impl/ValidateAgentAddress.java
@@ -0,0 +1,125 @@
+/*
+ * 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 net.shibboleth.sp.authn.impl;
+
+import java.net.InetAddress;
+import java.util.function.Function;
+
+import javax.annotation.Nonnull;
+
+import org.opensaml.messaging.context.navigate.ChildContextLookup;
+import org.opensaml.profile.action.ActionSupport;
+import org.opensaml.profile.action.EventIds;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.slf4j.Logger;
+
+import com.google.common.net.InetAddresses;
+
+import jakarta.servlet.http.HttpServletRequest;
+import net.shibboleth.idp.profile.AbstractProfileAction;
+import net.shibboleth.shared.annotation.constraint.NonnullBeforeExec;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.primitive.LoggerFactory;
+import net.shibboleth.shared.servlet.HttpServletSupport;
+import net.shibboleth.sp.Agent;
+import net.shibboleth.sp.context.AgentRequestContext;
+
+/**
+ * An action that validates the requesting client address is allowed for the identified
+ * {@link Agent} identity.
+ * 
+ * @event {@link EventIds#PROCEED_EVENT_ID}
+ * @event {@link EventIds#INVALID_PROFILE_CTX}
+ * @event {@link EventIds#ACCESS_DENIED}
+ * @pre <pre>ProfileRequestContext.ensureSubcontext(AgentRequestContext.class).getAgent() != null</pre>
+ */
+public class ValidateAgentAddress extends AbstractProfileAction {
+
+    /** Class logger. */
+    @Nonnull private final Logger log = LoggerFactory.getLogger(ValidateAgentAddress.class);
+    
+    /** Lookup strategy for {@link AgentRequestContext}. */
+    @Nonnull private Function<ProfileRequestContext,AgentRequestContext> agentRequestContextLookupStrategy;
+    
+    /** Cached agent from context. */
+    @NonnullBeforeExec private Agent agent;
+
+    /** Constructor. */
+    public ValidateAgentAddress() {
+        agentRequestContextLookupStrategy = new ChildContextLookup<>(AgentRequestContext.class);
+    }
+    
+    /**
+     * Sets the lookup strategy for the {@link AgentRequestContext}.
+     * 
+     * @param strategy lookup strategy
+     */
+    public void setAgentRequestContextLookupStrategy(
+            @Nonnull final Function<ProfileRequestContext,AgentRequestContext> strategy) {
+        checkSetterPreconditions();
+        
+        agentRequestContextLookupStrategy = Constraint.isNotNull(strategy,
+                "AgentRequestContext lookup strategy cannot be null");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    protected boolean doPreExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
+        
+        if (!super.doPreExecute(profileRequestContext)) {
+            return false;
+        }
+        
+        final AgentRequestContext agentCtx = agentRequestContextLookupStrategy.apply(profileRequestContext);
+
+        agent = agentCtx != null ? agentCtx.getAgent() : null;
+        if (agent == null) {
+            ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_PROFILE_CTX);
+            return false;
+        }
+        
+        return true;
+    }
+    
+    /** {@inheritDoc} */
+    @Override
+    protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
+        final HttpServletRequest request = getHttpServletRequest();
+        if (request == null) {
+            log.warn("{} Request denied from agent '{}', no servlet request available", getLogPrefix(), agent.getId());
+            ActionSupport.buildEvent(profileRequestContext, EventIds.ACCESS_DENIED);
+            return;
+        }
+        
+        final String s = HttpServletSupport.getRemoteAddr(request);
+        try {
+            final InetAddress addr = s != null ? InetAddresses.forString(s) : null;
+            if (addr == null) {
+                throw new IllegalArgumentException("Client address unavailable.");
+            }
+            
+            if (agent.isAllowed(addr)) {
+                log.debug("{} Request permitted from agent '{}' from {}", getLogPrefix(), agent.getId(), s);
+            } else {
+                log.warn("{} Request denied from agent '{}' from {}", getLogPrefix(), agent.getId(), s);
+                ActionSupport.buildEvent(profileRequestContext, EventIds.ACCESS_DENIED);
+            }
+        } catch (final IllegalArgumentException e) {
+            log.warn("{} Request denied from agent '{}'", getLogPrefix(), agent.getId(), e);
+            ActionSupport.buildEvent(profileRequestContext, EventIds.ACCESS_DENIED);
+        }
+    }
+    
+}
\ No newline at end of file
diff --git a/sp-server-impl/src/main/java/net/shibboleth/sp/impl/BasicAgent.java b/sp-server-impl/src/main/java/net/shibboleth/sp/impl/BasicAgent.java
index 84d1b29..8b93a4b 100644
--- a/sp-server-impl/src/main/java/net/shibboleth/sp/impl/BasicAgent.java
+++ b/sp-server-impl/src/main/java/net/shibboleth/sp/impl/BasicAgent.java
@@ -76,14 +76,8 @@ public class BasicAgent extends DefaultRelyingPartyConfigurationResolver impleme
         
         allowedAddressRanges = ranges != null ? CollectionSupport.copyToSet(ranges) : CollectionSupport.emptySet();
     }
-    
-    /**
-     * Returns true iff the supplied address matches one of the allowed ranges.
-     * 
-     * @param address address to test
-     * 
-     * @return true iff the supplied address matches one of the allowed ranges
-     */
+
+    /** {@inheritDoc} */
     public boolean isAllowed(@Nonnull final InetAddress address) {
         return allowedAddressRanges.stream().anyMatch(r -> r.contains(address));
     }
diff --git a/sp-server-impl/src/test/java/net/shibboleth/sp/authn/impl/ValidateAgentAddressTest.java b/sp-server-impl/src/test/java/net/shibboleth/sp/authn/impl/ValidateAgentAddressTest.java
new file mode 100644
index 0000000..04b8c35
--- /dev/null
+++ b/sp-server-impl/src/test/java/net/shibboleth/sp/authn/impl/ValidateAgentAddressTest.java
@@ -0,0 +1,109 @@
+/*
+ * 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 net.shibboleth.sp.authn.impl;
+
+import org.opensaml.profile.action.EventIds;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.webflow.execution.Event;
+import org.springframework.webflow.execution.RequestContext;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import net.shibboleth.idp.authn.AuthnEventIds;
+import net.shibboleth.idp.authn.context.AuthenticationContext;
+import net.shibboleth.idp.authn.context.UsernamePasswordContext;
+import net.shibboleth.idp.profile.context.navigate.WebflowRequestContextProfileRequestContextLookup;
+import net.shibboleth.idp.profile.testing.ActionTestingSupport;
+import net.shibboleth.idp.profile.testing.RequestContextBuilder;
+import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.shared.component.ComponentInitializationException;
+import net.shibboleth.shared.net.IPRange;
+import net.shibboleth.shared.testing.ConstantSupplier;
+import net.shibboleth.sp.context.AgentRequestContext;
+import net.shibboleth.sp.impl.BasicAgent;
+
+/**
+ * Unit test for {@link ValidateAgentAddress} action.
+ */
+ at SuppressWarnings("javadoc")
+public class ValidateAgentAddressTest {
+
+    private RequestContext src;
+    private ProfileRequestContext prc;
+    private MockHttpServletRequest request;
+    
+    private BasicAgent agent;
+    private ValidateAgentAddress action;
+    
+    @BeforeMethod
+    public void setUp() throws ComponentInitializationException {
+        src = new RequestContextBuilder().buildRequestContext();
+        prc = new WebflowRequestContextProfileRequestContextLookup().apply(src);
+        
+        agent = new BasicAgent();
+        agent.setId("foo");
+        agent.setAllowedAddressRanges(CollectionSupport.setOf(IPRange.parseCIDRBlock("127.0.0.1/32"),
+                IPRange.parseCIDRBlock("192.168.1.0/24")));
+        agent.initialize();
+        
+        action = new ValidateAgentAddress();
+        request = new MockHttpServletRequest();
+        action.setHttpServletRequestSupplier(new ConstantSupplier<>(request));
+        action.initialize();
+    }
+
+    @Test
+    public void testNoAgent() {
+        
+        // No context.
+        Event event = action.execute(src);
+        ActionTestingSupport.assertEvent(event, EventIds.INVALID_PROFILE_CTX);
+        
+        // Empty context.
+        prc.ensureSubcontext(AuthenticationContext.class).ensureSubcontext(AgentRequestContext.class);
+        event = action.execute(src);
+        ActionTestingSupport.assertEvent(event, EventIds.INVALID_PROFILE_CTX);
+    }
+
+    @Test
+    public void testInvalidAddress() {
+        prc.ensureSubcontext(AgentRequestContext.class).setAgent(agent);
+        request.setRemoteAddr("bogus");
+        
+        final Event event = action.execute(src);
+        ActionTestingSupport.assertEvent(event, EventIds.ACCESS_DENIED);
+    }
+    
+    @Test
+    public void testDisallowedAddress() {
+        prc.ensureSubcontext(AgentRequestContext.class).setAgent(agent);
+        request.setRemoteAddr("192.168.2.100");
+        
+        final Event event = action.execute(src);
+        ActionTestingSupport.assertEvent(event, EventIds.ACCESS_DENIED);
+    }
+
+    @Test
+    public void testAllowedAddress() {
+        prc.ensureSubcontext(AgentRequestContext.class).setAgent(agent);
+        request.setRemoteAddr("192.168.1.100");
+        
+        final Event event = action.execute(src);
+        ActionTestingSupport.assertProceedEvent(event);
+    }
+
+}
\ No newline at end of file

-- 
To stop receiving notification emails like this one, please contact
the administrator of this repository.


More information about the commits mailing list