Google

Jun 21, 2014

Password based Encryption and decryption example in Java

Password-Based Encryption is can be accomplished using the PBEParameterSpec class. For example, if you are storing passwords for your database or RESTful web service connections in your properties file, they need to be encrypted and base64 encoded. You can't have clear text passwords lying around in properties files, URLs, or database tables.


Here is a sample CryptoHelper class that make use of PBEParameterSpec to perform password protected encryption and decryption.


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.PBEKeySpec;


public class CryptoHelper {

    // Define the salt
    private static final byte[] SALT = {(byte)0x41, (byte)0x42, (byte)0x43, (byte)0x44,
                                        (byte)0x45, (byte)0x46, (byte)0x47, (byte)0x48}; //A to H

    // Iteration count
    private static final int COUNT          = 20;

    private static final String ALGORITHM   = "PBEWithMD5AndDES";

    // Create PBE parameter set
    private static PBEParameterSpec pbeParamSpec = new PBEParameterSpec(SALT, COUNT);


    /**
     * Not necessary at the moment as all methods are currently static.
     */
    protected CryptoHelper() {
    }


    /**
     * Encrypt a byte buffer using the given password.
     *
     * @param   data        The data to be encrypted.
     * @param   password    The password to be used.
     * @return  An encrypted byte array buffer.
     * @exception   CryptoException     Hmmm, we have a problem.
     * @see #decrypt(byte[],String)
     */
    public static byte[] encrypt(byte[] data, String password)  {
        return doCipher(Cipher.ENCRYPT_MODE, data, password);
    }


    /**
     * Decrypt a byte buffer using the given password.
     *
     * @param   data        The data to be decrypted.
     * @param   password    The password to be used.
     * @return  The original byte array buffer.
     * @exception   CryptoException     Hmmm, we have a problem.
     * @see #encrypt(byte[],String)
     */
    public static byte[] decrypt(byte[] data, String password)  {
        return doCipher(Cipher.DECRYPT_MODE, data, password);
    }


    /**
     * Performs password based encryption/decryption.
     *
     * @param   mode     Encrypt/Decrypt (Cipher.DECRYPT_MODE/Cipher.ENCRYPT_MODE)
     * @param   data     The data to be encrypted/decrypted.
     * @param   password The password to be used.
     * @return  The transformed byte buffer.
     * @exception   CryptoException     Hmmm, we have a problem.
     */
    private static byte[] doCipher(int mode, byte[] data, String password) {
        try {
            // First generate a SecretKey from the password given...
            PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

            // Create PBE Cipher
            Cipher pbeCipher = Cipher.getInstance(ALGORITHM);

            // Initialize PBE Cipher with key and parameters
            pbeCipher.init(mode, pbeKey, pbeParamSpec);

            // Encrypt/Decrypt the data
            return pbeCipher.doFinal(data);
        } catch(Exception ex) {
            throw new RuntimeException("Cryptography Exception: " + ex);
        }
    }
}


The class with the method using the helper class.




//You can use any Base64 encoding library 
import org.eclipse.persistence.internal.oxm.conversion.Base64;

public class CryptographyTest {
 
 public static void main(String[] args) {
   String clearDatabasePassword = "passw0rd";
   String encryptionPasword = "changeit";
   
   byte[] encryptedDatabasePassword = CryptoHelper.encrypt(clearDatabasePassword.getBytes(), 
                                                                      encryptionPasword);
   System.out.println("Encrypted:" + new String(encryptedDatabasePassword));
   
   
   byte[] decryptedDatabasePasswor = CryptoHelper.decrypt(encryptedDatabasePassword, 
                                                                  encryptionPasword);
   System.out.println("Decrypted:" + new String(decryptedDatabasePasswor));
   
   //gives you the readable characters that can be used in your properties file
   System.out.println("Encrypted and Base64 encoded:" + new String(Base64.base64Encode(
                                                            encryptedDatabasePassword)));
     
 }
}



The output is

Encrypted:—¥3urÓ«É |Ã÷ Œ±)
Decrypted:passw0rd
Encrypted and Base64 encoded:l6UzdXLTq8mgfMP3FIyxKQ==


