Author: tyrell
Date: Wed May 14 01:06:50 2008
New Revision: 16986

Log:
Adding capability to load a user specific keystore+certificates to carry out 
https sessions.

Modified:
   trunk/mashup/java/modules/core/src/org/wso2/mashup/MashupConstants.java
   
trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/CustomProtocolSocketFactory.java
   
trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/MashupArchiveManupulator.java
   trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/MashupUtils.java
   
trunk/mashup/java/modules/core/src/org/wso2/mashup/webapp/utils/RegistryUtils.java

Modified: 
trunk/mashup/java/modules/core/src/org/wso2/mashup/MashupConstants.java
==============================================================================
--- trunk/mashup/java/modules/core/src/org/wso2/mashup/MashupConstants.java     
(original)
+++ trunk/mashup/java/modules/core/src/org/wso2/mashup/MashupConstants.java     
Wed May 14 01:06:50 2008
@@ -83,7 +83,14 @@
     public static final String PROFILE_PATH = "profilePath";
     public static final String ALL_MASHUPS_PATH = "/mashups";
     public static final String QUERYSTORE_QUERY_PATH = "/querystore";
+
     public static final String USERS_PATH = "/users";
+
+    // The path to the individual keystore under every user
+    public static final String USER_KEYSTORE_PATH = "/keystore";
+    public static final String USER_KEYSTORE_TYPE = "user-keystore-type";
+    public static final String USER_KEYSTORE_PASSWORD = 
"user-keystore-password";
+
     public static final String SYSTEM_PATH = "/system";
     public static final String SYSTEM__QUERIES_PATH = SYSTEM_PATH + "/queries";
     public static final String PROFILES_PATH = USERS_PATH + "/profile";

Modified: 
trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/CustomProtocolSocketFactory.java
==============================================================================
--- 
trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/CustomProtocolSocketFactory.java
   (original)
+++ 
trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/CustomProtocolSocketFactory.java
   Wed May 14 01:06:50 2008
@@ -19,8 +19,9 @@
 import org.apache.commons.httpclient.params.HttpConnectionParams;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.wso2.utils.ServerConfiguration;
 import org.wso2.mashup.MashupConstants;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
 
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.KeyManagerFactory;
@@ -31,7 +32,7 @@
 import java.net.InetSocketAddress;
 import java.net.SocketAddress;
 import java.io.IOException;
-import java.io.FileInputStream;
+import java.io.ByteArrayInputStream;
 import java.security.KeyStore;
 import java.security.NoSuchAlgorithmException;
 import java.security.KeyStoreException;
@@ -39,7 +40,12 @@
 import java.security.KeyManagementException;
 import java.security.cert.CertificateException;
 
-
+/**
+ * 
+ * This is a custom implementation of the SecureProtocolSocketFactory, which 
is capable of
+ * using a specified keystore and certificates stored within to initiate https 
sessions.
+ *
+ */
 public class CustomProtocolSocketFactory implements 
