Creating Java keystore from existing private key and certificate

With the bunch of programming codes and programs found on the Web this days, Code Signing Certificates are fact and necessity. But the people who are end-users or developers are still in process of adjusting the awareness what programs/scripts/code are safe and junk free and should be trusted before running them on local machine. With this little guide I want to help new people which are diving into this area of problems.

Different platforms offer different way for code signing their apps , and in this post I will focus just on Java based systems.

Java web and desktop apps are bound with keystore files that keep the certificate chains signed by Internet authorities. With this technique it is easy to make distinction from trusted to untrusted programs with investment of some time and money.

Generally the process of creating Java keystore that can sign applications(source codes) can be covered in couple of steps that include the client and the certificate issuer:

  1. The client creates keystore file and generates private and public key pair
  2. The client exports Code Signing Request from the keys with personal and trustworthy data
  3. The client sends the CSR to Certificate issuer and waits for approval. Normally it is contacted during pending time.
  4. Certificate Issuer sends to the client the signed certificate and probably additional intermediate/root chain certificates that need to be included into the keystore.
  5. The client imports the certificate (probably in pkcs7 format) into the original keystore that was used to generate the keys and CSR with the appropriate alias that was used during the creation of the keystore.
  6. The keystore is included in Java applications and referenced with the alias so to sign the JARs used in the apps.

However it can happen the client to receive private key that ought to be used, without previously creating a valid keystore and generating key pair within it. This received key was used for generating CSR and certificate request was already sent to authority.

Well at this point it gets confusing what is the next step that should be taken and is it possible this key to be used for creating a new keystore? Some will say it is not possible (and seems logical because keytool doesn’t allow it), you will need to create new keystore and generate key pair  and issue a new certificate request with the CSR exported from this keystore key pair. That’s not true though, there is always a way.

Let’s suppose the original request has been approved and you received valid certificate cert.crt. At this point you have private.key and trusted cert.crt.

This files need to be merged and exported into pkcs12 format with the help of libssl library.

openssl pkcs12 -export -in cert.crt -inkey private.key -certfile cert.crt -name <certificate(alias)_name> -out keystore.p12

Next this new generated keystore.p12 should be used to create new keystore in JKS format with the help of keytool from the JDK.

keytool -importkeystore -srckeystore keystore.p12 -srcstoretype pkcs12 -destkeystore keystore.jks -deststoretype JKS
And that’s it voila! We have created keystore in jks format from existing private key.

After we have the keystore needed it is easy to import new certificates if required. Example:

keytool -import -trustcacerts -alias <alias(certificate)_name> -keystore keystore.jks -file <certificate_filename>

That’s it, three commands that will make your life easier.

SkeletorLead

Cheers,

Igor

Setting Up Context in Apache Tomcat for Serving Static Files

The intro:

So I’ve heard you want to serve static files from your Tomcat Web App in a way that they won’t be deleted on WAR redeploy or Tomcat restarted?

You have a solution, and that is mapping a custom Context in your Apache Tomcat server.xml .

The scenario :

You have a site that allows users to upload images that are public,shared and not under a hood of some security filter. The most intuitive solution is to put them in some directory i.e. ‘uploads’ , but then you realize that the things in the exploded WAR rewrite on redeploy or if the war is in the webapps directory on Tomcat restart. (you can change this behaviour)

The solution is simple: save the files to some directory outside of the war (something like ‘/usr/share/tomcat/uploads’) and map that directory on the server context of your Tomcat AS (something like http://lesite:8080/uploads).

With workaround like this you will see your uploaded cute kitty picture like this: http://lesite:8080/uploads/kitty.jpg

The implementation:

Let’s use the same examples. The mapping is done in <CATALINA_HOME>/conf/server.xml (hopes you know what and where catalina_home is )

This is default situation on new Tomcat install (a snippet from sever.xml):

<Host name=”localhost” appBase=”webapps” unpackWARs=”true” autoDeploy=”true”>

<Valve className=”org.apache.catalina.valves.AccessLogValve” directory=”logs”
prefix=”localhost_access_log.” suffix=”.txt”
pattern=”%h %l %u %t &quot;%r&quot; %s %b” />

</Host>

But we want to change that in this:

<Host name=”localhost” appBase=”webapps” unpackWARs=”true” autoDeploy=”true”>

<Context docBase="/usr/share/tomcat/uploads" path="/uploads" />

<Valve className=”org.apache.catalina.valves.AccessLogValve” directory=”logs”
prefix=”localhost_access_log.” suffix=”.txt”
pattern=”%h %l %u %t &quot;%r&quot; %s %b” />

</Host>

And that’s it, end of setting. Restart , code and redeploy.

The cookie:

Java snippet of simple utilization:

public class UploadsServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletExcpetion, IOException {
        File file = new File("/usr/share/tomcat/uploads", request.getPathInfo());
        response.setHeader("Content-Type", Files.probeContentType(file.toPath()));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        Files.copy(file.toPath(), response.getOutputStream());
    }

}

The conclusion:
In exact things the need for conclusion is deprecated. Everything should be concluded the one way :

return goToTopAndReadAgain();

The hint:

