How to manually set/propagate security context information e.g. Principal for JBoss 7 (over JBoss remoting 2) - authentication

I'm using jboss remoting 2.5.4.SP3 to provide remote access to EJBs in a JBoss 7.1 server from both a web app and other JBoss instances. I'm doing it manually because of issues with remote EJB access in JBoss 7.1, specifically (but not only) the inability to access the same (interface) bean on multiple servers simultaneously. I'm using remoting2 because remoting3 has no documentation.
I have remoting working using TransporterHandle/TransporterClient using the socket transport, but in methods called via this remote connection, the server wants to lookup the principal from the ejbContext. I can't find a way to manually set the principal, or other contextual security/identity information. At the limit I'd be happy just to set the principal when the ejb method is invoked - all incoming calls are to local EJB3 beans - or even to set it specifically for the EJBContext.
I've found a lot of information regarding Spring (which I'm not using), but nothing seems to match my particular context.

And now, the correct way to do this:
On the client side I get the security context and package up the security domain and subject info for transport to the server along with the invocation. The SecurityDomain is a String and SubjectInfo is serializable:
Map m = new HashMap();
SecurityContext securityContext = SecurityContextAssociation.getSecurityContext();
if (securityContext != null) {
m.put("SUBJECT-INFO", securityContext.getSubjectInfo());
m.put("SECURITY-DOMAIN", securityContext.getSecurityDomain());
}
response = remotingClient.invoke(request, m);
The map m gets sent with the invocation over jboss remoting. On the server side, I extract the security information and set the context for the invocation like this:
SecurityContext oldContext = SecurityContextAssociation.getSecurityContext();
SubjectInfo si = (SubjectInfo) invocation.getRequestPayload().get("SUBJECT-INFO");
String domain = (String) invocation.getRequestPayload().get("SECURITY-DOMAIN");
if (si != null) {
SecurityContext sc = new JBossSecurityContext(domain);
sc.setSubjectInfo(si);
SecurityContextAssociation.setSecurityContext(sc);
}
try {
return super.invoke(invocation);
} finally {
SecurityContextAssociation.setSecurityContext(oldContext);
}
Works like a charm!

Have a look at the jboss-ejb-client.properties. There is also a quickstart example using a remote client to lookup an EJB.

I've solved my underlying problem, although not in the general way I was hoping for.
I put a servlet filter on all incoming requests, recording request.getUserPrincipal in a thread local. I can then access this in non-EE code and find the principal making the request. Then when I make call to my app server I use JBoss Remoting's ability to attach metadata to each invocation to pass the Principal over the wire. I had to copy the TransporterClient to do this because it's private constructors et al don't allow for overriding the functionality required to attach per-request metadata (as opposed to per-connection). On the server side I take the incoming Principal and set it into a thread local. Then, in subsequent code that accesses EJBContext.getCallerPrincipal I also lookup the incoming Principal from the thread local, and if that isn't null (hence we are in a remote EJB call), I use that if the caller principal is anonymous. If it's not anonymous then it must have been set in some way after the incoming call, so I ignore the incoming Principal in that case.
All in all, a much more specialised solution than I was hoping for, and it doesn't shed any light on how I can do generic context propagation in JBoss 7.1 over the wire.

Related

Spring Session Redis with Sticky session on server side for log

Hi i have a Redis configured on my Spring project to use Spring Session, i'm using Jedis 2.9.0 and it works well. The problem I have is with the Sticky session on the Websphere Server, we have 2 main servers and 10 clones of each, with normal httpSession it uses the cookie to handle the request of that cookie to the same server again, good, but with Spring Session it doesn't work the same.
Spring create the cookie with the name "SESSION" and the Load Balancing of Websphere doesn't know where to redirect the request because the session is not on the JVM but is ditributed in Redis Cluster.
i need to (for log order porpuse) handle every request of cookie "abc123" to the server 1 clon 3 for example, and if that instance of the application goes down track that cookie to another instance and stay on that instance until the server goes down again or the user logout...
Searching here and the Spring Session doc, i found something that might be useful but I dont know how it works.
#Bean
public CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setCookieName("JSESSIONID");
serializer.setCookiePath("/");
serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
serializer.setJvmRoute("123");
return serializer;
}
The atribute Jvm Route adds a suffix to the cookie to know whats the JVM that handle that cookie, but i don't know how it works and I haven't been lucky finding examples or explanation about it.
if anyone have the answer or another workaround that i could use it will be great.

