[jboss-cvs] JBossAS SVN: r71734 - in projects/security/security-jboss-sx/trunk/jbosssx: src/main/org/jboss and 3 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Fri Apr 4 16:56:38 EDT 2008


Author: sguilhen at redhat.com
Date: 2008-04-04 16:56:38 -0400 (Fri, 04 Apr 2008)
New Revision: 71734

Added:
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/AbstractPasswordCredentialLoginModule.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/CallerIdentityLoginModule.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/ConfiguredIdentityLoginModule.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/GetPrincipalInfoAction.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/PBEIdentityLoginModule.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SecureIdentityLoginModule.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SubjectActions.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/Util.java
Modified:
   projects/security/security-jboss-sx/trunk/jbosssx/pom.xml
Log:
JBAS-5362: Imported the security classes from the connector project.



Modified: projects/security/security-jboss-sx/trunk/jbosssx/pom.xml
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/pom.xml	2008-04-04 20:49:02 UTC (rev 71733)
+++ projects/security/security-jboss-sx/trunk/jbosssx/pom.xml	2008-04-04 20:56:38 UTC (rev 71734)
@@ -151,6 +151,18 @@
          <scope>compile</scope>
       </dependency>
       <dependency>
+         <groupId>org.jboss.javaee</groupId>
+         <artifactId>jboss-javaee</artifactId>
+         <version>5.0.0.Beta3</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>jboss</groupId>
+         <artifactId>jboss-jmx</artifactId>
+         <version>4.2.1.GA</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
          <groupId>sun-xacml</groupId>
          <artifactId>sun-xacml</artifactId>
          <version>2.0</version>

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/AbstractPasswordCredentialLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/AbstractPasswordCredentialLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/AbstractPasswordCredentialLoginModule.java	2008-04-04 20:56:38 UTC (rev 71734)
@@ -0,0 +1,156 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, 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.resource.security;
+
+import java.util.Map;
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+import javax.resource.spi.ManagedConnectionFactory;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.logging.Logger;
+import org.jboss.mx.util.MBeanServerLocator;
+import org.jboss.security.auth.spi.AbstractServerLoginModule;
+
+
+/** A base login module that provides access to the ManagedConnectionFactory
+ * needed by the PasswordCredential.
+ * 
+ * @see javax.resource.spi.security.PasswordCredential
+ *
+ * @author <a href="mailto:d_jencks at users.sourceforge.net">David Jencks</a>
+ * @author Scott.Stark at jboss.org
+ * @version $Revision: 71545 $
+ */
+public abstract class AbstractPasswordCredentialLoginModule
+   extends AbstractServerLoginModule
+{
+   private static final Logger log = Logger.getLogger(AbstractPasswordCredentialLoginModule.class);
+   private MBeanServer server;
+   private ObjectName managedConnectionFactoryName;
+   private ManagedConnectionFactory mcf;
+   /** A flag that allows a missing MCF service to be ignored */
+   private Boolean ignoreMissigingMCF;
+
+   public AbstractPasswordCredentialLoginModule()
+   {
+      
+   }
+
+   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+      String name = (String) options.get("managedConnectionFactoryName");
+      try
+      {
+         managedConnectionFactoryName = new ObjectName(name);
+      }
+      catch (MalformedObjectNameException mone)
+      {
+         throw new IllegalArgumentException("Malformed ObjectName: " + name);
+      }
+
+      if (managedConnectionFactoryName == null)
+      {
+         throw new IllegalArgumentException("Must supply a managedConnectionFactoryName!");
+      }
+      Object flag = options.get("ignoreMissigingMCF");
+      if( flag instanceof Boolean )
+         ignoreMissigingMCF = (Boolean) flag;
+      else if( flag != null )
+         ignoreMissigingMCF = Boolean.valueOf(flag.toString());
+      server = MBeanServerLocator.locateJBoss();
+      getMcf();
+   }
+
+   /** Return false if there is no mcf, else return super.login(). Override
+    * to provide custom authentication.
+    * 
+    * @return false if there is no mcf, else return super.login().
+    * @exception LoginException if an error occurs
+    */
+   public boolean login() throws LoginException
+   {
+      if (mcf == null)
+      {
+         return false;
+      }
+      return super.login();
+   }
+
+   public boolean logout() throws LoginException
+   {
+      removeCredentials();
+      return super.logout();
+   }
+
+   protected ManagedConnectionFactory getMcf()
+   {
+      if (mcf == null)
+      {
+         try
+         {
+            mcf = (ManagedConnectionFactory) server.getAttribute(
+               managedConnectionFactoryName,
+               "ManagedConnectionFactory");
+         }
+         catch (Exception e)
+         {
+            log.error("The ConnectionManager mbean: " + managedConnectionFactoryName
+               + " specified in a ConfiguredIdentityLoginModule could not be found."
+               + " ConnectionFactory will be unusable!");
+            if( Boolean.TRUE != ignoreMissigingMCF )
+            {
+               throw new IllegalArgumentException("Managed Connection Factory not found: "
+                  + managedConnectionFactoryName);
+            }
+         } // end of try-catch
+         if (log.isTraceEnabled())
+         {
+            log.trace("mcfname: " + managedConnectionFactoryName);
+         }
+      } // end of if ()
+
+      return mcf;
+   }
+
+   protected MBeanServer getServer()
+   {
+      return server;
+   }
+
+   /** This removes the javax.security.auth.login.name and
+    * javax.security.auth.login.password settings from the sharteState map
+    * along with any PasswordCredential found in the PrivateCredentials set
+    */
+   protected void removeCredentials()
+   {
+      sharedState.remove("javax.security.auth.login.name");
+      sharedState.remove("javax.security.auth.login.password");
+      SubjectActions.removeCredentials(subject, mcf);
+   }
+
+}
+

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/CallerIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/CallerIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/CallerIdentityLoginModule.java	2008-04-04 20:56:38 UTC (rev 71734)
@@ -0,0 +1,213 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, 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.resource.security;
+
+import java.security.acl.Group;
+import java.security.Principal;
+import java.util.Map;
+import java.util.Set;
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.RunAsIdentity;
+import org.jboss.logging.Logger;
+
+/**
+ * A simple login module that simply associates the principal making the
+ * connection request with the actual EIS connection requirements.
+ *
+ * The type of Principal class used is
+ * <code>org.jboss.security.SimplePrincipal.</code>
+ * <p>
+ *
+ * @see org.jboss.resource.security.ConfiguredIdentityLoginModule
+ *
+ * @author Scott.Stark at jboss.org
+ * @author <a href="mailto:d_jencks at users.sourceforge.net">David Jencks</a>
+ * @author <a href="mailto:dan.bunker at pbs.proquest.com">Dan Bunker</a>
+ * @version $Revision: 71545 $
+ */
+public class CallerIdentityLoginModule
+   extends AbstractPasswordCredentialLoginModule
+{
+   /**
+    * Class logger
+    */
+   private static final Logger log = Logger.getLogger(CallerIdentityLoginModule.class);
+
+   /**
+    * The default username/principal to use for basic connections
+    */
+   private String userName;
+
+   /**
+    * The default password to use for basic connections
+    */
+   private char[] password;
+   /** A flag indicating if the run-as principal roles should be added to the subject */
+   private boolean addRunAsRoles;
+   private Set runAsRoles;
+
+   /**
+    * Default Constructor
+    */
+   public CallerIdentityLoginModule()
+   {
+   }
+
+   /**
+    * The initialize method sets up some default connection information for
+    * basic connections.  This is useful for container initialization connection
+    * use or running the application in a non-secure manner.  This method is
+    * called before the login method.
+    *
+    * @param subject
+    * @param handler
+    * @param sharedState
+    * @param options
+    */
+   public void initialize(Subject subject, CallbackHandler handler,
+      Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+
+      userName = (String) options.get("userName");
+      if (userName == null)
+      {
+         log.debug("No default username supplied.");
+      }
+
+      String pass = (String) options.get("password");
+      if (pass == null)
+      {
+         log.debug("No default password supplied.");
+      }
+      else
+      {
+         password = pass.toCharArray();
+      }
+
+      // Check the addRunAsRoles
+      String flag = (String) options.get("addRunAsRoles");
+      addRunAsRoles = Boolean.valueOf(flag).booleanValue();
+
+      log.debug("got default principal: " + userName + ", username: "
+         + userName + ", password: " + (password == null ? "null" : "****")
+         + " addRunAsRoles: "+addRunAsRoles);
+
+   }
+
+   /**
+    * Performs the login association between the caller and the resource for a
+    * 1 to 1 mapping.  This acts as a login propagation strategy and is useful
+    * for single-sign on requirements
+    *
+    * @return True if authentication succeeds
+    * @throws LoginException
+    */
+   public boolean login() throws LoginException
+   {
+      log.trace("Caller Association login called");
+
+      //setup to use the default connection info.  This will be overiden if security
+      //associations are found
+      String username = userName;
+
+      //ask the security association class for the principal info making this request
+      try
+      {
+         Principal user = GetPrincipalInfoAction.getPrincipal();
+         char[] userPassword = GetPrincipalInfoAction.getCredential();
+
+         if( userPassword != null )
+         {
+            password = userPassword;
+         }
+
+         if (user != null)
+         {
+            username = user.getName();
+            if (log.isTraceEnabled())
+            {
+               log.trace("Current Calling principal is: " + username
+                  + " ThreadName: " + Thread.currentThread().getName());
+            }
+            // Check for a RunAsIdentity
+            RunAsIdentity runAs = GetPrincipalInfoAction.peekRunAsIdentity();
+            if( runAs != null )
+            {
+               runAsRoles = runAs.getRunAsRoles();
+            }
+         }
+      }
+      catch (Throwable e)
+      {
+         throw new LoginException("Unable to get the calling principal or its credentials for resource association");
+      }
+
+      // Update userName so that getIdentity is consistent
+      userName = username;
+      if (super.login() == true)
+      {
+         return true;
+      }
+
+      // Put the principal name into the sharedState map
+      sharedState.put("javax.security.auth.login.name", username);
+      super.loginOk = true;
+
+      return true;
+   }
+
+   public boolean commit() throws LoginException
+   {
+      // Put the principal name into the sharedState map
+      sharedState.put("javax.security.auth.login.name", userName);
+      // Add any run-as roles if addRunAsRoles is true
+      if( addRunAsRoles && runAsRoles != null )
+      {
+         SubjectActions.addRoles(subject, runAsRoles);         
+      }
+
+      // Add the PasswordCredential
+      PasswordCredential cred = new PasswordCredential(userName, password);
+      cred.setManagedConnectionFactory(getMcf());
+      SubjectActions.addCredentials(subject, cred);
+      return super.commit();
+   }
+
+   protected Principal getIdentity()
+   {
+      log.trace("getIdentity called");
+      Principal principal = new SimplePrincipal(userName);
+      return principal;
+   }
+
+   protected Group[] getRoleSets() throws LoginException
+   {
+      log.trace("getRoleSets called");
+      return new Group[]{};
+   }
+}

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/ConfiguredIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/ConfiguredIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/ConfiguredIdentityLoginModule.java	2008-04-04 20:56:38 UTC (rev 71734)
@@ -0,0 +1,122 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, 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.resource.security;
+
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Map;
+
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SimplePrincipal;
+
+/**
+ * A simple login module that simply associates the principal specified
+ * in the module options with any subject authenticated against the module.
+ * The type of Principal class used is
+ * <code>org.jboss.security.SimplePrincipal.</code>
+ * <p>
+ * If no principal option is specified a principal with the name of 'guest'
+ * is used.
+ *
+ * @see org.jboss.security.SimpleGroup
+ * @see org.jboss.security.SimplePrincipal
+ *
+ * @author Scott.Stark at jboss.org
+ * @author <a href="mailto:d_jencks at users.sourceforge.net">David Jencks</a>
+ * @version $Revision: 71545 $
+ */
+public class ConfiguredIdentityLoginModule extends AbstractPasswordCredentialLoginModule
+{
+   private String principalName;
+   private String userName;
+   private String password;
+
+   private static final Logger log = Logger.getLogger(ConfiguredIdentityLoginModule.class);
+
+
+   public ConfiguredIdentityLoginModule()
+   {
+   }
+
+   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+      principalName = (String) options.get("principal");
+      if( principalName == null )
+      {
+         throw new IllegalArgumentException("Must supply a principal name!");
+      }
+      userName = (String) options.get("userName");
+      if( userName == null )
+      {
+         throw new IllegalArgumentException("Must supply a user name!");
+      }
+      password = (String) options.get("password");
+      if( password == null )
+      {
+         log.warn("Creating LoginModule with no configured password!");
+         password = "";
+      }
+      log.trace("got principal: " + principalName + ", username: " + userName + ", password: " + password);
+
+   }
+
+   public boolean login() throws LoginException
+   {
+      log.trace("login called");
+      if( super.login() == true )
+         return true;
+
+      Principal principal = new SimplePrincipal(principalName);
+      SubjectActions.addPrincipals(subject, principal);
+      // Put the principal name into the sharedState map
+      sharedState.put("javax.security.auth.login.name", principalName);
+      PasswordCredential cred = new PasswordCredential(userName, password.toCharArray());
+      cred.setManagedConnectionFactory(getMcf());
+      SubjectActions.addCredentials(subject, cred);
+      super.loginOk = true;
+      return true;
+   }
+
+   protected Principal getIdentity()
+   {
+      log.trace("getIdentity called");
+      Principal principal = new SimplePrincipal(principalName);
+      return principal;
+   }
+
+   /** This method simply returns an empty array of Groups which means that
+   no role based permissions are assigned.
+   */
+   protected Group[] getRoleSets() throws LoginException
+   {
+      log.trace("getRoleSets called");
+      return new Group[] {};
+   }
+   
+}

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/GetPrincipalInfoAction.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/GetPrincipalInfoAction.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/GetPrincipalInfoAction.java	2008-04-04 20:56:38 UTC (rev 71734)
@@ -0,0 +1,175 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, 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.resource.security;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.Principal;
+import java.io.UnsupportedEncodingException;
+
+import org.jboss.security.SecurityAssociation;
+import org.jboss.security.RunAsIdentity;
+
+/** PrivilegedActions used by this package
+ * 
+ * @author Scott.Stark at jboss.org
+ * @version $Revision: 71545 $
+ */
+class GetPrincipalInfoAction
+{
+   /* Obtain the password credential by trying char[], byte[],
+    and toString()
+    */
+   private static char[] getPassword()
+   {
+      Object credential = SecurityAssociation.getCredential();
+      char[] password = null;
+       if( credential instanceof char[] )
+       {
+          password = (char[]) credential;
+       }
+       else if( credential instanceof byte[] )
+       {
+          try
+          {
+             String tmp = new String((byte[]) credential, "UTF-8");
+             password = tmp.toCharArray();
+          }
+          catch (UnsupportedEncodingException e)
+          {
+             throw new SecurityException(e.getMessage());
+          }
+       }
+       else if( credential != null )
+       {
+          String tmp = credential.toString();
+          password = tmp.toCharArray();
+       }
+      return password;
+   }
+
+   interface PrincipalActions
+   {
+      PrincipalActions PRIVILEGED = new PrincipalActions()
+      {
+         private final PrivilegedAction peekAction = new PrivilegedAction()
+         {
+            public Object run()
+            {
+               return SecurityAssociation.peekRunAsIdentity();
+            }
+         };
+
+         private final PrivilegedAction getPrincipalAction = new PrivilegedAction()
+         {
+            public Object run()
+            {
+               return SecurityAssociation.getPrincipal();
+            }
+         };
+
+         private final PrivilegedAction getCredentialAction = new PrivilegedAction()
+         {
+            public Object run()
+            {
+               return getPassword();
+            }
+         };
+
+         public RunAsIdentity peek()
+         {
+            return (RunAsIdentity)AccessController.doPrivileged(peekAction);
+         }
+
+         public Principal getPrincipal()
+         {
+            return (Principal)AccessController.doPrivileged(getPrincipalAction);
+         }
+
+         public char[] getCredential()
+         {
+            return (char[]) AccessController.doPrivileged(getCredentialAction);
+         }
+      };
+
+      PrincipalActions NON_PRIVILEGED = new PrincipalActions()
+      {
+         public RunAsIdentity peek()
+         {
+            return SecurityAssociation.peekRunAsIdentity();
+         }
+
+         public Principal getPrincipal()
+         {
+            return SecurityAssociation.getPrincipal();
+         }
+
+         public char[] getCredential()
+         {
+            return getPassword();
+         }
+      };
+
+      Principal getPrincipal();
+      char[] getCredential();
+      RunAsIdentity peek();
+   }
+
+   static Principal getPrincipal()
+   {
+      Principal principal;
+      if(System.getSecurityManager() == null)
+      {
+         principal = PrincipalActions.NON_PRIVILEGED.getPrincipal();
+      }
+      else
+      {
+         principal = PrincipalActions.PRIVILEGED.getPrincipal();
+      }
+      return principal;
+   }
+   static char[] getCredential()
+   {
+      char[] credential;
+      if(System.getSecurityManager() == null)
+      {
+         credential = PrincipalActions.NON_PRIVILEGED.getCredential();
+      }
+      else
+      {
+         credential = PrincipalActions.PRIVILEGED.getCredential();
+      }
+      return credential;
+   }
+   static RunAsIdentity peekRunAsIdentity()
+   {
+      if(System.getSecurityManager() == null)
+      {
+         return PrincipalActions.NON_PRIVILEGED.peek();
+      }
+      else
+      {
+         return PrincipalActions.PRIVILEGED.peek();
+      }
+   }
+
+}