Now, you can have the password stored in common.properties file as shown below

myapp.db.password=l6UzdXLTq8mgfMP3FIyxKQ==

Base64 encoding helps you compactly transport binary data as readable characters.

Labels: ,

May 12, 2014

Understanding service and socket timeouts in Java enterprise applications?

Q. Why is it important to set proper timeout values in your applications?
A. Security and performance.

Security reason: it is often necessary to control how long a Web Service client or other valuable clients invoking valuable resources like database connections, transaction management, etc waits for a response after sending a request. Not setting proper timeouts can be a potential candidate for DoS attacks, especially via web service calls. This is why the application servers provide various timeout configurations to prevent DoS attacks. For example, in application servers

  • The RequestReadTimeout allows to limit the time a client may take to send the request.
  • The TimeOut directive should be lowered on sites that are subject to DoS attacks. Setting this to as low as a few seconds may be appropriate. 
  • The KeepAliveTimeout directive may be also lowered on sites that are subject to DoS attacks. Some sites even turn off the keepalives completely, which has of course other drawbacks on performance.

Performance reason: A common cause of bad Java EE performance for highly distributed systems is due to not properly implementing timeouts causing client threads to get stuck, which can lead to full domino effect. So, it is imperative to test for non-happy path and implement proper service, transaction, and socket timeouts.


Q. Can you give some examples as to how you can set service timeouts?
A. 

1. If you are using Apache HttpClient via Spring, you can set it via the application context file. The timeouts you have set are associated with the time it takes to establish a (socket) connection and the maximum time between establishing a connection and receiving data from the connection. 


<http:conduit name="*.http-conduit">
     <http:tlsClientParameters secureSocketProtocol="TLS" disableCNCheck="true" useHttpsURLConnectionDefaultSslSocketFactory="false">
              <sec:keyManagers keyPassword="${myapp.password}">
                 <sec:keyStore type="JKS" resource="${myapp.keystore}"/>
              </sec:keyManagers>
       </http:tlsClientParameters>
      <http:client ConnectionTimeout="30000" ReceiveTimeout="30000"/>
</http:conduit>


Make the timeout value configurable via a properties file. Don't hard code it.

2. If you want to set it from you Java code

Future<String> future = executor.submit(new Callable<String>() {
    public String call() {
        return webService.executeServiceMethod();
    }
});

try {
    String result = future.get(5, TimeUnit.SECONDS);
    processResult(result);
} catch (TimeoutException ex) {
    retryServiceOrDisplayErrorMessage();
}


Make the timeout value configurable via a properties file. Don't hard code it. Here is a tutorial like example on timeout.


3. Application server configurations. For example, in Weblogic application server the JTA timeout is set via the server console



In Tomcat, via server.xml file

<Connector URIEncoding="UTF-8" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" enableLookups="false" maxHttpHeaderSize="8192" maxSpareThreads="75" maxThreads="150" minSpareThreads="25" port="7777" redirectPort="8443"/>


Most Java framework APIs provide timeout facilities, and make use of it.


Q. How will you go about performing outage testing of your application(s)?
A.

1. Setting up a dummy service to test.  Understanding dynamic proxies in Java with a practical example -- Service retry example
2. SSH tunneling via an SSH client like putty to a real service. Set up an SSH tunnel to the actual service, and then use the tunnel host/port number in the client application. Severe the tunnel connectivity, and see how your client application handles connection disruption.
3. By bringing down the actual service. Also known as the real outage testing. You need to notify other users of the actual service, and book a time for this outage testing to not impact other client applications.



Q. How  will you monitor real service outages of your java applications?
A.

  • Java Management eXtentions (JMX) provides a way for you to connect to remote clients and monitor applications running on a JVM. 
  • Monitoring your Java application infrastructures with Nagios, which provides complete monitoring of Java applications and servers. Nagios Offers effective JMX monitoring.
  • Splunk can monitor your log files to predict behviors and proactively address potential outages


  • Commercial monitoring tools like Tivoli from IBM and SiteScope from HP.



Labels: ,

