filter_list

InstallCert and Java 7

Thursday 20.06.2013

When communicating with a server using a self-signed SSL using a Java based client, this custom certificate must be known by the callee side of the communication. This can be done manually by adding the certificate to the client JVM.

To simplify this process, one can use a simple tool called InstallCert as described here and here. This application was originally written for Java 5 / Java 6. While this solution still works, when you try to run this application through Java 7, you will get an additional error message like this:

javax.net.ssl.SSLException: java.lang.UnsupportedOperationException
 at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
 at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
 at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1844)
 at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1827)
 at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1346)
 at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
 at org.vangen.auth.InstallCert.main(InstallCert.java:81)
Caused by: java.lang.UnsupportedOperationException
 at org.vangen.auth.InstallCert$SavingTrustManager.getAcceptedIssuers(InstallCert.java:168)
 at sun.security.ssl.AbstractTrustManagerWrapper.checkAlgorithmConstraints(SSLContextImpl.java:926)
 at sun.security.ssl.AbstractTrustManagerWrapper.checkAdditionalTrust(SSLContextImpl.java:872)
 at sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(SSLContextImpl.java:814)
 at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
 at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
 at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
 at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
 at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
 at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
 at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
 ... 2 more
 

To avoid this error, you will need to change how accepted issuers are returned. The original code threw an exception for this method. The Java 7 implementation calls this method, which was not the case with earlier versions of Java. The solution to this problem is to simply return an empty array like this:


    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
        // throw new UnsupportedOperationException();
    }

By doing this small change, the application will no longer return an error upon execution. The full application code will then be:


package org.vangen.auth;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class InstallCert {

    public static void main(final String[] args) throws Exception {
        String host;
        int port;
        char[] passphrase;
        if ((args.length == 1) || (args.length == 2)) {
            final String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            final String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            System.out.println(
                    "Usage: java InstallCert <host>[:port] [passphrase]");
            return;
        }

        File file = new File("jssecacerts");
        if (file.isFile() == false) {
            final char SEP = File.separatorChar;
            final File dir = new File(System.getProperty("java.home")
                    + SEP + "lib" + SEP + "security");
            file = new File(dir, "jssecacerts");
            if (file.isFile() == false) {
                file = new File(dir, "cacerts");
            }
        }

        System.out.println("Loading KeyStore " + file + "...");
        final InputStream in = new FileInputStream(file);
        final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        final SSLContext context = SSLContext.getInstance("TLS");
        final TrustManagerFactory tmf =
                TrustManagerFactory.getInstance(TrustManagerFactory
                        .getDefaultAlgorithm());
        tmf.init(ks);
        final X509TrustManager defaultTrustManager =
                (X509TrustManager) tmf.getTrustManagers()[0];
        final SavingTrustManager tm = new SavingTrustManager(
                defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        final SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to "
                + host + ":" + port + "...");
        final SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (final SSLException e) {
            System.out.println();
            e.printStackTrace(System.out);
        }

        final X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        final BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        final MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            final X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject "
                    + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.println("Enter certificate to add to trusted keystore"
                + " or 'q' to quit: [1]");
        final String line = reader.readLine().trim();
        int k;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (final NumberFormatException e) {
            System.out.println("KeyStore not changed");
            return;
        }

        final X509Certificate cert = chain[k];
        final String alias = host + "-" + (k + 1);
        ks.setCertificateEntry(alias, cert);

        final OutputStream out = new FileOutputStream(file);
        ks.store(out, passphrase);
        out.close();

        System.out.println();
        System.out.println(cert);
        System.out.println();
        System.out.println(
                "Added certificate to keystore 'cacerts' using alias '"
                        + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(final byte[] bytes) {
        final StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[] chain;

        SavingTrustManager(final X509TrustManager tm) {
            this.tm = tm;
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
            // throw new UnsupportedOperationException();
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] chain,
                final String authType)
                throws CertificateException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] chain,
                final String authType)
                throws CertificateException {
            this.chain = chain;
            this.tm.checkServerTrusted(chain, authType);
        }
    }
}

First published at:
http://infposs.blogspot.no/2013/06/installcert-and-java-7.html

Restlet and Spring integration

Friday 14.06.2013
Restlet supports publication of their services either through a servlet or an indepdendent server out of the box. To better integrate the REST service into a Spring MVC framework, I created some glue to better bind them together. While Restlet supports Spring through their own Spring integration, I wanted to avoid the use of a an another servlet for the Restlet integration. Instead I wanted to use an automatically configured Spring MVC controller. In addition I wanted to use the new Spring JavaConfig for configuring the Spring Beans.

