Translating IP into its binary representation

Today I was working in the recovery of an Atlassian Crowd 2.2.x installation and in the process I needed to get the base64 representation for an IP address (See https://confluence.atlassian.com/display/CROWDKB/Client+Host+is+Invalid) like this:

IP: 127.0.0.1
Base 64: fwAAAQ==

So I wrote a simple script and uploaded it to http://iptobinary.zz.mu/ so you can get it easily.

Generar y firmar una CRL usando openssl

Necesitaremos contar con la clave privada y el certificado con el cual firmaremos la CRL  y luego ejecutamos el comando


openssl ca -gencrl -keyfile ca_key -cert ca_crt -out my_crl.pem

Con las opciones por defecto de openssl se requerira contar con una carpeta como la siguiente en el directorio actual, pero no hay que preocuparse aún por esto porque openssl nos mostrará un mensaje adecuado de error advirtiéndonos de esto:

demoCA/
- crlnumber
- index.txt

donde index.txt será un archivo vació y crlnumber contiene solamente ¨01¨, sin las comillas.

 

Y listo tenemos una CRL vacía, en una entrada posterior mostraré como incluir algunos certificados revocados en esta.

Un recordatorio sobre como crear XML por programa en Java


DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
 DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
 Document document = documentBuilder.newDocument();
 Element integers1 = document.createElement("integers");
 document.appendChild(integers1);
 TransformerFactory transformerFactory = TransformerFactory.newInstance();
 Transformer transformer = transformerFactory.newTransformer();
 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 transformer.transform(new DOMSource(document), new StreamResult(outputStream));
 String xmlAsString = new String(outputStream.toByteArray());

System.out.println(xmlAsString);

 

y esto generaría


<?xml version="1.0" encoding="UTF-8" standalone="no"?><integers/>

 

Absolutamente horrible, ¿no es cierto? Pero al parecer es la manera estándar en el mundo Java

Convertir texto de html input automáticamente a mayúsculas

Algunas veces necesitamos que el texto que se ingresa en un campo de texto de html como:

<input type="text" id="texto" />

Solamente permita ingresar datos en mayúsculas independientemente de si el usuario ingresa mayúsculas y minúsculas.

En este caso, el siguiente plugin de jquery convierte automáticamente la entrada en mayúsculas y además retira las tildes de los caracteres tildados, con lo cual, á se convierte en A y Á también se convierte en A.

Pueden descargarlo desde aquí:

https://github.com/skarootz/jquery-utils-pack/blob/master/jquery.mayusculassintildes.js

Y un ejemplo se puede ver en demos/index.html en:

https://github.com/skarootz/jquery-utils-pack

Básicamente todo lo que tienes que hacer es

$("#texto").mayusculassintildes();

En este momento el plugin se encuentra muy básico si tienes alguna observación o encuentras alguna incompatibilidad con lo que deseas hacer crea una cuenta en https://github.com y modifícalo ;)

WSF/Spring and Axis2 1.6.1

If you are in a hurry for a version of WSF/Spring that works with Axis2 1.6.1 I have modified the last version in Subversion for that project:

You can download source from here http://www.4shared.com/rar/Q9BRhxkH/wsf-spring-kpr.html

Download it and make


mvn install

Anyway I expect WSF/Spring project updates it library as soon as possible as that project seems to be getting unmaintained. Note that the artifact Id has been changed to avoid confusion so you will need to change you maven dependencies too.

Integrating SafeNet Luna PCI 3000 with WSS4J

Because of the need to integrate Luna PCI HSM Cryptographic accelerator card with WS-Security for WS-Signature operations for improving speed I had to customize a couple of things in the configuration of WSS4J, I will take Axis2 Configuration as example but it applies to CXF too as it uses WSS4J for WS-Security operations.

First of all Luna JSP (Java Service Provider) should be installed, with Luna JCE and JCA correctly installed in the JRE and java.security file with the ap\aaaaapropiate Luna providers in this position:


security.provider.1=sun.security.provider.Sun
security.provider.2=com.chrysalisits.crypto.LunaJCAProvider
security.provider.3=com.chrysalisits.cryptox.LunaJCEProvider
security.provider.4=sun.security.rsa.SunRsaSign
security.provider.5=com.sun.net.ssl.internal.ssl.Provider
...

 

As I’m using a policy based WS-Security configuration. I had to modify policy as follows:


...
</sp:SignedParts>
<ramp:RampartConfig xmlns:ramp="http://ws.apache.org/rampart/policy">
<ramp:user>SDE Server</ramp:user>
<ramp:passwordCallbackClass>com.kprtech.service.ws.security.ServerCallback</ramp:passwordCallbackClass>

<ramp:signatureCrypto>
<ramp:crypto provider="example.MyMerlin">
<ramp:property name="org.apache.ws.security.crypto.merlin.keystore.type">Luna</ramp:property>
<ramp:property name="org.apache.ws.security.crypto.merlin.file"></ramp:property>
<ramp:property name="org.apache.ws.security.crypto.merlin.keystore.password"></ramp:property>
</ramp:crypto>
</ramp:signatureCrypto>



</ramp:RampartConfig>

...


Where ramp:user is the alias in the HSM for the signing certificate and example.MyMerlin is as follows:

package example;

import com.chrysalisits.crypto.LunaPrivateKeyRsa;
import com.chrysalisits.crypto.LunaSession;
import com.chrysalisits.crypto.LunaTokenObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.security.components.crypto.CredentialException;
import org.apache.ws.security.components.crypto.Merlin;

import java.io.IOException;
import java.security.PrivateKey;
import java.util.Properties;

/**
* Creado por: jaime
* 13/02/12
*/
public class MyMerlin extends Merlin {

/**
* THE HANDLE!
*/
public static final int PRIVATE_KEY_HANDLE = 71;

public MyMerlin(Properties properties, ClassLoader loader) throws CredentialException, IOException {
super(properties, loader);
}

public MyMerlin(Properties properties) throws CredentialException, IOException {
super(properties);
}

private static Log log = LogFactory.getLog(MyMerlin.class);

@Override
public PrivateKey getPrivateKey(String alias, String password) throws Exception {
return new LunaPrivateKeyRsa(new LunaTokenObject(PRIVATE_KEY_HANDLE, LunaSession.GetNewInstance()));
}

}</pre>
&nbsp;
<pre>

Where the constant PRIVATE_KEY_HANDLE should be set the value of the handle id of the private key used for signing. ramp:user set in the first configuration won’t be enough as the Luna JCA Keystore implementation maps only to the certificate and not the private key. This is not a really clean solution but to the time it works.

You can always get the handle id using Luna software:


cmu list 

You will need too to place calls to:


 HSM_Manager.HSM_Login();

and


 HSM_Manager.HSM_Login();

in the correct places in your app so your application becomes logged to the HSM.

Any question I’ll be glad to help you as this problem took me more than a week to get resolved.

One point worths to note is that the improvement in speed wasn’t as good as I expected, I suppose that because of the work done by Axis2/Rampart to create Ws-Security XML is more than the work needed to create the actual signature

WSF/Spring, Axis2 + Spring Security with WS-Signature

Hi, I want to comment my experience on setting up a web service using WSF/Spring to expose and axis2 web service and integrating this with Spring Security so the authentication gets done by spring.

I will asume you have already set up a web service with WSF/Spring (just WSF for brevity) + WS-Signature (using rampart) and that you know about spring security, I will only show how to add an axis2 handler to WSF to intercept incoming web services operations and authenticate them using spring security and WS-Signature.

Axis2 Handler for Spring Security Integration



import util.ServiceContext;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.engine.Handler;
import org.apache.axis2.handlers.AbstractHandler;
import org.apache.ws.security.WSSecurityEngineResult;
import org.apache.ws.security.handler.WSHandlerConstants;
import org.apache.ws.security.handler.WSHandlerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import javax.security.auth.Subject;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;

/**
* Executed in a custom phase after the security phase has been proccesed
*
* Creado por: jaime
* 28/12/11
*/
public class SpringSecurityHandler extends AbstractHandler {

@Override
public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {


//  get xmldsig and authenticate
List<Object> results = (List<Object>) msgContext.getProperty(WSHandlerConstants.RECV_RESULTS);
if (results == null) {
return InvocationResponse.ABORT;
}


for (Iterator iter = results.iterator(); iter.hasNext(); ) {
WSHandlerResult hr = (WSHandlerResult) iter.next();
if (hr == null || hr.getResults() == null) {
return InvocationResponse.ABORT;
}
for (Iterator it = hr.getResults().iterator(); it.hasNext(); ) {
WSSecurityEngineResult er = (WSSecurityEngineResult) it.next();
if (er != null && er.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE) instanceof X509Certificate) {
X509Certificate x509Cert= (X509Certificate) er.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);

// TODO check against database

SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(x509Cert, null));


return InvocationResponse.CONTINUE;
}
}
}
return InvocationResponse.ABORT;
}

}

 

