User: pra
Date: 02/03/06 09:27:50
Added: src/main/org/jboss/mq/security SecurityManager.java
SecurityManagerMBean.java SecurityMetadata.java
ServerSecurityInvoker.java SessionIDGenerator.java
Log:
Commit of JBossMQ new JAAS based security architecture
Revision Changes Path
1.1 jbossmq/src/main/org/jboss/mq/security/SecurityManager.java
Index: SecurityManager.java
===================================================================
/*
* JBoss, the OpenSource EJB server
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.mq.security;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.HashMap;
import java.security.Principal;
import java.security.acl.Group;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.Subject;
import javax.management.ObjectName;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.InvalidAttributeValueException;
import javax.jms.JMSException;
import javax.jms.JMSSecurityException;
import org.jboss.security.SecurityAssociation;
import org.jboss.security.SecurityPolicy;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.SubjectSecurityManager;
import org.jboss.system.ServiceMBeanSupport;
import org.jboss.mq.ConnectionToken;
import org.jboss.mq.server.JMSServerInvoker;
/**
* A JAAS based security manager for JBossMQ.
*
* @author <a href="[EMAIL PROTECTED]">Peter Antman</a>
* @version $Revision: 1.1 $
*/
public class SecurityManager
extends ServiceMBeanSupport
implements SecurityManagerMBean
{
/**
* Cached info on subject, to speed lookups.
*/
class SubjectInfo {
Subject subject;
Principal principal;
Group roles;
public String toString() {
return "SubjectInfo
{subject="+subject+";principal="+principal+";roles="+roles.toString();
}
}
private ObjectName name;
String securityDomainName = "java:/jaas/jbossmq";
Context securityCtx;
HashMap authCache = new HashMap(32);
HashMap securityConf = new HashMap(32);
ServerSecurityInvoker invoker;
SubjectSecurityManager sec;//FIXME
SessionIDGenerator idGenerator;
protected ObjectName getObjectName(MBeanServer server, ObjectName name)
throws MalformedObjectNameException
{
this.name = name == null ? OBJECT_NAME : name;
return this.name;
}
public JMSServerInvoker getInvoker() {
return invoker;
}
// DEBUGGING METHOD: DANGEROUS
public String printAuthCache() {
return authCache.toString();
}
public void addDestination(String destName, org.w3c.dom.Element conf) throws
Exception {
SecurityMetadata m = new SecurityMetadata(conf);
securityConf.put(destName,m);
}
public void addDestination(String destName, String conf) throws Exception {
SecurityMetadata m = new SecurityMetadata(conf);
securityConf.put(destName,m);
}
public void removeDestination(String destName) throws Exception {
securityConf.remove(destName);
}
public SecurityMetadata getSecurityMetadata(String destName) {
SecurityMetadata m = (SecurityMetadata)securityConf.get(destName);
if (m == null) {
// No SecurityManager was configured for the dest,
// default to guest
log.warn("No SecurityMetadadata was available for " + destName + " adding
default security conf");
m = new SecurityMetadata();
securityConf.put(destName,m);
}
return m;
}
public void startService() throws Exception {
// Get the JBoss security manager from the ENC context
try
{
InitialContext iniCtx = new InitialContext();
//securityCtx = (Context) iniCtx.lookup(securityDomainName);
// FIXME, should we really lookit up here
sec = (SubjectSecurityManager)iniCtx.lookup(securityDomainName);
}
catch(NamingException e)
{
// Apparently there is no security context?
}
invoker = new ServerSecurityInvoker(this);
idGenerator = new SessionIDGenerator();
}
public void stopService() throws Exception
{
// Anything to do here?
}
public String authenticate(String user, String password) throws JMSException {
/*
try {
o = securityCtx.lookup("securityMgr");
}catch(NamingException ex) {
throw new JMSException("Could not get a security context");
}
*/
boolean trace = log.isTraceEnabled();
if (sec instanceof SubjectSecurityManager) {
SubjectSecurityManager securityMgr =(SubjectSecurityManager)sec;
SimplePrincipal principal = new SimplePrincipal(user);
char[] passwordChars = null;
if( password != null )
passwordChars = password.toCharArray();
if( securityMgr.isValid(principal, passwordChars) )
{
if (trace)
log.trace("Username: "+user+" is authenticated");
// Put it in the assoc, so that the manager
// login callback can get them from it
SecurityAssociation.setPrincipal(principal);
SecurityAssociation.setCredential(passwordChars);
Subject subject = securityMgr.getActiveSubject();
String sessionId = generateId(subject);
addId(sessionId,subject, principal);
// Should we log it out since we do not use manager any more?
return sessionId;
}
else
{
if (trace)
log.trace("User: "+user+" is NOT authenticated");
throw new JMSSecurityException("User: "+user+" is NOT authenticated");
}
} else {
throw new IllegalStateException("SecurityManager only works with a
SubjectSecurityManager");
}
}
public boolean authorize(ConnectionToken token, Set rolePrincipals) throws
JMSException
{
//Unfortunately we can not reliably use the securityManager and its
// subject, since can not guarantee that every connection is
// connected to a unique thread.
// For now we implement the RealmMapping our self
boolean trace = log.isTraceEnabled();
boolean hasRole = false;
SubjectInfo info = ( SubjectInfo)authCache.get(token.getSessionId());
if (info == null)
throw new JMSSecurityException("User session is not valid");
if (trace)
log.trace("Checking authorize on subjectInfo: " + info.toString() + " for
rolePrincipals " + rolePrincipals.toString());
Group group = info.roles;
if( group != null )
{
Iterator iter = rolePrincipals.iterator();
while( hasRole == false && iter.hasNext() )
{
Principal role = (Principal) iter.next();
hasRole = group.isMember(role);
}
}
return hasRole;
}
// Is this a security problem? May a bad user set this manually and log out other
users?
public void logout(ConnectionToken token) {
if (token == null)
return;// Not much we can do
// FIXME - how do we clear the thread local in security manager?
removeId(token.getSessionId());
}
private void addId(String id, Subject subject, Principal callerPrincipal) {
boolean trace = log.isTraceEnabled();
SubjectInfo info = new SubjectInfo();
info.subject = subject;
info.principal = callerPrincipal;
Set subjectGroups = subject.getPrincipals(Group.class);
Iterator iter = subjectGroups.iterator();
while( iter.hasNext() )
{
Group grp = (Group) iter.next();
String name = grp.getName();
if( name.equals("CallerPrincipal") )
{
Enumeration members = grp.members();
if( members.hasMoreElements() )
info.principal = (Principal) members.nextElement();
}
else if( name.equals("Roles") ) {
if (trace)
log.trace("Adding group : " + grp.getClass() + " " + grp.toString());
info.roles = grp;
}
}
/* Handle null principals with no callerPrincipal. This is an indication
of an user that has not provided any authentication info, but
has been authenticated by the domain login module stack. Here we look
for the first non-Group Principal and use that.
*/
if( callerPrincipal == null && info.principal == null )
{
Set subjectPrincipals = subject.getPrincipals(Principal.class);
iter = subjectPrincipals.iterator();
while( iter.hasNext() )
{
Principal p = (Principal) iter.next();
if( (p instanceof Group) == false )
info.principal = p;
}
}
synchronized(authCache) {
authCache.put(id,info);
}
}
private void removeId(String id) {
synchronized(authCache) {
authCache.remove(id);
}
}
private String generateId(Subject subject) throws JMSException {
try {
return idGenerator.nextSessionId();
}catch(Exception ex) {
log.error("Could not generate a secure sessionID", ex);
//Dont show client the real reason
throw new JMSSecurityException("Could not generate a secure sessionID");
}
}
} // SecurityManager
1.1 jbossmq/src/main/org/jboss/mq/security/SecurityManagerMBean.java
Index: SecurityManagerMBean.java
===================================================================
/*
* JBoss, the OpenSource EJB server
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.mq.security;
import javax.management.ObjectName;
import org.jboss.util.jmx.ObjectNameFactory;
import org.jboss.system.ServiceMBean;
import org.jboss.mq.server.JMSServerInvoker;
/**
* MBean interface for security manager.
*
* @author <a href="[EMAIL PROTECTED]">Peter Antman</a>
* @version $Revision: 1.1 $
*/
public interface SecurityManagerMBean extends ServiceMBean
{
ObjectName OBJECT_NAME =
ObjectNameFactory.create("jboss.mq:service=SecurityManager");
JMSServerInvoker getInvoker();
// REMOVE
String printAuthCache();
public void addDestination(String jndi, String conf) throws Exception;
public void addDestination(String jndi, org.w3c.dom.Element conf) throws
Exception;
public void removeDestination(String jndi) throws Exception;
} // SecurityManagerMBean
1.1 jbossmq/src/main/org/jboss/mq/security/SecurityMetadata.java
Index: SecurityMetadata.java
===================================================================
/*
* JBoss, the OpenSource J2EE webOS
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.mq.security;
import java.util.Set;
import java.util.HashSet;
import java.util.HashMap;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Attr;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.jboss.security.SimplePrincipal;
import org.jboss.logging.Logger;
/**
* SecurityMetadata.java
*
*
* Created: Tue Feb 26 15:02:29 2002
*
* @author Peter
* @version
*/
public class SecurityMetadata {
static Role DEFAULT_ROLE = new Role("guest", true, true, false);
static class Role {
String name;
boolean read= false;
boolean write = false;
boolean create = false;
public Role(String name, boolean read, boolean write, boolean create) {
this.name = name;
this.read = read;
this.write = write;
this.create = create;
}
public String toString() {
return "Role
{name="+name+";read="+read+";write="+write+";create="+create+"}";
}
}
HashMap roles = new HashMap();
HashSet read = new HashSet();
HashSet write = new HashSet();
HashSet create = new HashSet();
Logger log = Logger.getLogger(SecurityMetadata.class);
public SecurityMetadata() {
addRole(DEFAULT_ROLE);
}
/**
* Create with given xml @see configure.
*
* If the configure script is null, a default role named guest will be
* created with read and write access, but no create access.
*/
public SecurityMetadata(String conf)throws Exception {
configure(conf);
}
public SecurityMetadata(Element conf)throws Exception {
configure(conf);
}
/**
* Configure with an xml string.
*
* The format of the string is:
* <security>
* <role name="nameOfRole" read="true" write="true" create="false"/>
* </security>
*
* There may be one or more role elements.
*/
public void configure(String conf) throws Exception {
Element sec = null;
if (conf != null) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse(new InputSource(new StringReader(conf)));
sec = doc.getDocumentElement();
}
configure(sec);
}
public void configure(Element sec) throws Exception {
if (sec == null) {
addRole(DEFAULT_ROLE);
}else {
if (!sec.getTagName().equals("security"))
throw new SAXException("Configuration document not valid: root element
must be security, not " + sec.getTagName());
// Parse
NodeList list = sec.getElementsByTagName("role");
int l = list.getLength();
for(int i = 0; i<l;i++) {
Element role = (Element)list.item(i);
Attr na = role.getAttributeNode("name");
if (na == null)
throw new SAXException("There must exist a name attribute of role");
String n = na.getValue();
boolean r = role.getAttributeNode("read") != null ? Boolean.valueOf(
role.getAttributeNode("read").getValue() ).booleanValue() : false;
boolean w = role.getAttributeNode("write") != null ? Boolean.valueOf(
role.getAttributeNode("write").getValue() ).booleanValue() : false;
boolean c = role.getAttributeNode("create") != null ? Boolean.valueOf(
role.getAttributeNode("create").getValue() ).booleanValue() : false;
addRole(n,r,w,c);
}
}
}
public void addRole(String name, boolean read, boolean write, boolean create) {
Role r = new Role(name,read,write,create);
addRole(r);
}
public void addRole(Role r) {
if (log.isTraceEnabled())
log.trace("Adding role: " + r.toString());
roles.put(r.name,r);
SimplePrincipal p = new SimplePrincipal(r.name);
if(r.read == true)
read.add(p);
if(r.write == true)
write.add(p);
if (r.create == true)
create.add(p);
}
public Set getReadPrincipals() {
return read;
}
public Set getWritePrincipals() {
return write;
}
public Set getCreatePrincipals() {
return create;
}
} // SecurityMetadata
1.1
jbossmq/src/main/org/jboss/mq/security/ServerSecurityInvoker.java
Index: ServerSecurityInvoker.java
===================================================================
/*
* JBoss, the OpenSource EJB server
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.mq.security;
import java.util.Set;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.JMSSecurityException;
import javax.jms.InvalidDestinationException;
import org.jboss.mq.ConnectionToken;
import org.jboss.mq.SpyMessage;
import org.jboss.mq.SpyDestination;
import org.jboss.mq.SpyTopic;
import org.jboss.mq.DurableSubscriptionID;
import org.jboss.mq.Subscription;
import org.jboss.mq.server.JMSServerInvokerSupport;
/**
* ServerSecurityInvoker.java
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Antman</a>
* @version $Revision: 1.1 $
*/
public class ServerSecurityInvoker extends JMSServerInvokerSupport
{
SecurityManager manager;
public ServerSecurityInvoker(SecurityManager manager) {
super();
this.manager = manager;
}
public String authenticate(String name, String password) throws JMSException {
log.trace("Autenticating user " +name +"/"+password);
return manager.authenticate(name,password);
}
/**
* Close connection. Logout user after connection is closed.
*
* @param dc Description of Parameter
* @exception JMSException Description of Exception
*/
public void connectionClosing(ConnectionToken dc)
throws JMSException {
super.connectionClosing(dc);
manager.logout(dc);
}
/*
Here is a number of methods that I do no know if we should check access on.
By the way, how do we check access on temporary destinations??????
getTemporaryTopic()
getTemporaryQueue()
deleteTemporaryDestination()
createQueue()
createTopic()
unsubscribe() - probably not.
*/
//
// Read methods, to check access on
//
public SpyMessage[] browse(ConnectionToken dc, Destination dest, String selector)
throws JMSException {
if (log.isTraceEnabled())
log.trace( "Checking browse authorize on " +dc + " dest=" +dest);
if (!authorizeRead(dc, ((SpyDestination)dest).getName()) )
throw new JMSSecurityException("Connection not autorized to browse to
destination: " + dest);
return super.browse(dc,dest,selector);
}
// FIXME This might actually be unneeded since a subscribe is
// allways done first.
// fuck.
// If we remove it, remember to remove the getSubscription method
public SpyMessage receive(ConnectionToken dc, int subscriberId, long wait)
throws JMSException {
if (log.isTraceEnabled())
log.trace( "Checking receive authorize on " +dc + " subId="+subscriberId);
// Another nightmare, how the fck do we get the dest name.
Subscription sub = super.getSubscription(dc,subscriberId);
String destName = sub.destination.getName();
if (!authorizeRead(dc, destName) )
throw new JMSSecurityException("Connection not autorized to receive from
destination: " + destName);
return super.receive(dc,subscriberId,wait);
}
// The price we pay for adding this to an implementation not done
// for acl's. The method to create a durable susbcriber is this, but
// with a durableSubscriptionID in the destination of the subscription.
// For all but, durable subscriptions this is a read access thingy.
// Even more: if this is a create of a durable sub, or a change of one
// or just usage of an existing one, that does basically only JMSTopic (it's new
or has changed) and StateManager (its allowed) know of.
// The logic has to be this, to not get into trouble: for ALL usage
// of a durable sub create access is demanded!
//
public void subscribe(org.jboss.mq.ConnectionToken dc, org.jboss.mq.Subscription
sub)
throws JMSException {
if (log.isTraceEnabled())
log.trace( "Checking subscribe authorize on " + dc +" sub="+sub);
// Do some sanity checks
if (sub == null)
throw new JMSException("The subscription is not allowed to be null");
else if (sub.destination == null)
throw new InvalidDestinationException ("Destination is not allowed to be
null");
// Check if its a durable sub/ this might actually not be true create
// only access to an old one. But we only allow read from durable
// if you actually have the rights to create one, or...does this make
// preconfigured clientID meaningless.
SpyDestination dest = sub.destination;
String destName = dest.getName();
if (dest instanceof SpyTopic) {
// Check durable sub
DurableSubscriptionID id = ((SpyTopic)dest).
getDurableSubscriptionID();
if (id != null) {
// Durable sub, check create access.
if (!authorizeCreate(dc, destName))
throw new JMSSecurityException("Connection not authorized to do
durabe subscription on topic: " + destName);
}
}
// We ALLWAYS check read access, even for durables
if(!authorizeRead(dc,destName))
throw new JMSSecurityException("Connection not authorized to subscribe to
destination: " + destName);
super.subscribe(dc,sub);
}
//
// Write methods, to check access on
//
public void addMessage(ConnectionToken dc, SpyMessage message)
throws JMSException {
String dest = ((SpyDestination)message.getJMSDestination()).getName();
if (!authorizeWrite(dc, dest))
throw new JMSSecurityException("Connection not autorized to addMessages to
destination: " + dest);
super.addMessage(dc,message);
}
//
// Create methods, to check access on
//
public void destroySubscription(ConnectionToken dc,DurableSubscriptionID id)
throws JMSException {
// Oh, this fucker is a nightmare. How do we get wich topic the
// connection is trying to unsubscribe from
SpyTopic t = super.getDurableTopic(id);
if (t == null)
throw new InvalidDestinationException("No durable topic found for
subscription " + id.getSubscriptionName());
if (!authorizeCreate(dc,t.getName()))
throw new JMSSecurityException("Connection not autorized to unsubscribe
from subscription: " + t.getName());
super.destroySubscription(dc,id);
}
//
// Security helper methods
//
public boolean authorizeRead(ConnectionToken dc,String destination) throws
JMSException{
// First we must get access to the destinations security meta data
SecurityMetadata m = manager.getSecurityMetadata(destination);
if (m == null) {
log.warn("No security configuration avaliable for " + destination);
return false;//FIXME, is this OK?
}
Set readPrincipals = m.getReadPrincipals();
if (manager.authorize(dc,readPrincipals))
return true;
else
return false;
}
public boolean authorizeWrite(ConnectionToken dc,String destination) throws
JMSException{
// First we must get access to the destinations security meta data
SecurityMetadata m = manager.getSecurityMetadata(destination);
if (m == null) {
log.warn("No security configuration avaliable for " + destination);
return false;//FIXME, is this OK?
}
Set writePrincipals = m.getWritePrincipals();
if (manager.authorize(dc,writePrincipals))
return true;
else
return false;
}
public boolean authorizeCreate(ConnectionToken dc,String destination) throws
JMSException{
// First we must get access to the destinations security meta data
SecurityMetadata m = manager.getSecurityMetadata(destination);
if (m == null) {
log.warn("No security configuration avaliable for " + destination);
return false;//FIXME, is this OK?
}
Set createPrincipals = m.getCreatePrincipals();
if (manager.authorize(dc,createPrincipals))
return true;
else
return false;
}
} // ServerSecurityInvoker
1.1 jbossmq/src/main/org/jboss/mq/security/SessionIDGenerator.java
Index: SessionIDGenerator.java
===================================================================
/*
* JBoss, the OpenSource EJB server
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.mq.security;
import java.util.Random;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Generator of session id for ConnecttionToken.
*
* There should be nonguessabe and none repeting as long as the server is
* alive.
*
* This could by all mean be made much more secure!
*
* @author <a href="[EMAIL PROTECTED]">Peter Antman</a>
* @author <a href="[EMAIL PROTECTED]">Hiram Chirino</a>
* @version $Revision: 1.1 $
*/
public class SessionIDGenerator {
int id = 0;
public SessionIDGenerator() {
}
public String nextSessionId() throws NoSuchAlgorithmException {
int myid = -1;
synchronized(this) {
myid=id;
id++;
}
String key = randString();
String data = randString();
MessageDigest
md5=java.security.MessageDigest.getInstance("MD5");
md5.update(String.valueOf(myid).getBytes());
md5.update(data.getBytes());
md5.update(data.getBytes());
byte[] byteHash = md5.digest(key.getBytes());
return byteArrayToHexString(byteHash);
}
String randString() {
Random r = new Random( System.currentTimeMillis());
return ""+r.nextLong();
}
private final String byteArrayToHexString(byte[] byteArray)
{
String res = "";
for (int i = 0; i < byteArray.length; i++) {
int x = byteArray[i];
if (x < 0)
x += 256;
String xs = Integer.toHexString(x);
while (xs.length() < 2)
xs = "0" + xs;
res += xs;
}
return res;
}
public static void main(String[] args) throws Exception{
int rounds = 1000;
if (args.length == 1)
rounds = Integer.parseInt(args[0]);
SessionIDGenerator gen = new SessionIDGenerator();
for (int i =0;i<rounds;i++) {
System.out.println(gen.nextSessionId());
}
}
} // SessionIDGenerator
_______________________________________________
Jboss-development mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/jboss-development