Working with Trust Managers

As an example, heres a simple URL−based client that can retrieve arbitrary URLs: package javasec.samples.ch14; import java.io.; import java.net.; public class URLClient { public static void mainString[] args throws Exception { URL u = new URLargs[0]; URLConnection uc = u.openConnection ; BufferedReader br = new BufferedReader new InputStreamReaderuc.getInputStream ; String s = br.readLine ; while s = null { System.out.printlns; s = br.readLine ; } } } You can run this code with an HTTP−based URL as follows: piccolo java javasec.samples.ch14.URLClient http:www.sun.com ... lots of output from sun.com ... Similarly, by specifying the appropriate property for the HTTPS protocol handler, you can connect to an HTTPS−based URL: piccolo java \ −Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol \ javasec.samples.ch14.URLClient https:www.sun.com As always, the server sun.com in this case will present its certificate to the client, which must verify it using its truststore. In this case, weve used the default truststore JREHOMElibsecuritycacerts, which contains the root certificate of many CAs including the one used by Sun. If you connect to your own server, you may need to specify the appropriate trustStore property.

14.6.1 Verifying HTTPS Hosts

When we wrote our own SSL client socket code, we had to extract the name from the servers certificate and make sure that it represented the host to which we expected to connect. The HTTPS protocol handler will do that for us automatically, and if the hostnames dont match, an IOException will be thrown when you attempt to get the input or output stream. There are times when this verification is insufficient. If you connect to https:192.18.297.41, the default verification will fail. The certificate presented by that site has an embedded name of www.sun.com, and even though 192.18.297.41 is the correct IP address, the protocol handler will do a string comparison of 192.18.297.41 and www.sun.com and will fail. In cases such as this you may want to look up the IP address of the name in the certificate and see if it matches your target. You may also want to ask the user if its okay to proceed regardless of whether the names match. To handle such situations, you can implement a hostname verifier in order to perform extended hostname verification. Extended hostname verification is used only if the name in the certificate and the hostname in the URL dont match; if the names match, the HTTPS protocol handler does not call the hostname verifier. Hence, a hostname verifier cannot be used to prevent any arbitrary connection.