Saturday 11 May 2019

Tomcat Custom Valve to extract UserId out of HTTP SSO Headers and build X509 Certificate

Evernote Export

Overview
In this blog post i am going to show how to write a Tomcat Custom Valve. In my project I had a unique requirement of fetching user name/id from HTTP headers (being populated by a front Web Server responsible for authenticating user with SSO credentials) and then building X509 certificate programatically so that applications deployed having auth-method as CLIENT-CERT can pass.

Pre-requisite
  • Tomcat 9
  • Java 8 or above
  • A Front-end Web Server performing SSO authentication and then populating HTTP headers with SSO information OR you can simulate it via POSTMAN or other HTTP Requests sending tools.
    • For example in our case the http headers "sm_user" and "sm_session" was populated by userid information.

Steps to follow
  1. Create a Java Project in Eclipse IDE.
  2. Create a Java Class as below for a Custom Valve, remember you will have to import jars from <Tomcat-Home>/bin and <Tomcat-Home/lib folders:
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.servlet.ServletException;
//import jars from <TOMCAT-HOME>/lib
import org.apache.catalina.Globals;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
//import jars from <TOMCAT-HOME>/bin
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateVersion;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
public class X509CertCreatorCustomValve extends ValveBase {
private static final Log log = LogFactory.getLog(X509CertCreatorCustomValve.class);
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
log.info("Custom valve X509CertCreatorCustomValve is called");
String userid = request.getHeader("sm_user");
if (userid == null || userid.isEmpty()) {
userid = request.getHeader("sm_universalid");
}
log.info("UserId extracted from SSO Headers: " + userid);
if (userid != null) {
try {
X509Certificate certs[] = (X509Certificate[]) request.getAttribute(Globals.CERTIFICATES_ATTR);
if ((certs == null) || (certs.length < 1)) {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
String distinguishedName = "CN=" + userid + ", OU=TSD, O=XUZ, L=US1, S=NJ, C=US";
Certificate certificate = generateCertificate(distinguishedName, keyPair, 365, "SHA256withRSA");
certs = new X509Certificate[1];
certs[0] = (X509Certificate) certificate;
request.setAttribute(Globals.CERTIFICATES_ATTR, certs);
}
} catch (Exception e) {
log.error("Error preparing X509 certificate", e);
}
}
getNext().invoke(request, response);
}
private X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
throws GeneralSecurityException, IOException {
PrivateKey privkey = pair.getPrivate();
X509CertInfo info = new X509CertInfo();
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000l);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(dn);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, owner);
info.set(X509CertInfo.ISSUER, owner);
info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
// Update the algorithm, and resign.
algo = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
return cert;
}
}
  1. Export the class as a jar by using Eclipse jar export feature or build it manually from the compiled class.
  2. Put the jar in <TOMCAT-HOME>/lib folder
  3. Add a <valve> entry in <TOMCAT-HOME>/conf/server.xml file under <Host> tag as mentioned below:
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Valve className="X509CertCreatorCustomValve"/>
........
........
</Host>
  1. Start the Tomcat and test your application. Remember the pre-requisite setup you need, your web application must have CLIENT-CERT auth methnd configured in web.xml and http header needs to be populated before hitting your application.


Thank You!

No comments:

Post a Comment