Property changes on: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/GetPrincipalInfoAction.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java	2008-04-04 20:56:38 UTC (rev 71734)
@@ -0,0 +1,224 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, 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.resource.security;
+
+import java.security.acl.Group;
+import java.security.Principal;
+import java.security.PrivilegedExceptionAction;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.util.Map;
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+import javax.management.ObjectName;
+import javax.management.MBeanServer;
+
+import org.jboss.security.SimplePrincipal;
+import org.jboss.logging.Logger;
+
+/** A login module for statically defining a data source username and password
+ that uses a password that has been ecrypted by a JaasSecurityDomain. The
+ base64 format of the data source password may be generated using the PBEUtils
+ command:
+ 
+ java -cp jbosssx.jar org.jboss.security.plugins.PBEUtils salt count
+   domain-password data-source-password
+
+ salt : the Salt attribute from the JaasSecurityDomain
+ count : the IterationCount attribute from the JaasSecurityDomain
+ domain-password : the plaintext password that maps to the KeyStorePass
+   attribute from the JaasSecurityDomain
+ data-source-password : the plaintext password for the data source that
+   should be encrypted with the JaasSecurityDomain password
+
+ for example:
+
+ java -cp jbosssx.jar org.jboss.security.plugins.PBEUtils abcdefgh 13 master ''
+ Encoded password: E5gtGMKcXPP
+
+ A sample login-config.xml configuration entry would be:
+ 
+ <application-policy name = "EncryptedHsqlDbRealm">
+    <authentication>
+       <login-module code = "org.jboss.resource.security.JaasSecurityDomainIdentityLoginModule"
+       flag = "required">
+          <module-option name = "userName">sa</module-option>
+          <module-option name = "password">E5gtGMKcXPP</module-option>
+          <module-option name = "managedConnectionFactoryName">jboss.jca:service=LocalTxCM,name=DefaultDS</module-option>
+          <module-option name = "jaasSecurityDomain">jboss.security:service=JaasSecurityDomain,domain=ServerMasterPassword</module-option>
+       </login-module>
+    </authentication>
+ </application-policy>
+
+
+ @author Scott.Stark at jboss.org
+ @author <a href="mailto:noel.rocher at jboss.org">Noel Rocher</a> 29, june 2004 username & userName issue
+ @version $Revision: 71545 $
+ */
+public class JaasSecurityDomainIdentityLoginModule
+   extends AbstractPasswordCredentialLoginModule
+{
+   private static final Logger log = Logger.getLogger(JaasSecurityDomainIdentityLoginModule.class);
+
+   private String username;
+   private String password;
+   private ObjectName jaasSecurityDomain;
+
+   public void initialize(Subject subject, CallbackHandler handler,
+      Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+      // NR : we keep this username for compatibility
+      username = (String) options.get("username");
+      if( username == null )
+      {
+      	// NR : try with userName
+        username = (String) options.get("userName");      	
+        if( username == null )
+        {
+         throw new IllegalArgumentException("The user name is a required option");
+        }
+     }
+
+      password = (String) options.get("password");
+      if( password == null )
+      {
+         throw new IllegalArgumentException("The password is a required option");
+      }
+
+      String name = (String) options.get("jaasSecurityDomain");
+      if( name == null )
+      {
+         throw new IllegalArgumentException("The jaasSecurityDomain is a required option");
+      }
+
+      try
+      {
+         jaasSecurityDomain = new ObjectName(name);
+      }
+      catch(Exception e)
+      {
+         throw new IllegalArgumentException("Invalid jaasSecurityDomain: " + e.getMessage());
+      }
+   }
+
+   public boolean login() throws LoginException
+   {
+      log.trace("login called");
+      if( super.login() == true )
+         return true;
+
+      super.loginOk = true;
+      return true;
+   }
+
+   public boolean commit() throws LoginException
+   {
+      Principal principal = new SimplePrincipal(username);
+      SubjectActions.addPrincipals(subject, principal);
+      sharedState.put("javax.security.auth.login.name", username);
+      // Decode the encrypted password
+      try
+      {
+         char[] decodedPassword = DecodeAction.decode(password,
+            jaasSecurityDomain, getServer());
+         PasswordCredential cred = new PasswordCredential(username, decodedPassword);
+         cred.setManagedConnectionFactory(getMcf());
+         SubjectActions.addCredentials(subject, cred);
+      }
+      catch(Exception e)
+      {
+         log.debug("Failed to decode password", e);
+         throw new LoginException("Failed to decode password: " + e.getMessage());
+      }
+      return true;
+   }
+
+   public boolean abort()
+   {
+      username = null;
+      password = null;
+      return true;
+   }
+
+   protected Principal getIdentity()
+   {
+      log.trace("getIdentity called, username=" + username);
+      Principal principal = new SimplePrincipal(username);
+      return principal;
+   }
+
+   protected Group[] getRoleSets() throws LoginException
+   {
+      Group[] empty = new Group[0];
+      return empty;
+   }
+
+   private static class DecodeAction implements PrivilegedExceptionAction
+   {
+      String password;
+      ObjectName jaasSecurityDomain;
+      MBeanServer server;
+      
+      DecodeAction(String password, ObjectName jaasSecurityDomain,
+         MBeanServer server)
+      {
+         this.password = password;
+         this.jaasSecurityDomain = jaasSecurityDomain;
+         this.server = server;
+      }
+
+      /**
+       * 
+       * @return
+       * @throws Exception
+       */ 
+      public Object run() throws Exception
+      {
+         // Invoke the jaasSecurityDomain.decodeb64 op
+         Object[] args = {password};
+         String[] sig = {String.class.getName()};
+         byte[] secret = (byte[]) server.invoke(jaasSecurityDomain,
+            "decode64", args, sig);
+         // Convert to UTF-8 base char array
+         String secretPassword = new String(secret, "UTF-8");
+         return secretPassword.toCharArray();
+      }
+      static char[] decode(String password, ObjectName jaasSecurityDomain,
+         MBeanServer server)
+         throws Exception
+      {
+         DecodeAction action = new DecodeAction(password, jaasSecurityDomain, server);
+         try
+         {
+            char[] decode = (char[]) AccessController.doPrivileged(action);
+            return decode;
+         }
+         catch(PrivilegedActionException e)
+         {
+            throw e.getException();
+         }
+      }
+   }
+}