SecureProtocolSocketFactory {
 
     /**
@@ -49,23 +55,19 @@
 
     private SSLContext sslcontext = null;
 
-    public CustomProtocolSocketFactory() {
+    private Resource userKeyStore = null;
+
+    public CustomProtocolSocketFactory(Resource keyStore) {
         super();
+        this.userKeyStore = keyStore;
     }
 
-    private static SSLContext createSSLContext() {
-        ServerConfiguration serverConfig = ServerConfiguration.getInstance();
-
-        String keyStoreLocation =
-                serverConfig.getFirstProperty(MashupConstants.SECURITY_CONFIG 
+ "." +
-                        MashupConstants.SECURITY_CONFIG_KEYSTORE + "." + 
MashupConstants
-                        .SECURITY_CONFIG_KEYSTORE_LOCATION);
+    private SSLContext createSSLContext() {
         
-        String keyStorePass = 
serverConfig.getFirstProperty(MashupConstants.SECURITY_CONFIG + "." +
-                MashupConstants.SECURITY_CONFIG_KEYSTORE + "." + 
MashupConstants
-                .SECURITY_CONFIG_KEYSTORE_PASSWORD);
+        String keyStorePass = 
userKeyStore.getProperty(MashupConstants.USER_KEYSTORE_PASSWORD);
 
-        try {
+        try {                   
+            
             System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");
             SSLContext sslContext = SSLContext.getInstance("TLS");
 
@@ -73,13 +75,13 @@
 
             KeyStore keyStore = KeyStore.getInstance("JKS");
             char[] keyPassphrase = keyStorePass.toCharArray();
-            keyStore.load(new FileInputStream(keyStoreLocation), 
keyPassphrase);
+            keyStore.load(new ByteArrayInputStream((byte[]) 
this.userKeyStore.getContent()), keyPassphrase);
             keyManagerFactory.init(keyStore, keyPassphrase);
 
             TrustManagerFactory trustManagerFactory = 
TrustManagerFactory.getInstance("SunX509");
             KeyStore trustStore = KeyStore.getInstance("JKS");
             char[] trustPassphrase = keyStorePass.toCharArray();
-            trustStore.load(new FileInputStream(keyStoreLocation), 
trustPassphrase);
+            trustStore.load(new ByteArrayInputStream((byte[]) 
this.userKeyStore.getContent()), trustPassphrase);
             trustManagerFactory.init(trustStore);
 
             sslContext.init(keyManagerFactory.getKeyManagers(),
@@ -92,14 +94,16 @@
             log.error(e);
         } catch (KeyStoreException e) {
             log.error(e);
-        } catch (IOException e) {
-            log.error(e);
         } catch (CertificateException e) {
             log.error(e);
         } catch (UnrecoverableKeyException e) {
             log.error(e);
         } catch (KeyManagementException e) {
             log.error(e);
+        } catch (RegistryException e) {
+            log.error(e);
+        } catch (IOException e) {
+            log.error(e);
         }
 
         return null;

Modified: 
trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/MashupArchiveManupulator.java
==============================================================================
--- 
trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/MashupArchiveManupulator.java
      (original)
+++ 
trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/MashupArchiveManupulator.java
      Wed May 14 01:06:50 2008
@@ -197,7 +197,7 @@
      * Mashup Server donated by the destinationServerAddress.
      *
      * @param destinationServerAddress -
-     *                                 remote mashup server address (eg: 
http://mashup.wso2.org:9762)
+     *                                 remote mashup server address (eg: 
https://mooshup.com)
      * @param dataHandler              -
      *                                 contains the archived mashup service
      * @param configCtx                - The configuration Context
@@ -235,8 +235,8 @@
         options.setProperty(HTTPConstants.CHUNKED, "false");
         options.setProperty(Constants.Configuration.ENABLE_MTOM, 
Constants.VALUE_TRUE);
 
-        // Creating a custom protocol based on the user's keystores and 
trusted certs within
-        ProtocolSocketFactory psf = new CustomProtocolSocketFactory();
+        // Creating a custom protocol based on the user's keystores and 
trusted certs within        
+        ProtocolSocketFactory psf = new 
CustomProtocolSocketFactory(MashupUtils.getUserKeystoreResource(null, 
configCtx));
         Protocol protocol = new Protocol("https", psf, 443);
         options.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER,  protocol);
 

Modified: 
trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/MashupUtils.java
==============================================================================
--- trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/MashupUtils.java   
(original)
+++ trunk/mashup/java/modules/core/src/org/wso2/mashup/utils/MashupUtils.java   
Wed May 14 01:06:50 2008
@@ -50,6 +50,7 @@
 import org.wso2.registry.RegistryConstants;
 import org.wso2.registry.RegistryException;
 import org.wso2.registry.ResourceImpl;
+import org.wso2.registry.Resource;
 import org.wso2.registry.jdbc.EmbeddedRegistry;
 import org.wso2.registry.session.UserRegistry;
 import org.wso2.registry.users.AccessControlAdmin;
@@ -953,7 +954,7 @@
         ServerManager serverManager = ServerManager.getInstance();
         ConfigurationContext configContext = serverManager.configContext;
         return configContext.getAxisConfiguration().getTransportsIn();
-    }     
+    }
 
     public static boolean isTransportExposed(String serviceName, String 
transportName) throws AxisFault {
         ServerManager serverManager = ServerManager.getInstance();
@@ -1029,4 +1030,61 @@
         }
         return scripts;
     }
+
+
+    public static Resource getUserKeystoreResource(String userName, 
ConfigurationContext configCtx){
+
+        EmbeddedRegistry embeddedRegistry =
+                (EmbeddedRegistry) 
configCtx.getAxisConfiguration().getParameterValue(
+                        RegistryConstants.REGISTRY);
+        try {
+            UserRegistry systemRegistry = embeddedRegistry.getSystemRegistry();
+
+            // If a user name is provided using that, else using the currently 
logged in user's name.
+            String path = "";
+            if(userName != null){
+                path = MashupConstants.USERS_PATH + "/" + userName + 
MashupConstants.USER_KEYSTORE_PATH;
+            }else{
+                path = MashupConstants.USERS_PATH + "/" + 
systemRegistry.getUserName() + MashupConstants.USER_KEYSTORE_PATH;
+            }
+
+            return systemRegistry.get(path);
+
+        } catch (RegistryException e) {
+            log.error(e);
+        }
+
+        return null;
+    }
+
+     public static byte[] getBytesFromFile(File file) throws IOException {
+        InputStream is = new FileInputStream(file);
+
+        // Get the size of the file
+        long length = file.length();
+
+        if (length > Integer.MAX_VALUE) {
+            // File is too large
+        }
+
+        // Create the byte array to hold the data
+        byte[] bytes = new byte[(int) length];
+
+        // Read in the bytes
+        int offset = 0;
+        int numRead = 0;
+        while (offset < bytes.length
+                && (numRead = is.read(bytes, offset, bytes.length - offset)) 
>= 0) {
+            offset += numRead;
+        }
+
+        // Ensure all the bytes have been read in
+        if (offset < bytes.length) {
+            throw new IOException("Could not completely read file " + 
file.getName());
+        }
+
+        // Close the input stream and return bytes
+        is.close();
+        return bytes;
+    }
 }
\ No newline at end of file

Modified: 
trunk/mashup/java/modules/core/src/org/wso2/mashup/webapp/utils/RegistryUtils.java
==============================================================================
--- 
trunk/mashup/java/modules/core/src/org/wso2/mashup/webapp/utils/RegistryUtils.java
  (original)
+++ 
trunk/mashup/java/modules/core/src/org/wso2/mashup/webapp/utils/RegistryUtils.java
  Wed May 14 01:06:50 2008
@@ -23,6 +23,7 @@
 import org.wso2.mashup.MashupFault;
 import org.wso2.mashup.utils.QueryResult;
 import org.wso2.mashup.utils.QueryResults;
+import org.wso2.mashup.utils.MashupUtils;
 import org.wso2.mashup.webapp.userprofile.User;
 import org.wso2.registry.ActionConstants;
 import org.wso2.registry.Collection;
@@ -51,6 +52,8 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.net.URLDecoder;
 import java.util.ArrayList;
 import java.util.Calendar;
@@ -58,6 +61,8 @@
 import java.util.GregorianCalendar;
 import java.util.HashMap;
 import java.util.Map;
+import java.nio.channels.FileChannel;
+import java.nio.ByteBuffer;
 
 public class RegistryUtils {
 
@@ -78,7 +83,7 @@
                     (EmbeddedRegistry) 
context.getAttribute(RegistryConstants.REGISTRY);
 
             userRegistry = createUserRegistry(RegistryConstants.ANONYMOUS_USER,
-                                                                 "guest", 
embeddedRegistry);
+                                              "guest", embeddedRegistry);
 
             request.getSession().setAttribute(MashupConstants.USER_REGISTRY, 
userRegistry);
 
@@ -87,7 +92,7 @@
     }
 
     public static UserRegistry createUserRegistry(String username, String 
password,
-                                                      EmbeddedRegistry 
registry)
+                                                  EmbeddedRegistry registry)
             throws MashupFault {
         UserRegistry userRegistry;
         try {
@@ -138,7 +143,7 @@
     /**
      * Validates whether a logged in user can perform a given action on a 
given resource
      *
-     * @param userRegistry       An active instance of the registry
+     * @param userRegistry   An active instance of the registry
      * @param resourcePath   A path to a Registry Resource
      * @param resourceAction An action to be performed on the resource
      * @return Whether the user is authorized or not
@@ -163,35 +168,36 @@
 
     public static boolean isAdminRole(UserRegistry userRegistry) throws 
RegistryException {
 
-            String[] userRoles;
-            UserStoreReader userStoreReader;
-            try {
-                userStoreReader = 
userRegistry.getUserRealm().getUserStoreReader();
+        String[] userRoles;
+        UserStoreReader userStoreReader;
+        try {
+            userStoreReader = userRegistry.getUserRealm().getUserStoreReader();
 
-                // Get user properties and respond as non-admin if current 
user is a pseudo user.
-                Map userProps = 
userStoreReader.getUserProperties(userRegistry.getUserName());
-                if (Boolean.parseBoolean((String) 
userProps.get(MashupConstants.PSEUDO_USER))) {
-                    return false;
-                }
-                
-                userRoles = 
userStoreReader.getUserRoles(userRegistry.getUserName());
-            } catch (UserStoreException e) {
+            // Get user properties and respond as non-admin if current user is 
a pseudo user.
+            Map userProps = 
userStoreReader.getUserProperties(userRegistry.getUserName());
+            if (Boolean.parseBoolean((String) 
userProps.get(MashupConstants.PSEUDO_USER))) {
                 return false;
             }
 
-            if (userRoles != null) {
-                for (int x = 0; x < userRoles.length; x++) {
-                    if 
(userRoles[x].equalsIgnoreCase(RegistryConstants.ADMIN_ROLE)) {
-                        return true;
-                    }
+            userRoles = 
userStoreReader.getUserRoles(userRegistry.getUserName());
+        } catch (UserStoreException e) {
+            return false;
+        }
+
+        if (userRoles != null) {
+            for (int x = 0; x < userRoles.length; x++) {
+                if 
(userRoles[x].equalsIgnoreCase(RegistryConstants.ADMIN_ROLE)) {
+                    return true;
                 }
             }
+        }
 
         return false;
     }
 
     /**
      * Returns if the current user is playing a pseudo user role.
+     *
      * @param userRegistry UserRegistry instance.
      * @return true if the user is playinng a pseudo role.
      */
@@ -212,7 +218,7 @@
      * Allows an admin to make self a pseudo user.
      *
      * @param userRegistry Instance of registry.
-     * @param enable   Make into a pseudo user if true. If false, revert to 
admin.
+     * @param enable       Make into a pseudo user if true. If false, revert 
to admin.
      * @return true if the operation succeeds.
      * @throws RegistryException If an error is encountered.
      */
@@ -248,7 +254,7 @@
      * @param registry Secure registry instance.
      * @return UserStoreAdmin instance.
      * @throws RegistryException  Thrown in case a exception occurs in the 
registry
-     * @throws UserStoreException  Thrown in case a exception occurs in User 
Manager
+     * @throws UserStoreException Thrown in case a exception occurs in User 
Manager
      */
     public static UserStoreAdmin getUserStoreAdmin(Registry registry)
             throws RegistryException, UserStoreException {
@@ -264,7 +270,7 @@
      *
      * @param request Current servlet request.
      * @return User's full name.
-     * @throws RegistryException  Thrown in case a exception occurs in the 
registry
+     * @throws RegistryException Thrown in case a exception occurs in the 
registry
      */
     public static String getCurrentUserFullName(HttpServletRequest request)
             throws RegistryException {
@@ -272,7 +278,8 @@
         String currentUserFullName;
         String currentUser;
 
-        UserRegistry userRegistry = (UserRegistry) 
session.getAttribute(MashupConstants.USER_REGISTRY);
+        UserRegistry userRegistry =
+                (UserRegistry) 
session.getAttribute(MashupConstants.USER_REGISTRY);
 
         currentUser = getCurrentUser(userRegistry);
 
@@ -283,7 +290,8 @@
 
     /**
      * Retrieve the full name of a given user from the user manager database.
-     * @param request Servlet request instance.
+     *
+     * @param request  Servlet request instance.
      * @param userName Name of user, for whom full name is required.
      * @return The full name of the specified user.
      * @throws RegistryException If the retrieval of user information fails.
@@ -301,7 +309,7 @@
             // If the full name has not been cached in the session, retrieve 
it and add to cache.
             if (fullName == null || "".equals(fullName)) {
                 UserRegistry userRegistry = (UserRegistry) request.getSession()
-                                .getAttribute(MashupConstants.USER_REGISTRY);
+                        .getAttribute(MashupConstants.USER_REGISTRY);
                 UserRealm realm = userRegistry.getUserRealm();
 
                 try {
@@ -347,7 +355,8 @@
         registry.put(profilePath, userProfile);
     }
 
-    public static QueryResults doQuery(UserRegistry userRegistry, String 
queryHeading, String queryPath,
+    public static QueryResults doQuery(UserRegistry userRegistry, String 
queryHeading,
+                                       String queryPath,
                                        String[] params, int maxResults)
             throws RegistryException {
 
@@ -493,7 +502,8 @@
 
                         queryResult
                                 .setRating(
-                                        
userRegistry.getRating(resultArtifact.getPath(), currentUser));
+                                        
userRegistry.getRating(resultArtifact.getPath(),
+                                                               currentUser));
                         queryResult
                                 .setAverageRating(
                                         
userRegistry.getAverageRating(resultArtifact.getPath()));
@@ -534,11 +544,11 @@
      * this user authority to modify his or her own profile.
      *
      * @param systemRegistry Instance of the JDBC registry.
-     * @param userName Name of user to add to registry.
-     * @param fullName Full name of user.
-     * @param eMailId  User's e-mail ID.
-     * @param bio      User's bio.
-     * @throws UserStoreException  Thrown in case a exception occurs in 
usermanager
+     * @param userName       Name of user to add to registry.
+     * @param fullName       Full name of user.
+     * @param eMailId        User's e-mail ID.
+     * @param bio            User's bio.
+     * @throws UserStoreException Thrown in case a exception occurs in 
usermanager
      * @throws RegistryException  Thrown in case a exception occurs in the 
registry
      */
     public static void createUser(UserRegistry systemRegistry, String userName,
@@ -622,18 +632,21 @@
                 deploymentEngine.setDirectoryToExtensionMappingMap(newMap);
             }
         }
+
+        // Create the keystore for this user
+        addUserKeyStore(systemRegistry, userName);
     }
 
     /**
      * Updates information for a given user in the user manager and the 
registry.
      *
-     * @param userRegistry       Instance of the JDBC registry.
+     * @param userRegistry   Instance of the JDBC registry.
      * @param userStoreAdmin User manager admin interface instance.
      * @param userName       Name of user to add to registry.
      * @param fullName       Full name of user.
      * @param eMailId        User's e-mail ID.
      * @param bio            User's bio.
-     * @throws UserStoreException  Thrown in case a exception occurs in 
usermanager
+     * @throws UserStoreException Thrown in case a exception occurs in 
usermanager
      * @throws RegistryException  Thrown in case a exception occurs in the 
registry
      */
     public static void updateUser(UserRegistry userRegistry, UserStoreAdmin 
userStoreAdmin,
@@ -688,9 +701,10 @@
     /**
      * Extracts the new and old password values from the string provided and 
calls user manager to
      * change the user's password.
+     *
      * @param storeAdmin User store admin instance.
-     * @param userName Name of user, who's password is to be changed.
-     * @param values String containing old and new password values.
+     * @param userName   Name of user, who's password is to be changed.
+     * @param values     String containing old and new password values.
      * @throws UserStoreException If the update fails.
      */
     public static void changeUserPassword(UserStoreAdmin storeAdmin, String 
userName, String values)
@@ -717,7 +731,8 @@
      * @param userName User name to be checked for status.
      * @return true if user profile is enabled.
      */
-    public static boolean isUserPrimary(UserRealm realm, String userName) 
throws UserStoreException {
+    public static boolean isUserPrimary(UserRealm realm, String userName)
+            throws UserStoreException {
         // Get the user's properties.
         UserStoreReader userStoreReader = realm.getUserStoreReader();
         Map userProps = userStoreReader.getUserProperties(userName);
@@ -758,7 +773,7 @@
                 return false;
             }
         } catch (RegistryException e) {
-            e.printStackTrace();
+            log.error(e);
             return false;
         }
     }
@@ -780,4 +795,60 @@
         return "http://wso2.com/announcements/mashup/"; + serverVersion + 
"/index.html";
 
     }
