Question

Need Help with solving SSL mutual authentication

Asked by: dhulipala


Hi i have a servlet that is deployed on tomcat designed to communicate with server written as a plain java class. Both servlet and server are to communicate using SSL mutual authentication.

When i am running server on port 9000

Server starting...
Server started on port 9000
Waiting for clients...
Connected.  Cipher Suite: Unknown 0x0:0x0
Request from client received...
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHands
hakeException: Received fatal alert: certificate_unknown

And the servlet running on the tomcat is giving this exception:

javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found


Both servlet and server exchange certificates for authentication. I am creating certificates using OpenSSL.These are the steps i am following to create keystore and truststore on both sides:

1. creating a server keystore:
 
 keytool -genkey -alias server -keystore server_keystore
2. creating a client keystore

 keytool -genkey -alias client -keystore client_keystore

3. creating cert requests from both the keystores

4. create a 1024-bit private key to use when creating  CA.:

C:\ssl>openssl genrsa -des3 -out keys/ca.key 1024

5.create a master certificate based on this key, to use when signing other certificates:

C:\ssl>openssl req -config openssl.conf -new -x509 -days 1001 -key keys/ca.key -out certs/ca.cer

6.Sign both the requests as follows:

C:\ssl>openssl ca -policy policy_anything -config openssl.conf -cert certs/ca.cer -in requests/certreq.txt -keyfile keys/ca.key -days 360 -out certs/iis.cer

7.Converting  the signed certificate into x509 format for use with IIS:(for both the client and server request certs)

C:\ssl>openssl x509 -in certs/iis.cer -out certs/iisx509.cer

8. storing the signed server cert in server keystore and client truststore using keytool import

9. storing the signed client cert in client keystore and server truststore using keytool import.

Placing the client keystore and truststore in tomcat  and placing the server keystore and truststore in folder where server is running.

By seeing the steps mentioned above am i  missing anything. Please suggest me solution this is very urgent









This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-10-08 at 20:19:33ID21588635
Tags

mutual

,

authentication

Topics

Java Programming Language

,

Java Servlets