axis2Config.xml (Displaying only modified parts)


<bean id="axis2InFaultPhaseOrder">
<property name="phaseOrderType" value="InFaultFlow"></property>
<property name="phases">
<list>
<ref bean="axis2AddressingPhase"/>
<ref bean="security"/>
<ref bean="springSecurityCheckPhase"/>
<ref bean="preDispatchPhase"/>
<bean id="InFaultDispatchPhase">
<property name="name" value="Dispatch"></property>
<property name="clazz" value="org.apache.axis2.engine.DispatchPhase"></property>
<property name="handlers">
<list>
<ref bean="RequestURI"/>
<ref bean="SOAPAction"/>
<ref bean="RequestURIOperation"/>
<ref bean="SOAPMessageBody"/>
<ref bean="HTTPLocationBased"/>
</list>
</property>
</bean>
</list>
</property>
</bean>

<bean id="axis2InPhaseOrder">
<property name="phaseOrderType" value="InFlow"></property>
<property name="phases">
<list>
<ref bean="axis2TransportPhase"/>
<ref bean="axis2AddressingPhase"/>
<ref bean="security"/>
<ref bean="springSecurityCheckPhase"/>
<ref bean="preDispatchPhase"/>
<bean id="InDispatchPhase">
<property name="name" value="Dispatch"></property>
<property name="clazz" value="org.apache.axis2.engine.DispatchPhase"></property>
<property name="handlers">
<list>
<ref bean="RequestURI"/>
<ref bean="SOAPAction"/>
<ref bean="RequestURIOperation"/>
<ref bean="SOAPMessageBody"/>
<ref bean="HTTPLocationBased"/>
</list>
</property>
</bean>

</list>
</property>
</bean>



....

<!-- add a handler in the Security phase after SecurityInHandler-->

<bean id="springSecurityHandlerBean">
<property name="name" value="SpringSecurityHandler"></property>
<property name="clazz" value="com.kprtech.service.ws.security.SpringSecurityHandler"></property>
</bean>

<bean id="springSecurityCheckPhase">
<property name="name" value="SpringSecurityCheckPhase" />
<property name="handlers">
<list>
<ref bean="springSecurityHandlerBean"/>
</list>
</property>
</bean>


The last part of xml is creating a new phase with a handler (SpringSecurityHandler) and attaching it to axis2InPhaseOrder and axis2InFaultPhaseOrder after the Security proccesing of rampart.