SEC-1743: Separate remoting from core into separate module.

This commit is contained in:
Luke Taylor
2011-05-14 11:57:30 +01:00
parent 1c1ffe2f0f
commit 295ea27526
22 changed files with 65 additions and 5 deletions

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* 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.springframework.security.remoting.dns;
/**
* This will be thrown if no entry matches the specified DNS query.
*
* @author Mike Wiesner
* @since 3.0
*/
public class DnsEntryNotFoundException extends DnsLookupException {
private static final long serialVersionUID = -947232730426775162L;
public DnsEntryNotFoundException(String msg) {
super(msg);
}
public DnsEntryNotFoundException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* 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.springframework.security.remoting.dns;
/**
* This will be thrown for unknown DNS errors.
*
* @author Mike Wiesner
* @since 3.0
*/
public class DnsLookupException extends RuntimeException {
public DnsLookupException(String msg, Throwable cause) {
super(msg, cause);
}
public DnsLookupException(String msg) {
super(msg);
}
}

View File

@@ -1,73 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* 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.springframework.security.remoting.dns;
/**
* Helper class for DNS operations.
*
* @author Mike Wiesner
* @since 3.0
*/
public interface DnsResolver {
/**
* Resolves the IP Address (A record) to the specified host name.
* Throws DnsEntryNotFoundException if there is no record.
*
* @param hostname The hostname for which you need the IP Address
* @return IP Address as a String
* @throws DnsEntryNotFoundException No record found
* @throws DnsLookupException Unknown DNS error
*/
public String resolveIpAddress(String hostname) throws DnsEntryNotFoundException, DnsLookupException;
/**
* <p>Resolves the host name for the specified service in the specified domain</p>
* <p>For example, if you need the host name for an LDAP server running in the
* domain springsource.com, you would call <b>resolveServiceEntry("ldap", "springsource.com")</b>.</p>
*
* <p>The DNS server needs to provide the service records for this, in the example above, it
* would look like this:
*
* <pre>_ldap._tcp.springsource.com IN SRV 10 0 88 ldap.springsource.com.</pre>
*
* The method will return the record with highest priority (which means the lowest number in the DNS record)
* and if there are more than one records with the same priority, it will return the one with the highest weight.
* You will find more informatione about DNS service records at <a href="http://en.wikipedia.org/wiki/SRV_record">Wikipedia</a>.</p>
*
* @param serviceType The service type you are searching for, e.g. ldap, kerberos, ...
* @param domain The domain, in which you are searching for the service
* @return The hostname of the service
* @throws DnsEntryNotFoundException No record found
* @throws DnsLookupException Unknown DNS error
*/
public String resolveServiceEntry(String serviceType, String domain) throws DnsEntryNotFoundException, DnsLookupException;
/**
* Resolves the host name for the specified service and then the IP Address for this host in one call.
*
* @param serviceType The service type you are searching for, e.g. ldap, kerberos, ...
* @param domain The domain, in which you are searching for the service
* @return IP Address of the service
* @throws DnsEntryNotFoundException No record found
* @throws DnsLookupException Unknown DNS error
* @see #resolveServiceEntry(String, String)
* @see #resolveIpAddress(String)
*/
public String resolveServiceIpAddress(String serviceType, String domain) throws DnsEntryNotFoundException, DnsLookupException;
}

View File

@@ -1,41 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* 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.springframework.security.remoting.dns;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
* This is used in JndiDnsResolver to get an InitialDirContext for DNS queries.
*
* @author Mike Wiesner
* @since 3.0
* @see InitialDirContext
* @see DirContext
* @see JndiDnsResolver
*/
public interface InitialContextFactory {
/**
* Must return a DirContext which can be used for DNS queries
* @return JNDI DirContext
*/
public DirContext getCtx();
}

View File

@@ -1,168 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* 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.springframework.security.remoting.dns;
import java.util.*;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
* Implementation of DnsResolver which uses JNDI for the DNS queries.
*
* Uses an <b>InitialContextFactory</b> to get the JNDI DirContext. The default implementation
* will just create a new Context with the context factory <b>com.sun.jndi.dns.DnsContextFactory</b>
*
* @author Mike Wiesner
* @since 3.0
* @see DnsResolver
* @see InitialContextFactory
*/
public class JndiDnsResolver implements DnsResolver {
private InitialContextFactory ctxFactory = new DefaultInitialContextFactory();
/**
* Allows to inject an own JNDI context factory.
*
* @param ctxFactory factory to use, when a DirContext is needed
* @see InitialDirContext
* @see DirContext
*/
public void setCtxFactory(InitialContextFactory ctxFactory) {
this.ctxFactory = ctxFactory;
}
/* (non-Javadoc)
* @see org.springframework.security.remoting.dns.DnsResolver#resolveIpAddress(java.lang.String)
*/
public String resolveIpAddress(String hostname) {
return resolveIpAddress(hostname, ctxFactory.getCtx());
}
/* (non-Javadoc)
* @see org.springframework.security.remoting.dns.DnsResolver#resolveServiceEntry(java.lang.String, java.lang.String)
*/
public String resolveServiceEntry(String serviceType, String domain) {
return resolveServiceEntry(serviceType, domain, ctxFactory.getCtx());
}
/* (non-Javadoc)
* @see org.springframework.security.remoting.dns.DnsResolver#resolveServiceIpAddress(java.lang.String, java.lang.String)
*/
public String resolveServiceIpAddress(String serviceType, String domain) {
DirContext ctx = ctxFactory.getCtx();
String hostname = resolveServiceEntry(serviceType, domain, ctx);
return resolveIpAddress(hostname, ctx);
}
// This method is needed, so that we can use only one DirContext for
// resolveServiceIpAddress().
private String resolveIpAddress(String hostname, DirContext ctx) {
try {
Attribute dnsRecord = lookup(hostname, ctx, "A");
// There should be only one A record, therefore it is save to return
// only the first.
return dnsRecord.get().toString();
} catch (NamingException e) {
throw new DnsLookupException("DNS lookup failed for: "+ hostname, e);
}
}
// This method is needed, so that we can use only one DirContext for
// resolveServiceIpAddress().
private String resolveServiceEntry(String serviceType, String domain, DirContext ctx) {
String result = null;
try {
String query = new StringBuilder("_").append(serviceType).append("._tcp.").append(domain).toString();
Attribute dnsRecord = lookup(query, ctx, "SRV");
// There are maybe more records defined, we will return the one
// with the highest priority (lowest number) and the highest weight
// (highest number)
int highestPriority = -1;
int highestWeight = -1;
for (NamingEnumeration<?> recordEnum = dnsRecord.getAll(); recordEnum.hasMoreElements();) {
String[] record = recordEnum.next().toString().split(" ");
if (record.length != 4) {
throw new DnsLookupException("Wrong service record for query " + query + ": [" + Arrays.toString(record) + "]");
}
int priority = Integer.parseInt(record[0]);
int weight = Integer.parseInt(record[1]);
// we have a new highest Priority, so forget also the highest weight
if (priority < highestPriority || highestPriority == -1) {
highestPriority = priority;
highestWeight = weight;
result = record[3].trim();
}
// same priority, but higher weight
if (priority == highestPriority && weight > highestWeight) {
highestWeight = weight;
result = record[3].trim();
}
}
} catch (NamingException e) {
throw new DnsLookupException("DNS lookup failed for service " + serviceType + " at " + domain, e);
}
// remove the "." at the end
if (result.endsWith(".")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
private Attribute lookup(String query, DirContext ictx, String recordType) {
try {
Attributes dnsResult = ictx.getAttributes(query, new String[] { recordType });
return dnsResult.get(recordType);
} catch (NamingException e) {
if (e instanceof NameNotFoundException) {
throw new DnsEntryNotFoundException("DNS entry not found for:" + query, e);
}
throw new DnsLookupException("DNS lookup failed for: " + query, e);
}
}
private static class DefaultInitialContextFactory implements InitialContextFactory {
public DirContext getCtx() {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
env.put(Context.PROVIDER_URL, "dns:"); // This is needed for IBM JDK/JRE
InitialDirContext ictx;
try {
ictx = new InitialDirContext(env);
} catch (NamingException e) {
throw new DnsLookupException("Cannot create InitialDirContext for DNS lookup", e);
}
return ictx;
}
}
}

View File

@@ -1,4 +0,0 @@
/**
* DNS resolution.
*/
package org.springframework.security.remoting.dns;

View File

@@ -1,85 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.remoting.httpinvoker;
import java.io.IOException;
import java.net.HttpURLConnection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Adds BASIC authentication support to <code>SimpleHttpInvokerRequestExecutor</code>.
*
* @author Ben Alex
*/
public class AuthenticationSimpleHttpInvokerRequestExecutor extends SimpleHttpInvokerRequestExecutor {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(AuthenticationSimpleHttpInvokerRequestExecutor.class);
//~ Methods ========================================================================================================
/**
* Provided so subclasses can perform additional configuration if required (eg set additional request
* headers for non-security related information etc).
*
* @param con the HTTP connection to prepare
* @param contentLength the length of the content to send
*
* @throws IOException if thrown by HttpURLConnection methods
*/
protected void doPrepareConnection(HttpURLConnection con, int contentLength)
throws IOException {}
/**
* Called every time a HTTP invocation is made.<p>Simply allows the parent to setup the connection, and
* then adds an <code>Authorization</code> HTTP header property that will be used for BASIC authentication.</p>
* <p>The <code>SecurityContextHolder</code> is used to obtain the relevant principal and credentials.</p>
*
* @param con the HTTP connection to prepare
* @param contentLength the length of the content to send
*
* @throws IOException if thrown by HttpURLConnection methods
*/
protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException {
super.prepareConnection(con, contentLength);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if ((auth != null) && (auth.getName() != null) && (auth.getCredentials() != null)) {
String base64 = auth.getName() + ":" + auth.getCredentials().toString();
con.setRequestProperty("Authorization", "Basic " + new String(Base64.encode(base64.getBytes())));
if (logger.isDebugEnabled()) {
logger.debug("HttpInvocation now presenting via BASIC authentication SecurityContextHolder-derived: "
+ auth.toString());
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Unable to set BASIC authentication header as SecurityContext did not provide "
+ "valid Authentication: " + auth);
}
}
doPrepareConnection(con, contentLength);
}
}

View File

@@ -1,19 +0,0 @@
/**
* Enables use of Spring's <code>HttpInvoker</code> extension points to
* present the <code>principal</code> and <code>credentials</code> located
* in the <code>ContextHolder</code> via BASIC authentication.
* <p>
* The beans are wired as follows:
*
* <pre>
* &lt;bean id="test" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"&gt;
* &lt;property name="serviceUrl"&gt;&lt;value&gt;http://localhost/Test&lt;/value&gt;&lt;/property&gt;
* &lt;property name="serviceInterface"&gt;&lt;value&gt;test.TargetInterface&lt;/value&gt;&lt;/property&gt;
* &lt;property name="httpInvokerRequestExecutor"&gt;&lt;ref bean="httpInvokerRequestExecutor"/&gt;&lt;/property&gt;
* &lt;/bean&gt;
*
* &lt;bean id="httpInvokerRequestExecutor"
* class="org.springframework.security.core.context.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor"/&gt;
* </pre>
*/
package org.springframework.security.remoting.httpinvoker;

View File

@@ -1,4 +0,0 @@
/**
* Remote client related functionality.
*/
package org.springframework.security.remoting;

View File

@@ -1,114 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.remoting.rmi;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.remoting.support.RemoteInvocation;
import java.lang.reflect.InvocationTargetException;
/**
* The actual <code>RemoteInvocation</code> that is passed from the client to the server, which contains the
* contents of {@link SecurityContextHolder}, being a {@link SecurityContext} object.
* <p>
* When constructed on the client via {@link ContextPropagatingRemoteInvocationFactory}, the contents of the
* <code>SecurityContext</code> are stored inside the object. The object is then passed to the server that is
* processing the remote invocation. Upon the server invoking the remote invocation, it will retrieve the passed
* contents of the <code>SecurityContextHolder</code> and set them on the server-side
* <code>SecurityContextHolder</code> while the target object is invoked. When the target invocation has been
* completed, the security context will be cleared using a call to {@link SecurityContextHolder#clearContext()}.
*
* @author James Monaghan
* @author Ben Alex
*/
public class ContextPropagatingRemoteInvocation extends RemoteInvocation {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private static final Log logger = LogFactory.getLog(ContextPropagatingRemoteInvocation.class);
//~ Instance fields ================================================================================================
private final SecurityContext securityContext;
//~ Constructors ===================================================================================================
/**
* Constructs the object, storing the value of the client-side
* <code>SecurityContextHolder</code> inside the object.
*
* @param methodInvocation the method to invoke
*/
public ContextPropagatingRemoteInvocation(MethodInvocation methodInvocation) {
super(methodInvocation);
securityContext = SecurityContextHolder.getContext();
if (logger.isDebugEnabled()) {
logger.debug("RemoteInvocation now has SecurityContext: " + securityContext);
}
}
//~ Methods ========================================================================================================
/**
* Invoked on the server-side as described in the class JavaDocs.
* <p>
* Invocations will always have their {@link org.springframework.security.core.Authentication#setAuthenticated(boolean)}
* set to <code>false</code>, which is guaranteed to always be accepted by <code>Authentication</code>
* implementations. This ensures that even remotely authenticated <code>Authentication</code>s will be untrusted by
* the server-side, which is an appropriate security measure.
*
* @param targetObject the target object to apply the invocation to
*
* @return the invocation result
*
* @throws NoSuchMethodException if the method name could not be resolved
* @throws IllegalAccessException if the method could not be accessed
* @throws InvocationTargetException if the method invocation resulted in an exception
*/
public Object invoke(Object targetObject)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
SecurityContextHolder.setContext(securityContext);
if ((SecurityContextHolder.getContext() != null)
&& (SecurityContextHolder.getContext().getAuthentication() != null)) {
SecurityContextHolder.getContext().getAuthentication().setAuthenticated(false);
}
if (logger.isDebugEnabled()) {
logger.debug("Set SecurityContextHolder to contain: " + securityContext);
}
try {
return super.invoke(targetObject);
} finally {
SecurityContextHolder.clearContext();
if (logger.isDebugEnabled()) {
logger.debug("Cleared SecurityContextHolder.");
}
}
}
}

View File

@@ -1,38 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.remoting.rmi;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.remoting.support.RemoteInvocation;
import org.springframework.remoting.support.RemoteInvocationFactory;
/**
* Called by a client-side instance of <code>org.springframework.remoting.rmi.RmiProxyFactoryBean</code> when it
* wishes to create a remote invocation.<P>Set an instance of this bean against the above class'
* <code>remoteInvocationFactory</code> property.</p>
*
* @author James Monaghan
* @author Ben Alex
*/
public class ContextPropagatingRemoteInvocationFactory implements RemoteInvocationFactory {
//~ Methods ========================================================================================================
public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
return new ContextPropagatingRemoteInvocation(methodInvocation);
}
}

View File

@@ -1,18 +0,0 @@
/**
* Enables use of Spring's RMI remoting extension points to propagate the <code>SecurityContextHolder</code> (which
* should contain an <code>Authentication</code> request token) from one JVM to the remote JVM.
* <p>
* The beans are wired as follows:
* <pre>
* &lt;bean id="test" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"&gt;
* &lt;property name="serviceUrl"&gt;&lt;value&gt;rmi://localhost/Test&lt;/value&gt;&lt;/property&gt;
* &lt;property name="serviceInterface"&gt;&lt;value&gt;test.TargetInterface&lt;/value&gt;&lt;/property&gt;
* &lt;property name="refreshStubOnConnectFailure"&gt;&lt;value&gt;true&lt;/value&gt;&lt;/property&gt;
* &lt;property name="remoteInvocationFactory"&gt;&lt;ref bean="remoteInvocationFactory"/&gt;&lt;/property&gt;
* &lt;/bean&gt;
*
* &lt;bean id="remoteInvocationFactory"
* class="org.springframework.security.remoting.rmi.ContextPropagatingRemoteInvocationFactory"/&gt;
* </pre>
*/
package org.springframework.security.remoting.rmi;