Sep 9, 2013

Web (i.e. HTTP) security vulnerabilities - HttpOnly attribute

Q. What do you understand by the term "HttpOnly" attribute in HTTP cookies?
A. Here is a sample PEN test report comment:

"During the application test, it was detected that the tested web application set a session cookie without the "HttpOnly" attribute. Since this session cookie does not contain the "HttpOnly" attribute, it might be accessed by a malicous script injected to the site (i.e XSS), and its value can be stolen. Any information stored in session tokens may be stolen and used later for identity theft or user impersonation"

When you tag a cookie with the "HttpOnly" flag, it tells the browser that this particular cookie should only be accessed by the server. Any attempt to access the cookie from client script is strictly forbidden. This will works woth  a modern web browser that supports and actually implements "HttpOnly" functionality correctly. The most modern browsers do support the "HttpOnly" flag. This flag will make more difficult to pull off XSS attacks.


Q. What do you understand by the term "Secure" attribute in HTTP cookies?
A. Here is a sample PEN test report comment:

"During the application test, it was detected that the tested web application set a cookie without the "secure" attribute, during an encrypted session. Since this cookie does not contain the "secure" attribute, it might also be sent to the site during an unencrypted session. Any information such as cookies, session tokens or user credentials that are sent to the server as clear text, may be stolen and used later for identity theft or user impersonation."

Remedy: Basically the only required attribute for the cookie is the "name" field. Common optional attributes are: "comment", "domain", "path", etc. The "secure" and "HttpOnly" attributes must be set accordingly in order to prevent a cookie from being sent unencrypted or modified respectively.

Tip: You can use the Firefox plugin Fire cookie to view these attributes.

Labels:

Jul 16, 2013

Java Security Interview Questions and Answers: Single Sign-On (i.e. SSO) with Spring 3 Security

Q. Can you provide a high level overview of the "access control security" in a recent application you had worked?
A. As shown below, SiteMinder is configured to intercept the calls to authenticate the user. Once the user is authenticated, a HTTP header "SM_USER" is added with the authenticated user name. For example "123". The user header is passed to Spring 3 security. The "Security.jar" is a custom component that knows how to retrieve user roles for a given user like 123 from a database or LDAP server. This custom component is responsible for creating a UserDetails Spring object that contains the roles as authorities. Once you have the authorities or roles for a given user, you can restrict your application URLs and functions to provide proper access control.







Q. What is SSO (i.e. Single Sign-ON)?
A. Single sign-on (SSO) is a session/user authentication process that permits a user to enter one name and password in order to access multiple applications. The process authenticates the user for all the applications they have been given rights to and eliminates further prompts when they switch applications during a particular session. For example, SiteMinder, TivoliAccessManager (i.e. TAM), etc provides SSO. As shown in the diagram above SiteMinder authenticates the user and adds the SM_USER HTTP header to the application. It removes all the "SM" headers and add them after authenticating the user. This prevents amy malicious headers being injected via the browser with plugins like "Firefox Modify headers".


Q. How will you go about implementing authentication and authorization in a web application?
A. Use SSO application like SIteminder or Tivoli Access Manager to authenticate users, and Spring security 3 for authorization as described in the following Spring 3 security tutorials. Spring security pre-authentication scenario assumes that a valid authenticated user is available via  either Single Sign On (SSO) applications like Siteminder, Tivoli, etc or a X509 certification based authentication. The Spring security in this scenario will only be used for authorization. The links to the tutorials below demonstrates this with code.


Q. Can you describe your understanding of SSL, key stores, and trust stores?
A.  SSL, key stores and trust stores


Q. What tools do you use to test your application for security holes?
A. These tests are known as PEN (i.e. penetration) testing or security vulnerability testing. There are tools like
  • SkipFish (web application security scanner) from Google.
  • Tamper data from Firefox. 

Q. What is a two factor authentication?
A. Two-factor authentication is a security process in which the user provides two means of identification. This includes
  • something you have and something you know. For example, a bank card is which something you have and a PIN (i.e. Personal Identification Number) is something you know.
  • two forms of identification like password and a biometric data like finger print or voice print. Some security procedures now require three-factor authentication, which involves possession of a physical token and a password, used in conjunction with biometric data. 