The first step was to create a Spring MVC controller, wrapping REST requests:


@Controller
@RequestMapping("/rest")
public class RestletController {

    @Autowired
    private Restlet root;

    @Autowired
    private Context context;

    private ServletAdapter adapter;

    public RestletController() {
    }

    @PostConstruct
    public final void postConstruct() {
        final Application application = new Application(this.context);
        application.setInboundRoot(this.root);

        this.adapter = new ServletAdapter(new DummyServletContext());
        this.adapter.setNext(application);
    }

    @RequestMapping("/**")
    public final void request(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        this.adapter.service(request, response);
    }
}

This controller sets up the Restlet application when all dependencies has been injected. This happens in the method annotated with a @PostContruct annotation. The ServletAdapter class is normally used in the Restlet servlet, but are here used as a target for forwarding the request and response objects. This will result in requests being handles as if the servlet was configured for the application container.

This application uses Spring JavaConfig for configuring the application, and this is the configuration class for setting up the Restlet environment:


@Configuration
public class RestletConfig {

    @Bean
    public Restlet root() {
        final SpringRouter router = new SpringRouter(this.restletContext());
        router.attach("/users", new SpringFinder() {
            @Override
            public ServerResource create() {
                // lookup-method
                return RestletConfig.this.usersResource();
            }
        });
        router.attach("/users/{domain}/{username}", new SpringFinder() {
            @Override
            public ServerResource create() {
                // lookup-method
                return RestletConfig.this.userResource();
            }
        });

        return router;
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public Context restletContext() {
        return new Context();
    }

    @Bean
    public ServiceSpringSecurityVerifier verifier() {
        return new ServiceSpringSecurityVerifier();
    }

    @Bean
    public UsersResource usersResource() {
        return new UsersResource();
    }

    @Bean
    public UserResource userResource() {
        return new UserResource();
    }
}

This class configures routes for the REST service, and utilizes the Restlet Spring integration to map server resources to Spring beans. For each mapping we can see that the create method looks up beans from the Spring container. By doing this, we are able to utilize injection of dependencies for our server resources.

This is the server resource for list of users:


public class UsersResource extends ServerResource {

    @Autowired
    private UserDao userDao;

    @Get("json")
    public final Representation getUsers() {
        return this.convertCollection(this.userDao.getAll());
    }

    @Post("json")
    public final void addUser(final User user) {
        this.userDao.persist(user);
    }

    private Representation convertCollection(final Collection<?> collection) {
        final JSONArray result = new JSONArray();
        for (final Object bean : collection) {
            result.put(new JSONObject(bean));
        }
        return new JsonRepresentation(result);
    }
}

This class injects a user DAO service, which in turn fetches users from the database. The first method covers the get-scenario for all users. This request should return a list of all known users. This server resource is also used for adding new users through the post-scenario. Unfortunately Restlet does not handle collections, which means that a method will need to be built to convert a collection into a JSONArray object, which in turn is returned as a list.

This is the server resource for single users:


public class UserResource extends ServerResource {

    @Autowired
    private UserDao userDao;

    @Get("json")
    public final Representation getUser() {
        final String userName = (String)
                this.getRequestAttributes().get("username");
        final User user = this.userDao.get(userName);

        if (user != null) {
            return new JsonRepresentation(user);
        } else {
            this.doError(Status.CLIENT_ERROR_NOT_FOUND);
            return null;
        }
    }

    @Put("json")
    public final void updateUser(final User user) {
        this.userDao.persist(user);
    }

    @Delete
    public final void deleteUser() {
        final String userName = (String)
                this.getRequestAttributes().get("username");
        final User user = this.userDao.get(userName);
        if (user != null) {
            this.userDao.delete(user);
        }
    }
}

In the get-scenario for a single user, you get that user if it can be found. If it cannot be found, a standard error should be given. The put-scenario replaces the user selected. The last method covers the delete-scenario, which simply deletes the selected user from the database.

The more observant reader would probably see that the same method is used for both adding and replacing a user. This is intentional, as we want to make is slightly easier to add and replace users. If a user with a given username is found in either of these scenarios, it will be replaced, Otherwise, the user will be added.

First published at:
http://infposs.blogspot.no/2013/06/restlet-and-spring-integration.html

2017

2016

2014

2013

2012

2011

2010

2009

2007

2005

2004

2003

2002

2001