Question

Making an https connection

Asked by: imladris

Expert gentlebeings,

I am using the following method (in a Jetty webserver) to exchange information with another webserver:

      String exchMsg(HttpResponse response,StringBuffer sb,boolean sendok)
      {      HttpURLConnection conn=null;
            try
            {      URL address=new URL("https://"+ipxml+":"+portxml);
                  conn=(HttpURLConnection)address.openConnection();
                  if(conn==null)
                  {      Log.warning("error connecting");
                        sendResp(response,"send error!");
                        return(null);
                  }
            } catch(Exception e)
            {      Log.warning("error connecting: "+e);
                  sendResp(response,"send error!");
                  return(null);
            }
            
            try
            {      conn.setRequestMethod("POST");
                  conn.setDoOutput(true);
                  conn.setDoInput(true);
                  conn.connect();
            
                  OutputStream outs=conn.getOutputStream();
                  outs.write(sb.toString().getBytes("ASCII"));
                  outs.flush();
                  outs.close();
            } catch(Exception e)
            {      Log.warning("error sending: "+e);
                  sendResp(response,"send error!");
                  return(null);
            }
            Log.event("SENT to "+ipxml+":"+portxml+" "+sb);
            if(sendok)sendResp(response,"OK");
            
            try
            {      InputStream ins=conn.getInputStream();
                  byte bs[]=new byte[1000];
                  sb=new StringBuffer(1000);
                  int n;
                  do
                  {      if((n=ins.read(bs))!=-1)sb.append(new String(bs,0,n));
                  } while(!sb.toString().endsWith("</Response>"));
                  ins.close();
            } catch(Exception e)
            {      Log.warning("error receiving: "+e);
                  return(null);
            }
            Log.event("RECV "+sb.toString());
            return(sb.toString());
      }

Now, when I was connecting to an unencrypted port, everything worked fine. However, in attempting to get it encrypted, I changed the URL to be https, connected to a different port on their end (that provides an encrypted connection), and now I get an exception in the second try/catch block, presumably at the conn.connect() statement:

08:12:51.921 WARN!! error sending: java.net.ConnectException: Connection timed out: connect

The guys at the other end indicate that I am not processing their public key, and that they don't have provision for processing a public key from us (not that I was intending to provide one), and they are getting a handshake exception:

HTTPRequestHandler.getRequestLine()javax.net.ssl.SSLHandshakeException:

Received fatal alert: certificate_unknown (HTTP Request handler) 2005-09-30 14:36:57,073 [HTTPRequest.java] DEBUG - Data has not been sent from another process, sending data... (HTTP Request handler) 2005-09-30 14:36:57,074 [HTTPResponse.java] DEBUG - Status code 400 (HTTP Request handler) 2005-09-30 14:36:57,074 [HTTPResponse.java] DEBUG - Sending standard request (HTTP Request handler) 2005-09-30 14:36:57,074 [HTTPResponse.java] DEBUG - Checking security, authorization string null (HTTP Request handler) 2005-09-30 14:36:57,075 [HTTPConst.java] DEBUG - Encoding URL: /~HTTPServerImages/notvalid.gif (HTTP Request handler) 2005-09-30 14:36:57,075 [HTTPConst.java] DEBUG - URL encoded /~HTTPServerImages/notvalid.gif (HTTP Request handler) 2005-09-30 14:36:57,076 [HTTPResponse.java] WARN - IOException:

HTTPResponse.send()javax.net.ssl.SSLException: Connection has been

shutdown: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown (HTTP Request handler) 2005-09-30 14:36:57,076


What must I do/add to get this to work?

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-09-30 at 08:33:06ID21579895
Tags

connection

Topic

Java Programming Language