Property changes on: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/PBEIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/PBEIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/PBEIdentityLoginModule.java	2008-04-04 20:56:38 UTC (rev 71734)
@@ -0,0 +1,270 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, 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.resource.security;
+
+import java.security.acl.Group;
+import java.security.Principal;
+import java.util.Map;
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.PBEParameterSpec;
+
+import org.jboss.security.Base64Utils;
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.Util;
+import org.jboss.logging.Logger;
+
+/** An example of how one could encrypt the database password for a jca
+  connection factory. The corresponding login config entry illustrates
+  the usage:
+ 
+   <application-policy name = "testPBEIdentityLoginModule">
+      <authentication>
+         <login-module code = "org.jboss.resource.security.PBEIdentityLoginModule"
+            flag = "required">
+            <module-option name = "principal">sa</module-option>
+            <module-option name = "userName">sa</module-option>
+            <!--
+            output from:
+               org.jboss.resource.security.PBEIdentityLoginModule
+               thesecret testPBEIdentityLoginModule abcdefgh 19 PBEWithMD5AndDES 
+            -->
+            <module-option name = "password">3fp7R/7TMjyTTxhmePdJVk</module-option>
+            <module-option name = "ignoreMissigingMCF">true</module-option>
+            <module-option name = "pbealgo">PBEWithMD5AndDES</module-option>
+            <module-option name = "pbepass">testPBEIdentityLoginModule</module-option>
+            <module-option name = "salt">abcdefgh</module-option>
+            <module-option name = "iterationCount">19</module-option>
+            <module-option name = "managedConnectionFactoryName">jboss.jca:service=LocalTxCM,name=DefaultDS</module-option>
+         </login-module>
+      </authentication>
+   </application-policy>
+
+ This uses password based encryption (PBE) with algorithm parameters dervived
+ from pbealgo, pbepass, salt, iterationCount options:
+ + pbealgo - the PBE algorithm to use. Defaults to PBEwithMD5andDES.
+ + pbepass - the PBE password to use. Can use the JaasSecurityDomain {CLASS}
+ and {EXT} syntax to obtain the password from outside of the configuration.
+ Defaults to "jaas is the way".
+ + salt - the PBE salt as a string. Defaults to {1, 7, 2, 9, 3, 11, 4, 13}.
+ + iterationCount - the PBE iterationCount. Defaults to 37.
+
+ * @author Scott.Stark at jboss.org
+ * @author <a href="mailto:noel.rocher at jboss.org">Noel Rocher</a> 29, june 2004 username & userName issue
+ * @version $Revision: 57189 $
+ */
+public class PBEIdentityLoginModule
+   extends AbstractPasswordCredentialLoginModule
+{
+   /**
+    * Class logger
+    */
+   private static final Logger log = Logger.getLogger(SecureIdentityLoginModule.class);
+
+   private String username;
+   private String password;
+   /** The Blowfish key material */
+   private char[] pbepass = "jaas is the way".toCharArray();
+   private String pbealgo = "PBEwithMD5andDES";
+   private byte[] salt = {1, 7, 2, 9, 3, 11, 4, 13};
+   private int iterationCount = 37;
+   private PBEParameterSpec cipherSpec;
+
+   public PBEIdentityLoginModule()
+   {
+   }
+   PBEIdentityLoginModule(String algo, char[] pass, byte[] pbesalt, int iter)
+   {
+      if( pass != null )
+         pbepass = pass;
+      if( algo != null )
+         pbealgo = algo;
+      if( pbesalt != null )
+         salt = pbesalt;
+      if( iter > 0 )
+         iterationCount = iter;
+   }
+
+   @SuppressWarnings("unchecked")
+   @Override
+   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+      // NR : we keep this username for compatibility
+      username = (String) options.get("username");
+      if( username == null )
+      {
+      	// NR : try with userName
+        username = (String) options.get("userName");      	
+        if( username == null )
+        {
+         throw new IllegalArgumentException("The user name is a required option");
+        }
+     }
+      password = (String) options.get("password");
+      if( password == null )
+      {
+         throw new IllegalArgumentException("The password is a required option");
+      }
+      // Look for the cipher password and algo parameters
+      String tmp = (String) options.get("pbepass");
+      if( tmp != null )
+      {
+         try
+         {
+            pbepass = Util.loadPassword(tmp);
+         }
+         catch(Exception e)
+         {
+            throw new IllegalStateException(e);
+         }
+      }
+      tmp = (String) options.get("pbealgo");
+      if( tmp != null )
+         pbealgo = tmp;
+      tmp = (String) options.get("salt");
+      if( tmp != null )
+         salt = tmp.substring(0, 8).getBytes();
+      tmp = (String) options.get("iterationCount");
+      if( tmp != null )
+         iterationCount = Integer.parseInt(tmp);
+   }
+
+   public boolean login() throws LoginException
+   {
+      log.trace("login called");
+      if( super.login() == true )
+         return true;
+
+      super.loginOk = true;
+      return true;
+   }
+
+   @SuppressWarnings("unchecked")
+   public boolean commit() throws LoginException
+   {
+      Principal principal = new SimplePrincipal(username);
+      SubjectActions.addPrincipals(subject, principal);
+      sharedState.put("javax.security.auth.login.name", username);
+      // Decode the encrypted password
+      try
+      {
+         char[] decodedPassword = decode(password);
+         PasswordCredential cred = new PasswordCredential(username, decodedPassword);
+         cred.setManagedConnectionFactory(getMcf());
+         SubjectActions.addCredentials(subject, cred);
+      }
+      catch(Exception e)
+      {
+         log.debug("Failed to decode password", e);
+         throw new LoginException("Failed to decode password: "+e.getMessage());
+      }
+      return true;
+   }
+
+   public boolean abort()
+   {
+      username = null;
+      password = null;
+      return true;
+   }
+
+   protected Principal getIdentity()
+   {
+      log.trace("getIdentity called, username="+username);
+      Principal principal = new SimplePrincipal(username);
+      return principal;
+   }
+
+   protected Group[] getRoleSets() throws LoginException
+   {
+      Group[] empty = new Group[0];
+      return empty;
+   }
+
+   private String encode(String secret)
+      throws Exception
+   {
+      // Create the PBE secret key
+      cipherSpec = new PBEParameterSpec(salt, iterationCount);
+      PBEKeySpec keySpec = new PBEKeySpec(pbepass);
+      SecretKeyFactory factory = SecretKeyFactory.getInstance(pbealgo);
+      SecretKey cipherKey = factory.generateSecret(keySpec);
+
+      // Decode the secret
+      Cipher cipher = Cipher.getInstance(pbealgo);
+      cipher.init(Cipher.ENCRYPT_MODE, cipherKey, cipherSpec);
+      byte[] encoding = cipher.doFinal(secret.getBytes());
+      return Base64Utils.tob64(encoding);
+   }
+
+   private char[] decode(String secret)
+      throws Exception
+   {
+      // Create the PBE secret key
+      cipherSpec = new PBEParameterSpec(salt, iterationCount);
+      PBEKeySpec keySpec = new PBEKeySpec(pbepass);
+      SecretKeyFactory factory = SecretKeyFactory.getInstance(pbealgo);
+      SecretKey cipherKey = factory.generateSecret(keySpec);
+      // Decode the secret
+      byte[] encoding = Base64Utils.fromb64(secret);
+      Cipher cipher = Cipher.getInstance(pbealgo);
+      cipher.init(Cipher.DECRYPT_MODE, cipherKey, cipherSpec);
+      byte[] decode = cipher.doFinal(encoding);
+      return new String(decode).toCharArray();
+   }
+
+   /** Main entry point to encrypt a password using the hard-coded pass phrase 
+    * 
+    * @param args - [0] = the password to encode
+    *    [1] = PBE password 
+    *    [2] = PBE salt 
+    *    [3] = PBE iterationCount 
+    *    [4] = PBE algo 
+    * @throws Exception
+    */ 
+   public static void main(String[] args) throws Exception
+   {
+      String algo = null;
+      char[] pass = "jaas is the way".toCharArray();
+      byte[] salt = null;
+      int iter = -1;
+      if( args.length >= 2 )
+         pass = args[1].toCharArray();
+      if( args.length >= 3 )
+         salt = args[2].getBytes();
+      if( args.length >= 4 )
+         iter = Integer.decode(args[3]).intValue();
+      if( args.length >= 5 )
+         algo = args[4];
+
+      PBEIdentityLoginModule pbe = new PBEIdentityLoginModule(algo, pass, salt, iter);
+      String encode = pbe.encode(args[0]);
+      System.out.println("Encoded password: "+encode);
+   }
+}