Q. What are the different layers of security?
A.

Application-Layer Security: For example, Spring 3 Security, JAAS (Java Authentication and Authorization) that provides a set of APIs to provide authentication and authorization (aka access control), etc. JAAS provides pluggable and extendable  framework for programmatic user authentication and authorization at the JSE level (NOT JEE level). JAAS provides security at the JVM level (e.g. classes, resources). JAAS is the the core underlying technology for JEE Security. Spring security tackles security at the JEE level (e.g. URLs, Controller methods, service methods, etc)

Transport-Layer Security: Java Secure Sockets Extension (JSSE) provides a framework and an implementation for a Java version of the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols and includes functionality for data encryption, server authentication, message integrity, and optional client authentication to enable secure Internet communications. (TLS) 1.0 / (SSL) 3.0, is the mechanism to provide private, secured and reliable communication over the internet between the client and the server. It is the most widely used protocol that provides HTTPS for internet communications between the client (web browsers) and web servers.

Message-Layer Security: In message-layer security, security information is contained within the SOAP message and/or SOAP message attachment, which allows security information to travel along with the message or attachment. For example, the credit card number is signed by a sender and encrypted for a particular receiver to decrypt. Java Generic Security Services (Java GSS-API) is a token-based API used to securely exchange messages between communicating applications. The GSS-API offers application programmers uniform access to security services on top of a variety of underlying security mechanisms, including Kerberos. The advantage of this over point to point transport layer security is that the security stays with the message over all hops and after the message arrives at its destination. So, it can be used with intermidiaries over multiple hops and protocols (e.g. HTTP, JMS, etc). The major disadvantage is that it is more complex to implement and requires more processing.

Note: Simple Authentication and Security Layer (SASL) is a framework for authentication and data security in Internet protocols.  SASL is an Application-Layer security that supports TLS to compliment the services offered SASL.

Note: The Java security API is complicated and Spring security as demonstrated via the above tutorials might be a better alternative.

Labels: , ,

May 15, 2013

Spring security pre-authentication scenario - Part2

In Part 1, I covered configuring Spring security. Here we will see how we can protect the controller and the service class methods by defining what roles are allowed.


Firstly, you can protect your controller as shown below.


Define the URLs to be protected in the ssoContext.xml file something like

<http auto-config="false" access-decision-manager-ref="springAccessDecisionManager" 
  once-per-request="true" create-session="ifRequired" entry-point-ref="MyAppAuthenticationEntryPoint">
  
  <session-management invalid-session-url="/j_spring_security_logout" />
  <!-- TODO: Would be cleaner if we didn't have to enumerate every role that can access some URL in the system. Consider hierarchical roles -->
  <intercept-url pattern="/**/*.css*" filters="none" />
  <intercept-url pattern="/**/*.js*" filters="none" />
  <intercept-url pattern="/**/*.png*" filters="none" />
  <intercept-url pattern="/**/codemapping.rpc" access="ROLE_admin,ROLE_viewer" /> 
  <intercept-url pattern="/**/generalLedgerService.rpc" access="ROLE_admin" />
  <intercept-url pattern="/**/MyAppAdjustment.html" access="ROLE_admin,ROLE_viewer" />
  <intercept-url pattern="/**/CodeMapping.html" access="ROLE_admin,ROLE_viewer" />
  <intercept-url pattern="/**/myapp_test.html" access="ROLE_admin" />
  <custom-filter ref="siteminderFilter" position="PRE_AUTH_FILTER" />
  <access-denied-handler ref="accessDeniedHandler"/> 
       
        ....    
    
</http>


In the Spring MVC controller, you can use the annotation as shown below.

   @RolesAllowed(
    {
        "ROLE_viewer", "ROLE.standard", "ROLE_senior"
    
    })
    @RequestMapping(value = "/portfolio/{portfoliocd}/details.csv", method = RequestMethod.GET, produces = "text/csv")
    @ResponseBody
    public void getCashForecastCSV(
            @PathVariable(value = "portfoliocd") String portfolioCode,
            @RequestParam(value = "valuationDate", required = true) @DateTimeFormat(pattern = "yyyyMMdd") Date valuationDate,
            HttpServletResponse response) throws Exception
    {
 
 
   //..............................
 
     }
 