Participating Experts
2
Points
0
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. tomcat - SSL only for few servlets
    I have a web application (tomcat container). I have some servlets (eg. Servl1, Servl2, Servl3) providing GUI for the user. I have also some servlets (HS1, HS2,...) providing some services via http requests. All servlets are running under the same context (it's only one web ap...
  2. Jetty SSL not working with cert that works in Tomcat
    I have an application that comes bundled with a Jetty server but does not use SSL by default. The vendor does provide a self-signed certificate and commented-out <Call name="addConnector"> section in jetty.xml to enable the secure port and this works fine aft...
  3. SSL Certificate on IIS + Tomcat
    Hi, I am currently managing a website with IIS + Tomcat combination. I am currently tasked to install SSL which I have never done before. 1. Does it mean that I need to go to 3rd party company i.e. thawte or verisign to purchase my SSL certificate? Is the certificate in fil...
  4. Setup SSL Mutual Authentication
    I am trying to setup SSL Mutual Authentication in IIS. When I try to access ny method of the web service on Server side, passing client certificate it throws Forbidden 403 error. Please let me know how to setup it in IIS.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: dhulipalaPosted on 2005-10-09 at 13:00:07ID: 15048688

Anybody please it is very urgent.

Thanks,
ravi

 

by: matthewdflemingPosted on 2005-10-10 at 07:00:08ID: 15052242

Are the client and server using http(s) to communicate with one another?  If not, can you post the client code and the server code? Have you gotten the client and server to work without SSLSockets?

 

by: dhulipalaPosted on 2005-10-10 at 07:06:09ID: 15052289

Both Servlet client and server are involved in SSL mutual authentication

Servlet Client code:

import java.io.InputStream;

import java.io.IOException;

import java.io.DataInputStream;

import java.io.FileInputStream;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SSLSecretNumberServletWithServerAndClientAuth

   extends HttpServlet

{

   private String server;

   private int port;


   public void init(ServletConfig config)

      throws ServletException

   {

      super.init(config);



      try

      {

         port = (new Integer(getInitParameter("port"))).

            intValue();

      }

      catch (NumberFormatException nfe)

      {

         log("port must be a parsable integer");

         throw new ServletException(nfe.getMessage());

      }



      String server = getInitParameter("server");

   }



   /**

    * Opens a secure socket connection with the external

    * server, retrieves the secret number generated from

    * the external server, and communicates it to the

    * client. This method is executed each time a client

    * invokes the servlet.

    *

    * @param request an HttpServletRequest object

    *        containing information about the client's

    *        request.

    * @param response an HttpServletResponse object in

    *        which the servlet stores information to be

    *        sent to the client.

    * @throws ServletException if an exception occurs that

    *         interferes with the servlet's normal

    *         operation.

    * @throws IOException if an I/O exception occurs.

    */

   public void service(HttpServletRequest request,

      HttpServletResponse response)

      throws ServletException, IOException

   {

      log("Requesting connection from " + server +

         " on port " + port + "...");



      // The truststore and keystore passwords are

      // both hardcoded

      char[] passwd = "xyz123".toCharArray();

      char[] passwd2 = "client123".toCharArray();



      SSLSocket s = null;



      try

      {

         // Create an SSLContext instance implementing

         // the TLS protocol.

         SSLContext ctx = SSLContext.getInstance("TLS");

         // Create a TrustManagerFactory implementing the

         // X.509 key management algorithm.

         TrustManagerFactory tmf =

            TrustManagerFactory.getInstance("IbmX509");



         // Create a KeyStore instance implementing the

         // Java KeyStore (JKS) algorithm.

         KeyStore ks = KeyStore.getInstance("JKS");



         // Load the KeyStore file keyStoreFile.

         ks.load(new

            FileInputStream("trustStoreFile"), passwd);



         // Initialize the TrustManagerFactory object with

         // the KeyStore.

         tmf.init(ks);



         // Since the server requires client authentication

         // the client must present its own certificate to

         // the server.



         // Create a KeyManagerFactory implementing the

         // X.509 key management algorithm.

         KeyManagerFactory kmf =

            KeyManagerFactory.getInstance("IbmX509");



         // Create a KeyStore instance implementing the

         // Java KeyStore (JKS) algorithm.

         KeyStore ks2 = KeyStore.getInstance("JKS");



         //  Load the KeyStore file keyClientStore

         ks2.load(new FileInputStream("keyClientStore"),

            passwd2);



         // Initialize the KeyManagerFactory object with

         // the KeyStore.

         kmf.init(ks2, passwd2);



         // Initialize the SSLContext with the

         // KeyManagerFactory and TrustManagerFactory.

         ctx.init(kmf.getKeyManagers(),

            tmf.getTrustManagers(), null);



         // Create an SSLSocketFactory instance from the

         // SSLContext and generate an SSLSocket from it.

         SSLSocketFactory sslFact = ctx.getSocketFactory();

         s = (SSLSocket) sslFact.createSocket

            (server, port);

      }

      catch (Exception e)

      {

         // Catch any Exception and turn it into a

         // ServletException

         throw new ServletException(e.getMessage());

      }



      SSLSession session = s.getSession();

      log("Connected to server " + server + "\nCipher suite:"

         + session.getCipherSuite());



      // Get the secret number from the external server.

      InputStream in = s.getInputStream();

      DataInputStream dis = new DataInputStream(in);

      int secretNumber = dis.readInt();



      // Send the response to the client in HTML format.

      ServletOutputStream out = response.getOutputStream();

      response.setContentType("text/html");

      out.println("<HTML><HEAD><TITLE>" +

         "Secret Number Page</TITLE></HEAD></HTML>");

      out.println("<BODY><H1>Secret Number: " +

         secretNumber + "</H1></BODY>");

      out.println("</HTML>");

      dis.close();

      in.close();

      s.close();

   }

}


Server code:

import java.io.OutputStream;

import java.io.IOException;

import java.io.DataOutputStream;

import java.io.FileInputStream;



import java.util.Random;



import javax.net.ssl.SSLSocket;

import javax.net.ssl.SSLSession;

import javax.net.ssl.SSLServerSocket;

import javax.net.ssl.SSLServerSocketFactory;

import javax.net.ssl.SSLContext;

import javax.net.ssl.KeyManagerFactory;

import javax.net.ssl.TrustManagerFactory;



import java.security.KeyStore;



/**

 * Server class for random number generation. This server

 * runs as a process that external client applications can

 * contact by opening an appropriate socket. Every time a

 * client contacts the server application, a new Thread is

 * generated. The server application produces a new random

 * number, communicates it to the client, and closes the

 * connection with the client. The communication between

 * the server and client is protected by SSL. This server

 * supports server authentication and requires client

 * authentication.

 */

public class SSLServerWithServerAndClientAuth extends Thread

{

   private SSLSocket client;

   private static Random randomGenerator = new Random();



   /**

    * Public constructor. Initializes the server by setting

    * the Socket to communicate with the client.

    *

    * @param client an SSLSocket object representing the

    *       client application this server is

    *       communicating with.

    */

   public SSLServerWithServerAndClientAuth(SSLSocket c)

   {

      this.client = c;

   }



   /**

    * Generates a random number and communicates it to the

    * the client. The communication is protected by SSL.

    */

   public void run()

   {

      int secretNumber = randomGenerator.nextInt();

      System.out.println("Secret Number:" + secretNumber);



      try

      {

         OutputStream out = client.getOutputStream();

         DataOutputStream dos = new DataOutputStream(out);

         dos.writeInt(secretNumber);

         dos.flush();

         dos.close();

         out.close();

         client.close();

      }

      catch (IOException e)

      {

         System.out.println(e);

      }

   }

   /**

    * Launches the server application. This method expects

    * the port number to be passed on the command line.

    *

    * @param args a String[] array whose first element

    *       must represent the port number this server

    *       will be listening on. The port number is

    *       expected to be an integer between 1025 and

    *       65536. Values not in this range will cause the

    *       application to quit.

    */

   public static void main(String args[])

   {

      if (args.length == 0)

      {

         System.out.println("Usage: java Server <port>");

         System.exit(0);

      }



      int port = 0;



      try

      {

         port = (new Integer(args[0])).intValue();

      }

      catch (NumberFormatException nfe)

      {

         System.out.println("Usage: java Server <port>");

         System.out.println

            ("<port> must be a parsable integer");

         System.exit(0);

      }



      if (port <= 1024 || port > 65536)

      {

         System.out.println("Usage: java Server <port>");

         System.out.println

            ("<port> must be an integer in the range " +

            "1025-65536");

         System.exit(0);

      }



      // The keystore and truststore passwords are

      // both hardcoded

      char[] passwd = "abc123".toCharArray();

      char[] passwd2 = "trust123".toCharArray();



      SSLContext ctx = null;



      try

      {

         // Create an SSLContext instance implementing

         // the TLS protocol.

         ctx = SSLContext.getInstance("TLS");



         // Create a KeyManagerFactory implementing the

         // X.509 key management algorithm.

         KeyManagerFactory kmf =

            KeyManagerFactory.getInstance("IbmX509");



         // Open up the KeyStore in order to present the

         // Server's certificates to the client

         KeyStore ks = KeyStore.getInstance("JKS");



         // Load the KeyStore file keyStoreFile

         ks.load (new FileInputStream("keyStoreFile"),

            passwd);



         // Initialize the KeyManagerFactory object with

         // the KeyStore.

         kmf.init(ks, passwd);



         // Create a TrustManagerFactory implementing the

         // X.509 key management algorithm.

         TrustManagerFactory tmf =

            TrustManagerFactory.getInstance("IbmX509");



         // Since client authentication will be requested,

         // the server must be able to trust the client.

         KeyStore ts = KeyStore.getInstance("JKS");

         ts.load (new FileInputStream("trustServerStore"),

            passwd2);



         // Initialize the TrustManagerFactory object with

         // the TrustStore

         tmf.init(ts);

         // Initialize the SSLContext with the

         // KeyManagerFactory and TrustManagerFactory

         ctx.init(kmf.getKeyManagers(),

            tmf.getTrustManagers(), null);



      }

      catch (Exception e)

      {

         System.out.println

            ("Unable to initialize SSLContext " +

            e.getMessage());

         System.exit(0);

      }



      System.out.println("Server starting...");



      // Create an SSLServerSocketFactory instance from the

      // SSLContext and generate an SSLServerSocket from it.



      SSLServerSocketFactory sslSrvFact =

         ctx.getServerSocketFactory();

      SSLServerSocket ss = null;



      // Try to start the server. At this point, problems

      // may arise if another process is already listening

      // on the selected port.

      try

      {

         ss = (SSLServerSocket)

            sslSrvFact.createServerSocket(port);



         // Require client authentication

         ss.setNeedClientAuth(true);

      }

      catch (IOException ioe)

      {

         System.out.println

            ("There is already a server running on port "

            + port + "\n" + ioe);

         System.exit(0);

      }



      System.out.println("Server started on port " + port);

      System.out.println("Waiting for clients...");



      // Start an endless loop in which the server is

      // constantly waiting for clients to connect.

      while (true)

      {

         SSLSocket client = null;



         try

         {

            client = (SSLSocket)ss.accept();

            SSLSession session = client.getSession();

            System.out.println("Connected.  Cipher Suite: " +

               session.getCipherSuite());

         }

         catch (IOException ioe)

         {

            System.out.println("Unable to accept " +

               "connection from client\n" + ioe);

            System.exit(0);

         }



         System.out.println

            ("Request from client received...");

         SSLServerWithServerAndClientAuth server =

            new SSLServerWithServerAndClientAuth(client);

         server.start();

      }

   }

}




 

by: matthewdflemingPosted on 2005-10-10 at 07:09:43ID: 15052332

Okay first things first, does it work without the SSL?

 

by: dhulipalaPosted on 2005-10-10 at 07:13:25ID: 15052359

I didnt get your point. The error says that client (SERVLET) is connecting to server but Handshaking  failed .

thanks,
ravi

 

by: matthewdflemingPosted on 2005-10-10 at 07:16:30ID: 15052377

Well can you make your program run without using SSL encryption.. just use a regular socket.  Once you get a normal socket working then we can start adding the SSL stuff one at a time.  I just want to make sure that the program runs properly without SSL first.

 

by: matthewdflemingPosted on 2005-10-10 at 07:33:22ID: 15052510

After you verify the proggie works sans SSL, I would next implement the "standard" SSL protocol (instead of TLS and the IBM/JKS stuff).  You should only need keytool to get this done..

Just out of curiosity, why aren't you using regular https and using a java httpclient as the client and a servlet as the server?

 

by: dhulipalaPosted on 2005-10-10 at 09:15:38ID: 15053264

Hi it worked for me.. finally!!! The SSL mutual authentication works as desired.

thanks

 

by: matthewdflemingPosted on 2005-10-10 at 09:16:58ID: 15053277

What did you change?

 

by: dhulipalaPosted on 2005-10-10 at 09:21:11ID: 15053310

Nothing it is the problem with the certificates. The problem that i was getting before is due to client not trusting the CA that signed server cert.

 

by: matthewdflemingPosted on 2005-10-10 at 09:23:11ID: 15053325

That'll definitely do it.. glad everything is working

 

by: Computer101Posted on 2006-01-02 at 05:46:14ID: 15591127

PAQed with points refunded (500)

Computer101
EE Admin

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...