+
+
+    /**
+     * Adds a keystore to a given user, if one is not found already. This is 
initialized using
+     * the default system keystore and can be customized by individual users 
using the AdminUI.
+     * <p/>
+     * Typically, certificates will be added to this store in order to allow 
https sessions with
+     * outside domains. This store and its certificates will be loaded and 
used during such sessions.
+     *
+     * @param registry An instance of the registry
+     * @param userName The username of the keystore owner
+     */
+    private static void addUserKeyStore(Registry registry, String userName) {
+
+        String path =
+                MashupConstants.USERS_PATH + "/" + userName + 
MashupConstants.USER_KEYSTORE_PATH;
+        try {
+            registry.get(path);
+        } catch (RegistryException e) {
+            log.info("A keystore was not found for user " + userName +
+                    ". Initializing using the default keystore.");
+
+            // Getting the default keysotre
+            ServerConfiguration serverConfig = 
ServerConfiguration.getInstance();
+
+            String keyStoreLocation =
+                    
serverConfig.getFirstProperty(MashupConstants.SECURITY_CONFIG + "." +
+                            MashupConstants.SECURITY_CONFIG_KEYSTORE + "." + 
MashupConstants
+                            .SECURITY_CONFIG_KEYSTORE_LOCATION);
+
+            String keyStorePass =
+                    
serverConfig.getFirstProperty(MashupConstants.SECURITY_CONFIG + "." +
+                            MashupConstants.SECURITY_CONFIG_KEYSTORE + "." + 
MashupConstants
+                            .SECURITY_CONFIG_KEYSTORE_PASSWORD);
+
+            Resource keyStore = new ResourceImpl();
+            try {
+                // Reading the key file and storing it in the registry
+                keyStore.setContent(MashupUtils.getBytesFromFile(new 
File(keyStoreLocation)));
+
+                keyStore.setProperty(MashupConstants.USER_KEYSTORE_TYPE, 
"JKS");
+                keyStore.setProperty(MashupConstants.USER_KEYSTORE_PASSWORD, 
keyStorePass);
+
+                registry.put(path, keyStore);
+            } catch (FileNotFoundException e1) {
+                log.error(e1);
+            } catch (RegistryException e1) {
+                log.error(e1);
+            } catch (IOException e1) {
+                log.error(e1);
+            }
+        }
+    }
+
+
+   
 }

_______________________________________________
Mashup-dev mailing list
[email protected]
http://www.wso2.org/cgi-bin/mailman/listinfo/mashup-dev

Reply via email to