How to impersonate Nservicebus

Hi How to impersonate Nservicebus. I am using Nservicebus 5.2 version.
I see some code for old version but that is not available in new version.
Do we have some sample which demonstrate the impersonate in 5.2 version.
Configure.With()
.StructureMapBuilder()
.Sagas()
.RunTimeoutManager()
.UnicastBus()
.ImpersonateSender(false)
In New version there is no way to set
ImpersonateSender
Does anyone know how to pass the exact currentprincipal object up to END points?
I tried to start my endpoint by below command line.
Start NServiceBus.Host.exe /displayName:"myservice" /username:"mydomain\myname" /password:"mypwd"
However when I log userName then it is not picking the same username which I used to start endpoint.
public void Customize(BusConfiguration configuration)
{
configuration.UsePersistence<RavenDBPersistence>()
Console.WriteLine("-------------------NAME--------------\n");
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
Console.WriteLine("-------------------NAME--------------\n");
Console.WriteLine("-------------------NAME--------------\n");
Console.WriteLine(Thread.CurrentPrincipal.Identity.Name);
Console.WriteLine("-------------------NAME--------------\n");
}
output comes like:
-------------------NAME--------------
MYNetworkDomain\MyMachineLoggedInNTId
-------------------NAME--------------
-------------------NAME--------------
-------------------NAME--------------
Impersonation in .Net can have many flavors and may not end up behaving as you might expect.
In v4 when .ImpersonateSender(...) was set to true the behavior was to deliver along with the message, using a message header, the identity name used at the sender endpoint, the recipient would have used the incoming message header to set up a new generic identity.
It is not a real impersonation, not to mention that impersonation to work across different machines requires delegation to be set up, with all the security concerns that delegation brings to the table. Not to mention that, AFAIK, Windows Identity impersonation can't be done at the thread level, the security token is attached to the process and can't be overwritten by a thread pretending to be a different user.
That said, nothing prevents you to build your own logic to deliver identities along with messages in order to have .Net identity/principal infrastructure setup as you like and be able to perform security checks via the Role infrastructure.

Re-route/Divert some WL.Client Adapter Invocation traffic to WL Server through different URL (for PCI payment and security requirements)?