Participating Experts
4
Points
300
Comments
24

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. Unencrypting files from a different user account
    Here are some details to help understand what is happening: Dual partition, with Windows XP Pro and NTFS on both partitions c:\windows - Origional XP installation directory (corrupt) c:\winnt - New XP installation directory (working) myname - User account that created the ...
  2. URLConnection and IOException?
    Hi, In my application I am connecting to URL, and getting Input Stream. It works fine at local testing server. But it doesn't work at Client side server(Real-IP). The underlaying os is linux. It connects, but while getting input stream, it throws IOException. Is this a probl...
  3. How to Change From Unencrypted Connection String Pass…
    I currently have a site where the Web.Config file has a SQLServer connection string containing an unencrypted password. I would like to change it to be encrypted. What steps do I complete to make the conversion without messing up the connection?

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: CEHJPosted on 2005-09-30 at 08:35:32ID: 14993297

Try

URLConnection conn=address.openConnection();

and then cast as per conn's type

 

by: CEHJPosted on 2005-09-30 at 08:36:44ID: 14993305

Forget that ;-)

 

by: CEHJPosted on 2005-09-30 at 08:40:58ID: 14993344

What version of Java is Jetty running on?

 

by: praveen_koduPosted on 2005-09-30 at 09:46:55ID: 14993936

Try using javax.net.ssl.HttpsURLConnection available from JDK 1.4 onwards, I think.

 

by: girionisPosted on 2005-09-30 at 10:03:10ID: 14994055

> What must I do/add to get this to work?

You need the proper key to connect to the server and from the error message you are getting it seems to me that the server does not recognize your client. In order to connect to a secure server (https) it is not only enough to just change the url from http to https but you also need a proper certificate. Make sure that you have a certificate that the server you are trying to connect to recognizes. If you do not know what this is get in touch with the people who provided you with the keystore.

Basically what is going on is that you are trying to exchange key information with the server and the information you send and the information that the server has does not match.

You can have a look at this link to get an idea of how things work: http://www.andrew.cmu.edu/~mm6/95-733/PowerPoint/SSL.ppt

 

by: imladrisPosted on 2005-09-30 at 11:06:37ID: 14994667

CEHJ: Jetty is running on 1.4.2_06

praveen: As the URL.openConnection method will return an appropriate object, which in this case will be an HttpURLConnection object or something derived from it, and since I am only using methods defined in HttpURLConnection, and since the cast worked, I can see no reason for making the cast more specific.

girionis: I was not (rightly or wrongly) provided with a keystore. Doesn't some "automatic" mechanism exist to manage this stuff? When I go to look at a secure site with my web browser I don't have to first have the web owners "provide me with a keystore". The browser does some stuff, obtains a certificate (I assume this is something that contains the public key of the entity one is trying to connect to), holds it up to the browser user for inspection in a dialog, and then (if the user OK's it) everything proceeds.

 

by: girionisPosted on 2005-09-30 at 11:45:44ID: 14994987

Many of the common browser already implement support for https which allows access to secured communications without requiring the socket-level API provided with JSSE, but there are also cases where you are prompted with a pop up box that informs you if you want to accept the certificate.

Try this approach: http://javaalmanac.com/egs/javax.net.ssl/TrustAll.html and tell us if it makes any difference.

 

by: matthewdflemingPosted on 2005-09-30 at 12:07:17ID: 14995144

I always say this but use the jakarta http client.. it already has the SSL stuff figured out and will save you many headaches..
http://jakarta.apache.org/commons/httpclient/tutorial.html

 

by: praveen_koduPosted on 2005-09-30 at 12:42:57ID: 14995431

imladris: the standard java.net.URL class doesn't support SSL. SSL involves encrypting the stream with PKCS, which involves a handshake to be established between the client and the server to exchange certificates/keys for the encryption. During the connection, the client and server exchange credentials and negotiate the security parameters.
You would have to install the public key certificate on the client(jetty webserver) of the host(server, "https://"+ipxml) you're establishing the connection with.
I totally agree with girionis's perception. the "automatic" mechanism exists for web browsers, which would prompt whether you want to install the certificate, but for programmatic JSSE connections, the certificate needs to be installed and valid before the connection can be made.

 

by: praveen_koduPosted on 2005-09-30 at 12:50:35ID: 14995504


http://www.onjava.com/pub/a/onjava/2001/05/03/java_security.html looks like a pretty good introduction to me.

 

by: imladrisPosted on 2005-10-03 at 13:42:05ID: 15009712

girionis: just completed the trustall approach with no apparent effect. I added the following to the end of the my jetty HttpHandler:

            TrustManager[] trustAllCerts=new TrustManager[]
            {      new X509TrustManager()
                  {      public java.security.cert.X509Certificate[] getAcceptedIssuers()
                        {      return(null);
                        }
                        public void checkClientTrusted(java.security.cert.X509Certificate[] certs,String authType)
                        {
                        }
                        public void checkServerTrusted(java.security.cert.X509Certificate[] certs,String authType)
                        {
                        }
                  }
            };
            
            try
            {      SSLContext sc=SSLContext.getInstance("SSL");
                  sc.init(null,trustAllCerts,new java.security.SecureRandom());
                  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            } catch(Exception e)
            {
            }


Also, I assume that what I would be losing with this approach is the assurance that I am talking to the correct host. I don't know whether that will be acceptable in the long run or not. I guess I'll try talking to the guys on the other side and see about getting a certificate from them.

 

by: matthewdflemingPosted on 2005-10-03 at 13:43:12ID: 15009722

Seriously try the jakarta client.. you will be running https in no time..

 

by: imladrisPosted on 2005-10-03 at 15:26:47ID: 15010419

How would the jakarta client handle the situation where I don't have a certificate stored?

 

by: matthewdflemingPosted on 2005-10-04 at 06:38:57ID: 15013709

You don't need to do anything.. the httpclient acts just like a browser. Can you connect to their site using a browser?  If so using a java "browser" like httpclient will work in a similar fashion.  If you connect to their site and you get an untrusted popup asking you to trust they cert signer (e.g. it isn't verisign, thawte, etc), httpclient can handle these scenarios as well.

 