Property changes on: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/PBEIdentityLoginModule.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SecureIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SecureIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SecureIdentityLoginModule.java	2008-04-04 20:56:38 UTC (rev 71734)
@@ -0,0 +1,187 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, 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.resource.security;
+
+import java.security.acl.Group;
+import java.security.Principal;
+import java.security.NoSuchAlgorithmException;
+import java.security.InvalidKeyException;
+import java.util.Map;
+import java.math.BigInteger;
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.BadPaddingException;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.Cipher;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.jboss.security.SimplePrincipal;
+import org.jboss.logging.Logger;
+
+/** An example of how one could encrypt the database password for a jca
+  connection factory. The corresponding  
+ 
+<application-policy name = "HsqlDbRealm">
+   <authentication>
+      <login-module code = "org.jboss.resource.security.SecureIdentityLoginMdule"
+         flag = "required">
+         <module-option name = "userName">sa</module-option>
+         <module-option name = "password">-207a6df87216de44</module-option>
+         <module-option name = "managedConnectionFactoryName">jboss.jca:servce=LocalTxCM,name=DefaultDS</module-option>
+      </login-module>
+   </authentication>
+</application-policy>
+
+ This uses a hard-coded cipher algo of Blowfish, and key derived from the
+ phrase 'jaas is the way'. Adjust to your requirements.
+
+ * @author Scott.Stark at jboss.org
+ * @author <a href="mailto:noel.rocher at jboss.org">Noel Rocher</a> 29, june 2004 username & userName issue
+ * @version $Revision: 71545 $
+ */
+public class SecureIdentityLoginModule
+   extends AbstractPasswordCredentialLoginModule
+{
+   /**
+    * Class logger
+    */
+   private static final Logger log = Logger.getLogger(SecureIdentityLoginModule.class);
+
+   private String username;
+   private String password;
+
+   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+      // NR : we keep this username for compatibility
+      username = (String) options.get("username");
+      if( username == null )
+      {
+      	// NR : try with userName
+        username = (String) options.get("userName");      	
+        if( username == null )
+        {
+         throw new IllegalArgumentException("The user name is a required option");
+        }
+     }
+      password = (String) options.get("password");
+      if( password == null )
+      {
+         throw new IllegalArgumentException("The password is a required option");
+      }
+   }
+
+   public boolean login() throws LoginException
+   {
+      log.trace("login called");
+      if( super.login() == true )
+         return true;
+
+      super.loginOk = true;
+      return true;
+   }
+
+   public boolean commit() throws LoginException
+   {
+      Principal principal = new SimplePrincipal(username);
+      SubjectActions.addPrincipals(subject, principal);
+      sharedState.put("javax.security.auth.login.name", username);
+      // Decode the encrypted password
+      try
+      {
+         char[] decodedPassword = decode(password);
+         PasswordCredential cred = new PasswordCredential(username, decodedPassword);
+         cred.setManagedConnectionFactory(getMcf());
+         SubjectActions.addCredentials(subject, cred);
+      }
+      catch(Exception e)
+      {
+         log.debug("Failed to decode password", e);
+         throw new LoginException("Failed to decode password: "+e.getMessage());
+      }
+      return true;
+   }
+
+   public boolean abort()
+   {
+      username = null;
+      password = null;
+      return true;
+   }
+
+   protected Principal getIdentity()
+   {
+      log.trace("getIdentity called, username="+username);
+      Principal principal = new SimplePrincipal(username);
+      return principal;
+   }
+
+   protected Group[] getRoleSets() throws LoginException
+   {
+      Group[] empty = new Group[0];
+      return empty;
+   }
+
+   private static String encode(String secret)
+      throws NoSuchPaddingException, NoSuchAlgorithmException,
+      InvalidKeyException, BadPaddingException, IllegalBlockSizeException
+   {
+      byte[] kbytes = "jaas is the way".getBytes();
+      SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
+
+      Cipher cipher = Cipher.getInstance("Blowfish");
+      cipher.init(Cipher.ENCRYPT_MODE, key);
+      byte[] encoding = cipher.doFinal(secret.getBytes());
+      BigInteger n = new BigInteger(encoding);
+      return n.toString(16);
+   }
+
+   private static char[] decode(String secret)
+      throws NoSuchPaddingException, NoSuchAlgorithmException,
+      InvalidKeyException, BadPaddingException, IllegalBlockSizeException
+   {
+      byte[] kbytes = "jaas is the way".getBytes();
+      SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
+
+      BigInteger n = new BigInteger(secret, 16);
+      byte[] encoding = n.toByteArray();
+      
+      Cipher cipher = Cipher.getInstance("Blowfish");
+      cipher.init(Cipher.DECRYPT_MODE, key);
+      byte[] decode = cipher.doFinal(encoding);
+      return new String(decode).toCharArray();
+   }
+
+   /** Main entry point to encrypt a password using the hard-coded pass phrase 
+    * 
+    * @param args - [0] = the password to encode
+    * @throws Exception
+    */ 
+   public static void main(String[] args) throws Exception
+   {
+      String encode = encode(args[0]);
+      System.out.println("Encoded password: "+encode);
+   }
+}