Worklight 5.0.6.1
We are having a specific requirement from our client about using a PCI Appliance from Intel (http://info.intel.com/rs/intel/images/Intel_Expressway_Tokenization_Broker.pdf) to avoid a PCI Audit for the application and server.
Therefore, the Adapter calls that have something to do with payment data would need to go through this hardware appliance before hitting the worklight server. All other adapter calls should go to the worklight server directly (to not overload the appliance).
The idea is to have two different URLs but the same worklight server in the background. It is assumed that the calls through the appliance will be transparent for the worklight server, so worklight functionality should not be impacted.
My questions around this would be:
a Worklight best-practice for having two different URLs for the same worklight server and alternating those URLs from the client for Adapter invocations (only; not direct update or anything else, since we assume this is executed native)?
is it possible to dynamically overwrite the worklight server URL that is used for an adapter invocation through JavaScript code in the client code? e.g. overwrite a specific JS function that gets/returns the worklight URL from somewhere before the WL.Client AJAX adapter invocation?
We are also looking into having a load-balancer switch the route based on a regex of the AdapterName that is being invoked or so. But it is not sure right now if that is possible and what the performance impact is.
Though possible, this is not something supported by WL. You will not be able to get help from support in case something goes wrong (and it will). You have to keep in mind that all server cookies (e.g. session id) are per domain. Therefore when you're dynamically changing server URL you will loose them. Therefore WL server will treat your request as a new session, unrelated to an old (existing) one. This is not something specific to WL, this is how HTTP works.
WL keeps server URLs in two global properties - WL.AppProp.WORKLIGHT_ROOT_URL and WL.AppProp.APP_SERVICES_URL. You can override them thus changing server URLs.
First one is used for all requests triggered by developer (init, connect, login etc). Second one is used for miscellaneous internal functionality (e.g. encrypted cache).
Once again - this is a hack, definitely not a solution. Use with caution if at all:)
How About this,if we define our own function that will call some static properties and update them ?
function changeServerUrl(serverURL) {
WL.StaticAppProps.APP_SERVICES_URL = serverURL + WL.StaticAppProps.POSTFIX_APP_SERVICES_URL;
WL.StaticAppProps.WORKLIGHT_ROOT_URL = serverURL + WL.StaticAppProps.POSTFIX_WORKLIGHT_ROOT_URL;
WL.StaticAppProps.WORKLIGHT_BASE_URL = serverURL;
}
and call it
chnageServerUrl("http://"+yourServerIP+":"+PORT);
if you dig into the worklight.js file there is a function "setWLUrl(url)" that can be use to change the serevr URL.
call it like this and its done
setWLUrl("http://"+yourServerIP+":PORT");
its kind a hack but i think it should not have anny issue since its a function within there api.
Good Luck

How to call Apache NMS from in a sandbox?

I'm trying to call Apache ActiveMQ NMS Version 1.6.0 from my code ('IntPub') that must run in a sandbox in a .NET 4.0 environment for security reasons. The program that creates the sandbox makes my code 'partially trusted' and therefore 'security-transparent' which seems to mean that it can't create a ConnectionFactory (see error log below) because NMS seems to be 'security-critical'. Here's the code that's causing this error:
connecturi = new Uri("tcp://my.server.com:61616");
var connectionFactory = new ConnectionFactory(connecturi);
I also tried this instead with similar results:
connecturi = new Uri("activemq:tcp://my.server.com:61616");
var connectionFactory = NMSConnectionFactory.CreateConnectionFactory(connecturi);
Since I can't change the security level of my assembly (the sandbox prevents it) is there a way to make NMS run as 'safe-critical' so it can be called by 'security-transparent' code? Would I have to recompile it to do so, or does NMS do some operation that would never be considered 'safe-critical?
I appreciate any help or suggestions...
Assembly 'IntPub, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6fa620743b8dc60a' is partially trusted, which causes the CLR to make it entirely security transparent regardless of any transparency annotations in the assembly itself. In order to access security critical code, this assembly must be fully trusted.Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220956</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>Unexpected exception from plug-in (Execute): Test.Client: System.MethodAccessException: Attempt by security transparent method 'Test.Client.Execute(System.IServiceProvider)' to access security critical method 'Apache.NMS.ActiveMQ.ConnectionFactory..ctor(System.Uri)' failed.
From the error message attributes, it looks like you're running a Dynamics CRM 2011 plugin in sandbox mode, which has some very specific rules about what you can and can't do. In particular, you're only allowed to make network connections via HTTP and HTTPS, so attempting raw TCP sockets will definitely fail.
Take a look at this MSDN page on Plug-in Isolation, Trusts, and Statistics. It looks like there may be a way to relax the network restrictions by modifying a system registry entry to include tcp, etc, in the regex value. Below is an excerpt from the page. Note: I have not done this myself, so can't say for sure it'll work.
Sandboxed plug-ins and custom workflow activities can access the
network through the HTTP and HTTPS protocols. This capability provides
support for accessing popular web resources like social sites, news
feeds, web services, and more. The following web access restrictions
apply to this sandbox capability.
Only the HTTP and HTTPS protocols are allowed.
Access to localhost (loopback) is not permitted.
IP addresses cannot be used. You must use a named web address that requires DNS name resolution.
Anonymous authentication is supported and recommended. There is no provision for prompting the logged on user for credentials or saving those credentials.
These default web access restrictions are defined in a registry key on
the server that is running the Microsoft.Crm.Sandbox.HostService.exe
process. The value of the registry key can be changed by the System
Administrator according to business and security needs. The registry
key path on the server is:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM\SandboxWorkerOutboundUriPattern
The key value is a regular expression string that defines the web access restrictions.
The default key value is:
"^http[s]?://(?!((localhost[:/])|([.])|([0-9]+[:/])|(0x[0-9a-f]+[:/])|(((([0-9]+)|(0x[0-9A-F]+)).){3}(([0-9]+)|(0x[0-9A-F]+))[:/]))).+";*
By changing this registry key value, you can change the web access for sandboxed plug-ins.