by: imladrisPosted on 2005-10-07 at 11:21:01ID: 15040869

Investigation continues.

I have requested coding help from the guys on the other end; but they don't appear to see any problems with the code. It appears, in retrospect, that the other end is not an existing, performing, commercial site, yet, either. They listed a new ip and set of ports and requested I try those. Without the trustall code I got this exception: "javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found", which seems reasonable. With the trustall code I get: "javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?".

Does that suggest any useful action to take?

They will also be looking at the logs on their side.

Mathew, I will keep the httpClient in mind. I would prefer to not get involved in yet another license (no matter how mild) if I can avoid it. But I'll try it next week sometime if there isn't any progress.

 

by: matthewdflemingPosted on 2005-10-07 at 11:26:57ID: 15040909

The key here is to figure out which side the problem is on.. To do that I would use a process of elimination.. First things first.. which side is having the problem client or server?

To eliminate the server.. use a known client:
Have you tried accessing the site via a browser?  If so, what kind of warnings to you get?  Is the server cert signed by a known CA?

Next move down a layer to java:
Try the httpClient, is that it is a well tested and frequently used client and see if it works.. If it does and you don't want to use the apache license.. you can at least download the source code to see where your code isn't up to muster.

 

by: imladrisPosted on 2005-10-14 at 15:15:15ID: 15089347

Investigation continues to continue.

Latest error I get back from the other side is:

java.io.IOException: HTTPS hostname wrong: should be <xxx.xxx.xxx.xxx>

between the angle brackets is the ip that I was using to reach it.
Girionis, does that suggest any useful action to take?


Mathew,

If I access the address with https://<ip>:port, then I first get the dialog indicating I am about to view pages over a secure connection, then I hit OK and it comes up with a Security Alert dialog asking me if I want to trust the certificate. If I proceed it then comes up with a dialog indicating there is both secure and nonsecure content on the page. When I indicate that YES I want to see the nonsecure items too, I get a page with an Error 403: Access forbidden; it is impossible to view this page. It is not accessible from this service.

I remain convinced that the standard Java tools ought to work. However, since I'm not getting anywhere, I took the plunge on setting up a parallel project with the Apache client. I won't bore with what it took to find the various pieces and figure out how to run them. Since the tutorial is for 3.0, I am running the 3.0 client which is from 3 days ago (11 Oct 2005) (Yikes!). Once I got it compiled it worked with http without any trouble.

However, setting the address to https got me the old

"HttpClient exception e: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found"