Property changes on: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SecureIdentityLoginModule.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SubjectActions.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SubjectActions.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SubjectActions.java	2008-04-04 20:56:38 UTC (rev 71734)
@@ -0,0 +1,185 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, 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.resource.security;
+
+import java.security.AccessController;
+import java.security.Principal;
+import java.security.PrivilegedAction;
+import java.security.acl.Group;
+import java.util.Iterator;
+import java.util.Set;
+import javax.resource.spi.ManagedConnectionFactory;
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+
+import org.jboss.security.SimpleGroup;
+
+/**
+ * Common package privileged actions.
+ * 
+ * @author Scott.Stark at jboss.org
+ * @version $Revision: 71545 $
+ */
+class SubjectActions
+{
+   interface AddRolesActions
+   {
+      AddRolesActions PRIVILEGED = new AddRolesActions()
+      {
+         public void addRoles(final Subject subject, final Set roles)
+         {
+            AccessController.doPrivileged(new PrivilegedAction()
+            {
+               public Object run()
+               {
+                  addSubjectRoles(subject, roles);
+                  return null;
+               }
+            });
+         }
+      };
+
+      AddRolesActions NON_PRIVILEGED = new AddRolesActions()
+      {
+         public void addRoles(final Subject subject, final Set roles)
+         {
+            addSubjectRoles(subject, roles);
+         }
+      };
+
+      void addRoles(Subject subject, Set roles);
+   }
+
+   static class AddCredentialsAction implements PrivilegedAction
+   {
+      Subject subject;
+      PasswordCredential cred;
+      AddCredentialsAction(Subject subject, PasswordCredential cred)
+      {
+         this.subject = subject;
+         this.cred = cred;
+      }
+      public Object run()
+      {
+         subject.getPrivateCredentials().add(cred);
+         return null;
+      }
+   }
+   static class AddPrincipalsAction implements PrivilegedAction
+   {
+      Subject subject;
+      Principal p;
+      AddPrincipalsAction(Subject subject, Principal p)
+      {
+         this.subject = subject;
+         this.p = p;
+      }
+      public Object run()
+      {
+         subject.getPrincipals().add(p);
+         return null;
+      }
+   }
+   static class RemoveCredentialsAction implements PrivilegedAction
+   {
+      Subject subject;
+      ManagedConnectionFactory mcf;
+      RemoveCredentialsAction(Subject subject, ManagedConnectionFactory mcf)
+      {
+         this.subject = subject;
+         this.mcf = mcf;
+      }
+      public Object run()
+      {
+         Iterator i = subject.getPrivateCredentials().iterator();
+         while( i.hasNext() )
+         {
+            Object o = i.next();
+            if ( o instanceof PasswordCredential )
+            {
+               PasswordCredential pc = (PasswordCredential) o;
+               if( pc.getManagedConnectionFactory() == mcf )
+                  i.remove();
+            }
+         }
+         return null;
+      }
+   }
+
+   static void addCredentials(Subject subject, PasswordCredential cred)
+   {
+      AddCredentialsAction action = new AddCredentialsAction(subject, cred);
+      AccessController.doPrivileged(action);
+   }
+   static void addPrincipals(Subject subject, Principal p)
+   {
+      AddPrincipalsAction action = new AddPrincipalsAction(subject, p);
+      AccessController.doPrivileged(action);
+   }
+   static void removeCredentials(Subject subject, ManagedConnectionFactory mcf)
+   {
+      RemoveCredentialsAction action = new RemoveCredentialsAction(subject, mcf);
+      AccessController.doPrivileged(action);
+   }
+
+   static void addRoles(Subject subject, Set runAsRoles)
+   {
+      if( System.getSecurityManager() != null )
+      {
+         AddRolesActions.PRIVILEGED.addRoles(subject, runAsRoles);
+      }
+      else
+      {
+         AddRolesActions.NON_PRIVILEGED.addRoles(subject, runAsRoles);         
+      }
+   }
+
+   private static Group addSubjectRoles(Subject theSubject, Set roles)
+   {
+      Set subjectGroups = theSubject.getPrincipals(Group.class);
+      Iterator iter = subjectGroups.iterator();
+      Group roleGrp = null;
+      while (iter.hasNext())
+      {
+         Group grp = (Group) iter.next();
+         String name = grp.getName();
+         if (name.equals("Roles"))
+            roleGrp = grp;
+      }
+
+      // Create the Roles group if it was not found
+      if (roleGrp == null)
+      {
+         roleGrp = new SimpleGroup("Roles");
+         theSubject.getPrincipals().add(roleGrp);
+      }
+
+      iter = roles.iterator();
+      while (iter.hasNext())
+      {
+         Principal role = (Principal) iter.next();
+         roleGrp.addMember(role);
+      }
+      return roleGrp;
+   }
+
+}