EJB lookup problem

I have a Glassfish v2.1.1 cluster setup. I deployed an EAR file consisting a single stateless bean to stand alone server. It has an IIOP port 3752.
My client application which will be communicating with this bean is deployed on cluster. When i lookup bean's name, i get NameNotFoundException. Code looks as below:
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
if (logger.isDebugEnabled()) {
logger.debug("Looking for bean from location : " + PropertiesService.instance().getSchedulerOrbHost() + ":"
+ PropertiesService.instance().getSchedulerOrbPort());
}
props.setProperty("org.omg.CORBA.ORBInitialHost", PropertiesService.instance().getSchedulerOrbHost());
props.setProperty("org.omg.CORBA.ORBInitialPort", PropertiesService.instance().getSchedulerOrbPort());
InitialContext context = null;
try {
context = new InitialContext(props);
} catch (NamingException e) {
e.printStackTrace();
}
String beanName = "test.OperationControllerRemote";
OperationControllerRemote remote = (OperationControllerRemote) context.lookup(beanName);
Note that i checked JNDI tree and name "test.OperationControllerRemote" is there.
Any opinions please?
Here are the ways I have got it to work with a GF 2.1.1 cluster and a Swing client. I'm currently going with the Standalone option because of client launch speed, but the ACC might work for you.
Standalone
The way you're doing it is considered standalone.
http://glassfish.java.net/javaee5/ejb/EJB_FAQ.html#StandaloneRemoteEJB
http://blogs.oracle.com/dadelhardt/entry/standalone_iiop_clients_with_glassfish
ACC
Another way to approach this is to launch the client with the ACC. This means packaging the client code into the ear as an Application Client and either launching using the JNLP method or manually installing a bundled ACC (mini glassfish really) on client machines. In GF 2.1, either way works ok, but both are pretty fat and JNLP method can make startup times a bit longer. Supposedly in GF 3.1 they've reworked the ACC and it starts up faster. Something that may not be obvious is that with the ACC you get the list of servers in the cluster provided automatically at client startup.
http://blogs.oracle.com/theaquarium/entry/java_ee_clients_with_or
http://download.oracle.com/docs/cd/E18930_01/html/821-2418/beakv.html#scrolltoc
http://download.oracle.com/docs/cd/E18930_01/html/821-2418/gkusn.html
Lookups
Either of the above ways provides RMI/CORBA failover and load balancing for the client.
Either way, when you have the right dependencies on your classpath and the com.sun.appserv.iiop.endpoints system property set (like node1:33700,node2:33701), you'll only need the no-args InitialContext because Glassfish's stuff autoregisters their connection properties, etc as described in the first link:
new InitialContext()
And lookups will work. For my remote session beans (EJB 3.0) I typically do it like:
#Stateless(mappedName="FooBean")
public class FooBean implements FooBeanRemote {}
#Remote
public interface FooBeanRemote {}
then in client code:
FooBeanRemote foo = (FooBeanRemote) ctx.lookup("FooBean");