The service class methods can be protected by declaring the following in your spring context file where the methods reside.

 <!-- comment this line locally to bypass seurity access control in development. But don't check this in commented as security will be turned off -->
 <security:global-method-security secured-annotations="enabled" pre-post-annotations="enabled" jsr250-annotations="enabled"/>


Once declared, you can protect your service class methods as shown below.

    @RolesAllowed(
    {
        "ROLE_viewer", "ROLE_standard", "ROLE_senior"
    
    })
    @Override
    public ReconciliationResult getReconciliations(ReconciliationCriteria criteria)
    {
    //........................
 }
 


Labels: , ,

May 7, 2013

Spring security pre-authentication scenario - Part1

Spring security pre-authentication scenario assumes that a valid authenticated user is available via  either Single Sign On (SSO) applications like Siteminder, Tivoli, etc or a X509 certification based authentication. The Spring security in this scenario will only be used for authorization.

The example shown below retrieves the user name via the HTTP headers.

Step 1:  The dependency jars that are required.

 <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-core</artifactId>
   <version>3.1.0.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-web</artifactId>
   <version>3.1.0.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-acl</artifactId>
   <version>3.1.0.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-config</artifactId>
   <version>3.1.0.RELEASE</version>
  </dependency>


Step 2: Define the Spring security filter via the web.xml file.

     ....

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/META-INF/spring/applicationContext.xml</param-value>
 </context-param>
 
 
 
 <!-- Spring Security -->
 <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy </filter-class>            
 </filter>
 
 <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/myapp/*</url-pattern>
 </filter-mapping>
 
    ....
 
 


Step 3: The servlet filter configured above will make use of a spring context file like  ssoContext.xml to define the authorization sequences. The ssoContext file can be imported via the applicationContext.xml file bootstrapped via the web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:batch="http://www.springframework.org/schema/batch"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
            http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->

    <context:annotation-config />
    
    <import resource="myServerContext.xml" /> 
 <import resource="security/ssoContext.xml" /> 
    
</beans>


Step 4: The ssoContext.xml is defined below showing how the user can be retrieved from HTTP header SM_USER for site minder and passed to your own implementation to retrieve the roles (aka authorities). All the classes configured below are Spring classes except for the UserDetailsServiceImpl, which is used to retrieve the authorities.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:security="http://www.springframework.org/schema/security"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd  
                      http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">


    <context:component-scan base-package="com.myapp.dao.security" />
    <context:component-scan base-package="com.myapp.model.security" />

 <beans:bean id="springVoter"
  class="org.springframework.security.access.vote.RoleVoter" />
 <beans:bean id="springAccessDecisionManager"
  class="org.springframework.security.access.vote.AffirmativeBased">
  <beans:property name="allowIfAllAbstainDecisions"
   value="false" />
  <beans:property name="decisionVoters">
   <beans:list>
    <beans:ref local="springVoter" />
   </beans:list>
  </beans:property>
 </beans:bean>


    <http auto-config="false"   entry-point-ref="preAuthenticatedProcessingFilterEntryPoint">
      <security:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" />
      <intercept-url pattern="/**/details.csv*" access="ROLE_viewer, ROLE_standard, ROLE_senior" /> 
      <logout logout-url="/j_spring_security_logout" logout-success-url="https://smlogin-dev.myapp.net/siteminderagent/ssologout/Logout.html" invalidate-session="true" /> 
 </http> 
 
 
 <beans:bean id="preAuthenticatedProcessingFilterEntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>

 <beans:bean id="siteminderFilter"
  class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
  <beans:property name="principalRequestHeader" value="SM_USER" />
  <beans:property name="authenticationManager" ref="authenticationManager" />
  <beans:property name="exceptionIfHeaderMissing" value="false" />
 </beans:bean>

 <security:authentication-manager alias="authenticationManager">
  <security:authentication-provider
   ref="preauthAuthProvider" />
 </security:authentication-manager>

 <beans:bean id="preauthAuthProvider"
  class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
  <beans:property name="preAuthenticatedUserDetailsService">
   <beans:bean id="userDetailsServiceWrapper"
    class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
    <beans:property name="userDetailsService" ref="myUserDetailsService" />
   </beans:bean>
  </beans:property>
 </beans:bean>

 <beans:bean id="myUserDetailsService" class="com.myapp.UserDetailsServiceImpl">
  <beans:property name="appCd" value="appName" />
 </beans:bean>
 