Maybe you won’t be impressed, and probably you have a better solution/implementation for/of the scenario. However let me give you a clue how this can be found useful in different situation. Proxying and load balancing, possibly with Nginx on front and couple of Tomcats behind. Defining new server contextses and getting a feel of that damn Superman speed.

Fiuuuuuuuuuuuuuuuuu…

(salutations and thanks to a friend of mine for collaboration)

Deploying Java Applications: Apache Tomcat + IIS 7.5

I’m on vacation and I’m writing my first technical post. That’s unfortunate 🙂

So this will be for all you lads and gentleman (and ladies) struggling in the world of Java and its ecosystem. Have you ever deployed Java apps on IIS? Well If I am the man to be consulted I’ll never choose that solution. But of course here comes the project managers, the Active Directory stuff and so on, when you have such climate you must bend yourself and do your best.

I have the following scenario: couple of different Java apps deployed on Tomcats. Well that doesn’t sound so bad there are easy service wizard installs of Apache Tomcat on Windows, easier deployment of the same so I will not really bother with such a trivial things, I hope you can do that by yourself.

Where is the problem? Well there a plural applications and one open port for the outside world. That’s right, the standard HTTP 80 port.

Simple thing we should do is to port forward and url rewrite the addressing applications.

Before finding this solution I was aware of one way on connecting Java container with IIS, through ISAPI and JK. But that requires changing Windows registry, defining couple of configuration files, using isapi_redirect , in other words messy and hardly-working solution. There are couple of guides on the net, just google it if you want to try them. The next solution is clean, simple and productive.

The IIS I’m working on is version 7.5. That is nice because the fellow Microsoft guys introduce a new solution to us, ARR. The use of this module here is to be set up to work as proxy server and that is exactly what we need in this situation.

After installing this extension on the server machine (I’m working on Windows Server 2008) next thing is to enable proxy server. Follow this steps:

  1. Open the IIS Manager and in the IIS Group there should be Application Request Routing Cache module showing up. Select it.
  2. So here we are. In the Action menu choose – Server Proxy Settings .
  3. For the following scenario this set up will work : Enable proxy = true, checked keep-alive, time-out by will, reverse rewrite host headers in response checked. Apply the changes and proceed.

Half work done. Next thing that we need is the URL rewrite feature. Install it. (Here I don’t mention  anything about the features and roles that need to be installed to make IIS working. I think that is just not-needed information here. You have the wizards in Computer Management, use them).

Well I hope you got URL rewrite working. That’s where we will define the rewrites.

Lets imagine. Two  Tomcat installation with just one application per server.

Installation folders: D:\Tomcat1 , D:\Tomcat2 . We need only the HTTP connectors, so in $tomcat_home\conf\server.xml you can comment out the AJP connectors.

Don’t forget while installing the Tomcats, to configure them on different ports. Example :

  <Connector port=”8080″ protocol=”HTTP/1.1″ proxyName=”www.example.com” proxyPort=”80″
               connectionTimeout=”20000″
               redirectPort=”8443″ />

  <Connector port=”8081″ protocol=”HTTP/1.1″ proxyName=”www.example.com” proxyPort=”80″
               connectionTimeout=”20000″
               redirectPort=”8443″ />

You ask yourself why I have put proxyName and proxyPort here. Well they are not required but since we want this application to work for outside world as I mentioned , you don’t want Java calls like getServerName() to return localhost  and local port. We want ajax and applets to work. This way we ensure the right host name and port are returned.

Installation ports: Tomcat1 on port 8080, Tomcat2 on port 8081. Installed apps: on Tomcat1 app1, on Tomcat2 app2.

So we can open the deployed applications on following urls : http://localhost:8080/app1 and http://localhost:8081/app2 .

It’s time to finalize the installations. We want the apps to be accessible on the following urls http://www.example.com/app1 and http://www.example.com/app2 .

This is where URL rewrite comes in play and that’s where we do the things explicitly. You can define URL rewrite rules in the main configuration but I prefer creating new site bound to port 80 and defining it there. Add new site with name exampe.com and for physical path put D:\ or whatever you want for your local situation, this is just example. That’s the place where web.config file will be created and everything that we do in the IIS manager will be mapped in configuration file, which is an xml configuration file the IIS use.

  1. In the new site, IIS group, open URL rewrite.
  2. Add new rule from the actions menu. Choose blank rule.
  3. Configurations : Name – Tomcat1 rule,  requested url -> matches the pattern , simple pattern: (app1.+) , ignore cases true,  action type – rewrite , rewrite url: http://localhost:8080/{R:0}
  4. Apply , make another rule for the other tomcat and  just change the name, pattern and the port.
  5. Restart IIS and you got it.

Just to get things straight. URL rewrite allow us to filter by some rule patterns, conditions and replace server variables. We just defined simple rewrite rule. That’s why we use {R:0} . It simple variable for the first rule pattern. There can be more of course , the format is {R:N} , where N is from 0 to 9.

This was very simple. I hope this will give you some clues how can you manipulate this modules to do more complex stuff. And you are not limited to use only Java servers of course. Any socket listening on any port can work.

I wish you happy days, for the end a reward from me