and I got that, even if I added girionis's TrustAll dodge. I assume, in retrospect, that code won't affect the internals of how the HttpClient operates. It's resetting something in HttpsURLConnection.

Here is the Apache version for the exchMsg method:

      String exchMsg(HttpResponse response,StringBuffer sb,boolean sendok)
      {      String postrsp=null;
            boolean scs=true;
            HttpClient client=new HttpClient();
            PostMethod post=new PostMethod("https://"+ipxml+":"+portxml);
            post.setRequestEntity(new StringRequestEntity(sb.toString()));
            try
            {      int retcode=client.executeMethod(post);
                  if(retcode!=HttpStatus.SC_OK)
                  {      Log.warning("error Posting: "+post.getStatusLine());
                        scs=false;
                  }
                  if(sendok)sendResp(response,"OK");
                  postrsp=post.getResponseBodyAsString();
            } catch(IOException e)
            {      Log.warning("HttpClient exception e: "+e);
                  scs=false;
            }
            if(scs)Log.event("RECV "+postrsp);
            else sendResp(response,"error");
            return(postrsp);
      }

What would you suggest as a next step?

OK, so much for this week. I'm off for the weekend. Back at it on Monday.

 

by: girionisPosted on 2005-10-15 at 02:56:49ID: 15090768

> java.io.IOException: HTTPS hostname wrong: should be <xxx.xxx.xxx.xxx>

Try this: http://forum.java.sun.com/thread.jspa?threadID=521779&tstart=75

 

by: matthewdflemingPosted on 2005-10-15 at 07:02:28ID: 15091297

Ok here are your problems then. ...
>>asking me if I want to trust the certificate
and
>>Error 403: Access forbidden;

The first issue is that the CA that the server side folks used to sign their cert is not one of the few automagically trusted CAs.. they probably used a self-signed cert.  So you will need to import that certificate into your truststore before any java app will accept the cert.. this is analagous to you pushing OK from your browser.  
OR
using the apache http client you can use the EasySSLSocketProtocolFactory (http://jakarta.apache.org/commons/httpclient/sslguide.html) and have the client accept unknown CAs.  You probably don't want to do this in real production as it could be a security risk.. the site should get a real signed cert.

The 403 will give you problems no matter which client you attempt to use so that will need to be resolved on the server side to work properly.  You should be able to hit the server with your browser in any event without error.

 

by: imladrisPosted on 2005-11-07 at 08:02:41ID: 15239802

Update: still working on this. Unfortunately there was a company move last week, so I didn't get anything done while the network was being taken down, moved, and set back up at the new location. I had to move to of course, and by the time I was up and running again, the company network was up, but then I had to get them to poke holes in the firewall again so I could continue testing this. Hopefully some new results in the next week or so.

 

by: imladrisPosted on 2005-11-18 at 07:49:23ID: 15320409

Another update: I think I got a connection using girionis's dodges. I didn't get a sensible response though. Still working on it.

 

by: girionisPosted on 2005-11-19 at 06:59:17ID: 15325923

What was the response?

 

by: imladrisPosted on 2005-11-30 at 09:48:22ID: 15390111

Something about not being able to parse.

They requested another attempt this morning, and this time I got the same response as I did on the HTTP link. So it looks like we're underway. I specifically attempted to remove both of girionis's dodges one at a time. But both are necessary to make this work.

Thanks girionis.

I explicitly raised the issue with them, that I am bypassing the checks on whether the software is connecting to the right host, but, so far, they seem unconcerned. I assume that the problem is that something along the following lines could occur: if someone could access the PC running this code and change the configuration to point it to another ip, they could fire up a program on that ip that receives the requests, records the information, passes the request to 3C, and passes back the response. That is, despite the fact that the traffic is encrypted, a single configuration change would enable someone to gain access to all the traffic from a particular site. Is that right? Is there something worse that you could think of happening?

 

by: girionisPosted on 2005-11-30 at 11:28:01ID: 15390825

Thank you for accepting, glad I was of help :)

>  Is that right? Is there something worse that you could think of happening?

Yes it could happen, but if this happens on the other side (the receiving end) than it shouldn't be your problem.

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...