</beans:beans>


Step 5: Define the class UserDetailsServiceImpl class that needs to implement the Spring interface UserDetailsService and the required method   "public UserDetails loadUserByUsername(String username)". The returned model object  "UserDetails" is a Spring class as well.

package com.myapp.security;

import java.util.ArrayList;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class UserDetailsServiceImpl implements UserDetailsService 
{
 final static Logger LOG = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
 
 protected String  appCd;
 
 public UserDetailsServiceImpl()  {}

 @Required
 public void setAppCd(String appCd)
 {
  if ( appCd != null && appCd.length() > 0 )
           this.appCd = appCd;
 }
    
    // override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException 
    {
      
         String role = "ROLE_viewer"  ;  //hard coded, in real life retrieved via database or LDAP
         GrantedAuthorityImpl au_impl = new GrantedAuthorityImpl(role);
         Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
         authorities.add(au_impl);
         
         User usr = new User(username, "", true, true, true, true, authorities);
         return usr;
         
    }
}



The part-2 will cover annotating your Java methods and the URLs that intercept the calls to verify the roles (or authorities) returned for a given user against the roles allowed for a method or URL.


Labels: , ,

Nov 21, 2011

Java Interview Q&A on SSL and truststore vs keystore?

Q. What do you understand by the terms trusstores and keystores in Java?

A. You generally need a truststore that points to a file containing trusted certificates, no matter whether you are implementing the server or the client side. You may or may not need a keystore. The keystore points to a file containing private key. You need a keystore if

  • you are implementing the server side of the protocol, or 
  • you are implementing the client side and you need to authenticate yourself to the server. 
The keystore will be used for encrypting/signing some thing with your private key while the trust stores will be used mostly to authenticate remote servers. To create a trust store, follow the steps outlined below.

STEP 1:

The first step is to get hold of the certificates. You could export the certificates from Google chrome or Firefox. If you click the "view site" information in Google Chrome, it's possible to save to file any cert in the chain. In Firefox, you could try something like



Click on "I understand the Risks" and then on "Add exception". You will be getting a screen as shown below.


Click on "Get certificate" and then "View". On the 2nd tab, named "details" you will see an export button to export the certificate.



Save the file as shown above to be imported into your truststore as explained below.

STEP 2:

To create a working truststore, it needs to contain the certs to trust, as well as the certs in the parent chain. You can import certificates with the keytool that ships with Java.

Import parent certificate

keytool -importcert -alias myservices -file mydomain.crt -keystore truststore.jks

import another linked certificate

keytool -importcert -alias coreservices -file mydomain2.crt -keystore truststore.jks

Note: When prompted enter a password and answer yes to trust this certificate.


to view the certificates

keytool -list -keystore truststore.jks


STEP 3:

Use the trust store as shown below.

java -Djavax.net.ssl.trustStore=C:\whatever\truststore.jks  -Djavax.net.ssl.trustStorePassword=changeit 




Q. How do you go about resolving any SSL related installation issues?
A. There are several SSL tools that are available that can help you determine SSL problems and get your servers running SSL properly.

OpenSSL is an open source implementation of the SSL protocol, and by far the most versatile SSL tool.


Q. What is a one-way SSL?
A. One way SSL just means that the server does not validate the identity of the client. The client generates a random key, encrypts it so that only the server can decrypt it, and sends it to the server. The server and client now have a shared secret that can be used to encrypt and validate the communications in both directions.

Labels: ,