Property changes on: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/resource/security/SubjectActions.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/Util.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/Util.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/Util.java	2008-04-04 20:56:38 UTC (rev 71734)
@@ -0,0 +1,238 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, 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.security;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.ArrayList;
+import java.util.StringTokenizer;
+
+import org.jboss.logging.Logger;
+
+/**
+ * Util.
+ * 
+ * @author Scott.Stark at jboss.org
+ * @author <a href="adrian at jboss.com">Adrian Brock</a>
+ * @version $Revision: 1.1 $
+ */
+public class Util
+{
+   private static Logger log = Logger.getLogger(Util.class);
+
+   /**
+    * Execute a password load command to obtain the char[] contents of a
+    * password.
+    * @param  passwordCmd  - A command to execute to obtain the plaintext
+    * password. The format is one of:
+    * '{EXT}...' where the '...' is the exact command
+    * line that will be passed to the Runtime.exec(String) method to execute a
+    * platform command. The first line of the command output is used as the
+    * password.
+    * '{CLASS}classname[:ctorargs]' where the '[:ctorargs]' is an optional
+    * string delimited by the ':' from the classname that will be passed to the
+    * classname ctor. The ctorargs itself is a comma delimited list of strings.
+    * The password is obtained from classname by invoking a
+    * 'char[] toCharArray()' method if found, otherwise, the 'String toString()'
+    * method is used.
+    * @return the password characters
+    * @throws Exception
+    */ 
+   public static char[] loadPassword(String passwordCmd)
+      throws Exception
+   {
+      char[] password = null;
+      String passwordCmdType = null;
+      
+      // Look for a {...} prefix indicating a password command
+      if( passwordCmd.charAt(0) == '{' )
+      {
+         StringTokenizer tokenizer = new StringTokenizer(passwordCmd, "{}");
+         passwordCmdType = tokenizer.nextToken();
+         passwordCmd = tokenizer.nextToken();
+      }
+      else
+      {
+         // Its just the password string
+         password = passwordCmd.toCharArray();
+      }
+
+      if( password == null )
+      {
+         // Load the password
+         if( passwordCmdType.equals("EXT") )
+            password = execPasswordCmd(passwordCmd);
+         else if( passwordCmdType.equals("CLASS") )
+            password = invokePasswordClass(passwordCmd);
+         else
+            throw new IllegalArgumentException("Unknown passwordCmdType: "+passwordCmdType);
+      }
+      return password;
+   }
+
+   /**
+    * Execute a Runtime command to load a password.
+    * @param passwordCmd
+    * @return
+    * @throws Exception
+    */
+   private static char[] execPasswordCmd(String passwordCmd)
+      throws Exception
+   {
+      log.debug("Executing command: "+passwordCmd);
+      String password = execCmd(passwordCmd);
+      return password.toCharArray();
+   }
+
+   private static char[] invokePasswordClass(String passwordCmd)
+      throws Exception
+   {
+      char[] password = null;
+
+      // Check for a ctor argument delimited by ':'
+      String classname = passwordCmd;
+      String ctorArgs = null;
+      int colon = passwordCmd.indexOf(':');
+      if( colon > 0 )
+      {
+         classname = passwordCmd.substring(0, colon);
+         ctorArgs = passwordCmd.substring(colon+1);
+      }
+      log.debug("Loading class: "+classname+", ctorArgs="+ctorArgs);
+      ClassLoader loader = AccessController.doPrivileged(GetTCLAction.ACTION);
+      Class<?> c = loader.loadClass(classname);
+      Object instance = null;
+      // Check for a ctor(String,...) if ctorArg is not null
+      if( ctorArgs != null )
+      {
+         Object[] args = ctorArgs.split(",");
+         Class<?>[] sig = new Class[args.length];
+         ArrayList<Class<?>> sigl = new ArrayList<Class<?>>();
+         for(int n = 0; n < args.length; n ++)
+            sigl.add(String.class);
+         sigl.toArray(sig);
+         Constructor<?> ctor = c.getConstructor(sig);
+         instance = ctor.newInstance(args);
+      }
+      else
+      {
+         // Use the default ctor
+         instance = c.newInstance();
+      }
+
+      // Look for a toCharArray() method
+      try
+      {
+         log.debug("Checking for toCharArray");
+         Class<?>[] sig = {};
+         Method toCharArray = c.getMethod("toCharArray", sig);
+         Object[] args = {};
+         log.debug("Invoking toCharArray");
+         password = (char[]) toCharArray.invoke(instance, args);
+      }
+      catch(NoSuchMethodException e)
+      {
+         log.debug("No toCharArray found, invoking toString");
+         String tmp = instance.toString();
+         if( tmp != null )
+            password = tmp.toCharArray();
+      }
+      return password;
+   }
+
+   private static class GetTCLAction implements PrivilegedAction<ClassLoader>
+   {
+      static PrivilegedAction<ClassLoader> ACTION = new GetTCLAction();
+      public ClassLoader run()
+      {
+         return Thread.currentThread().getContextClassLoader();
+      }
+   }
+
+   private static String execCmd(String cmd) throws Exception
+   {
+      SecurityManager sm = System.getSecurityManager();
+      String line;
+      if( sm != null )
+      {
+         line = RuntimeActions.PRIVILEGED.execCmd(cmd);
+      }
+      else
+      {
+         line = RuntimeActions.NON_PRIVILEGED.execCmd(cmd);
+      }
+      return line;
+   }
+
+   
+   interface RuntimeActions
+   {
+      RuntimeActions PRIVILEGED = new RuntimeActions()
+      {
+         public String execCmd(final String cmd)
+            throws Exception
+         {
+            try
+            {
+               String line = AccessController.doPrivileged(
+               new PrivilegedExceptionAction<String>()
+                  {
+                     public String run() throws Exception
+                     {
+                        return NON_PRIVILEGED.execCmd(cmd);
+                     }
+                  }
+               );
+               return line;
+            }
+            catch(PrivilegedActionException e)
+            {
+               throw e.getException();
+            }
+         }
+      };
+      RuntimeActions NON_PRIVILEGED = new RuntimeActions()
+      {
+         public String execCmd(final String cmd)
+            throws Exception
+         {
+            Runtime rt = Runtime.getRuntime();
+            Process p = rt.exec(cmd);
+            InputStream stdin = p.getInputStream();
+            BufferedReader reader = new BufferedReader(new InputStreamReader(stdin));
+            String line = reader.readLine();
+            stdin.close();
+            int exitCode = p.waitFor();
+            log.debug("Command exited with: "+exitCode);
+            return line;
+         }
+      };
+      String execCmd(String cmd) throws Exception;
+   }
+}




More information about the jboss-cvs-commits mailing list