Advertisement
Guest User

Untitled

a guest
Jun 19th, 2017
504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.47 KB | None | 0 0
  1. package com.cfalzone.viewtools;
  2.  
  3. import java.security.MessageDigest;
  4. import java.util.Hashtable;
  5.  
  6. import javax.naming.AuthenticationException;
  7. import javax.naming.Context;
  8. import javax.naming.NamingEnumeration;
  9. import javax.naming.NamingException;
  10. import javax.naming.directory.DirContext;
  11. import javax.naming.directory.InitialDirContext;
  12. import javax.naming.directory.SearchControls;
  13. import javax.naming.directory.SearchResult;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpSession;
  16.  
  17. import org.apache.velocity.tools.view.tools.ViewTool;
  18.  
  19. import com.dotmarketing.business.APILocator;
  20. import com.dotmarketing.plugin.business.PluginAPI;
  21. import com.dotmarketing.util.Logger;
  22. import com.dotmarketing.util.UtilMethods;
  23.  
  24. /**
  25.  * Simple Session-based LDAP Authentication ViewTool for DotCMS
  26.  *
  27.  * @author Christopher Falzone <cfalzone@edinboro.edu>
  28.  * @version 2010.1006
  29.  */
  30. public class SimpleLDAPTool implements ViewTool {
  31.    
  32.     private String ldapServer = null;
  33.     private String ldapBase = null;
  34.     private String ldapReaderDN = null;
  35.     private String ldapReaderPassword = null;
  36.     private String ldapUsernameAttribute = null;
  37.     private String superSecretKey = null;
  38.     private final static String ldapContext = "com.sun.jndi.ldap.LdapCtxFactory";
  39.     private final static String ldapSecurity = "simple";
  40.    
  41.    
  42.     /**
  43.      * Init Method for the viewtool
  44.      */
  45.     public void init(Object obj) {
  46.         /* get the plugin Properties */
  47.         PluginAPI pluginAPI = APILocator.getPluginAPI();
  48.         try {
  49.             ldapServer = pluginAPI.loadProperty(
  50.                     "com.cfalzone.plugins.simpleldap",
  51.                     "simpleLDAP.ldapServer");
  52.             ldapBase = pluginAPI.loadProperty(
  53.                     "com.cfalzone.plugins.simpleldap",
  54.                     "simpleLDAP.ldapBase");
  55.             ldapUsernameAttribute = pluginAPI.loadProperty(
  56.                     "com.cfalzone.plugins.simpleldap",
  57.                     "simpleLDAP.ldapUsernameAttribute");
  58.             ldapReaderDN = pluginAPI.loadProperty(
  59.                     "com.cfalzone.plugins.simpleldap",
  60.                     "simpleLDAP.ldapReaderDN");
  61.             ldapReaderPassword = pluginAPI.loadProperty(
  62.                     "com.cfalzone.plugins.simpleldap",
  63.                     "simpleLDAP.ldapReaderPassword");
  64.             superSecretKey = pluginAPI.loadProperty(
  65.                     "com.cfalzone.plugins.simpleldap",
  66.                     "simpleLDAP.superSecretKey");
  67.         } catch (Exception e) {
  68.             Logger.error(this, "error while accessing properties", e);
  69.         }
  70.     }
  71.  
  72.     /**
  73.      * Sees if a user is logged in
  74.      *
  75.      * Example:  #set($islogged = $simple_ldap.is_logged($request))
  76.      *           #if($UtilMethods.isSet($islogged))
  77.      *             ## The User is logged in
  78.      *           #else
  79.      *             ## Show the login form
  80.      *           #end
  81.      *
  82.      * @param request   The Request Object
  83.      * @return          True if logged in, false otherwise
  84.      */
  85.     public Boolean is_logged(HttpServletRequest request) {
  86.  
  87.         HttpSession session = request.getSession(true);    
  88.        
  89.         /* Check for a form first */
  90.         String username = request.getParameter("username");
  91.         String password = request.getParameter("password");
  92.         if(UtilMethods.isSet(username) && UtilMethods.isSet(password)) {
  93.             /* There is a form, so process that login */           
  94.             if(checkLDAP(username, password)) {
  95.                 /* User Credentials pass -- create session and return true */
  96.                 session.setAttribute("username",request.getParameter("username"));
  97.                 session.setAttribute("logged",MD5(request.getParameter("username")+superSecretKey));
  98.                 Logger.info(this, "User "+username+" Logged in from form");
  99.                 return true;
  100.             } else {
  101.                 /* User Credentials do not pass -- clear session and return false */
  102.                 session.invalidate();
  103.                 Logger.info(this, "Invalid Login Form from user "+username);
  104.                 return false;
  105.             }
  106.         } else {
  107.             /* There is no form so check the session */
  108.             String user = (String) session.getAttribute("username");
  109.             String key = (String) session.getAttribute("logged");
  110.             if(UtilMethods.isSet(user) && UtilMethods.isSet(key)) {
  111.                 /* There is a session so check if it is valid */
  112.                 if(MD5(user+superSecretKey) == key) {
  113.                     /* Key matches so we have a good session return true */
  114.                     Logger.info(this, "User "+username+" Logged in from session");
  115.                     return true;
  116.                 } else {
  117.                     /* Invalid Session */
  118.                     session.invalidate();
  119.                     Logger.info(this, "Invalid Session from user "+username+" with key "+key);
  120.                     return false;
  121.                 }
  122.             } else {
  123.                 /* No session or form so just return false */
  124.                 return false;
  125.             }      
  126.         }
  127.     }
  128.  
  129.  
  130.     /**
  131.      * Checks to see if the supplied username and password are valid credentials
  132.      *
  133.      * @param username  The username to test
  134.      * @param password  The password to test
  135.      * @return          True if valid credentials, false otherwise
  136.      */
  137.     private Boolean checkLDAP(String username, String password) {
  138.         Hashtable<String, String> ldapEnv = new Hashtable<String, String>();
  139.         DirContext dirContext = null;
  140.         String ldapFilter = "("+ldapUsernameAttribute+"="+username+")";
  141.         SearchControls constraints = new SearchControls();
  142.        
  143.         /* Connect to LDAP */
  144.         ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, ldapContext);
  145.         ldapEnv.put(Context.PROVIDER_URL, ldapServer);
  146.         ldapEnv.put(Context.SECURITY_AUTHENTICATION, ldapSecurity);
  147.         ldapEnv.put(Context.SECURITY_PRINCIPAL, ldapReaderDN);
  148.         ldapEnv.put(Context.SECURITY_CREDENTIALS, ldapReaderPassword);
  149.         constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
  150.        
  151.         try {
  152.             dirContext = new InitialDirContext(ldapEnv);
  153.         } catch(Exception e) {
  154.             Logger.error(this, "error while connecting to LDAP", e);
  155.             return false;
  156.         }
  157.                
  158.         /* Do an LDAP Search for this user */
  159.         try {
  160.             Logger.info(this, "Searching for user "+username+" ...");
  161.             NamingEnumeration<SearchResult> results = dirContext.search(ldapBase, ldapFilter, constraints);
  162.             if(results != null && results.hasMore()) {
  163.                 /* This user Exists - check their password now */
  164.                 SearchResult sr = (SearchResult)results.next();
  165.                 String dn = sr.getName();
  166.                
  167.                 /* Try opening a Connection using this user */
  168.                 Logger.info(this, "Found user "+username+" with dn "+dn+" Attempting Login ...");
  169.                 Hashtable<String, String> authEnv = new Hashtable<String, String>();               
  170.                 authEnv.put(Context.INITIAL_CONTEXT_FACTORY, ldapContext);
  171.                 authEnv.put(Context.PROVIDER_URL, ldapServer);
  172.                 authEnv.put(Context.SECURITY_AUTHENTICATION, ldapSecurity);
  173.                 authEnv.put(Context.SECURITY_PRINCIPAL, dn);
  174.                 authEnv.put(Context.SECURITY_CREDENTIALS, password);
  175.                 try {
  176.                     @SuppressWarnings("unused")
  177.                     DirContext authContext = new InitialDirContext(authEnv);
  178.                    
  179.                     /* At this point we were able to bind with the user so they have good credentials */
  180.                     Logger.info(this, "User "+username+" logged in");
  181.                     return true;
  182.                 } catch(AuthenticationException e) {
  183.                     /* This is bad credentials */
  184.                     Logger.error(this, "User "+username+" bad credentials", e);
  185.                     return false;
  186.                 } catch (NamingException e) {
  187.                     Logger.error(this, "Error trying to login user "+username, e);
  188.                     return false;
  189.                 }
  190.             } else {
  191.                 /* This user does not exist so return false */
  192.                 Logger.error(this, "User "+username+" not found");
  193.                 return false;
  194.             }
  195.         } catch (Exception e) {
  196.             Logger.error(this, "Error while searching LDAP for user "+username, e);
  197.             return false;
  198.         }
  199.        
  200.     }
  201.    
  202.     /**
  203.      * Converts a byte array to a hex string
  204.      *
  205.      * @param data  The Byte Array
  206.      * @return      The Hex String
  207.      */
  208.     private String convertToHex(byte[] data) {
  209.         StringBuffer buf = new StringBuffer();
  210.         for (int i = 0; i < data.length; i++) {
  211.             int halfbyte = (data[i] >>> 4) & 0x0F;
  212.             int two_halfs = 0;
  213.             do {
  214.                 if ((0 <= halfbyte) && (halfbyte <= 9))
  215.                     buf.append((char) ('0' + halfbyte));
  216.                 else
  217.                     buf.append((char) ('a' + (halfbyte - 10)));
  218.                 halfbyte = data[i] & 0x0F;
  219.             } while(two_halfs++ < 1);
  220.         }
  221.         return buf.toString();
  222.     }
  223.  
  224.     /**
  225.      * Creates an MD5 String from the input
  226.      *
  227.      * @param text  The String to create the MD5 From
  228.      * @return      The MD5 String
  229.      */
  230.     private String MD5(String text) {
  231.         MessageDigest md;
  232.         byte[] md5hash = new byte[32];
  233.         try {
  234.             md = MessageDigest.getInstance("MD5");          
  235.             md.update(text.getBytes("iso-8859-1"), 0, text.length());
  236.             md5hash = md.digest();
  237.         } catch(Exception e) {
  238.             Logger.error(this, "Cannot Create an MD5", e);
  239.             return null;
  240.         }
  241.              
  242.         return convertToHex(md5hash);
  243.     }
  244. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement