Cliente del «Servicio de Verificación y Consulta de Datos: Plataforma de Intermediación» con CXF

Me ha tocado realizar un cliente para este Servicio Web del Estado (Español).
En los documentos adjuntos, hay mucha informacion relativa a lo que hace y como quiere los datos.
Sobre seguridad no indica nada mas que permite: WS-Security, XMLDSig y Xades. Que se tiene que firmar, pero no indica, que algoritmos hay que usar, como firmar las cabeceras, que partes hay que firmar, etc. Cosa sorprendente cuando ves que hay varias maneras de firmar y de hacer las cosas. Pero te dan una peticion y una respuesta tipo. En base a esa peticion he ido realizando pruebas y puedo afirmar que ya lo tengo.

En CXF recomiendan el uso de WS-Policy siempre y cuando el WSDL contenga estos apartados, pero en este caso tenemos que usar los interceptors de CXF. En el cliente antes de enviar la peticion SOAP, tenemos que firmar el soap:body. Esto se hace en el soap:header, con WS-Security y los Interceptors.

Por lo que he deducido las caracteristicas de WS-Security son:

Dejo mi fichero de configuración de spring para CXF y mi fichero de propiedades:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:cxf="http://cxf.apache.org/core" xmlns:http="http://cxf.apache.org/transports/http/configuration"
	xmlns:p="http://cxf.apache.org/policy" xmlns:wsa="http://cxf.apache.org/ws/addressing"
	xmlns:wsp="http://www.w3.org/2006/07/ws-policy" xmlns:sec="http://cxf.apache.org/configuration/security"
	xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
	xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
	xsi:schemaLocation="
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
	http://cxf.apache.org/transports/http/configuration
	http://cxf.apache.org/schemas/configuration/http-conf.xsd
	http://cxf.apache.org/configuration/security
	http://cxf.apache.org/schemas/configuration/security.xsd
	http://cxf.apache.org/ws/addressing 
	http://cxf.apache.org/schema/ws/addressing.xs
	http://cxf.apache.org/transports/http/configuration 
	http://cxf.apache.org/schemas/configuration/http-conf.xsd
	http://www.w3.org/2006/07/ws-policy	
	http://www.w3.org/2006/07/ws-policy.xsd
	http://cxf.apache.org/policy 
	http://cxf.apache.org/schemas/policy.xsd
	http://cxf.apache.org/core 
	http://cxf.apache.org/schemas/core.xsd
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://cxf.apache.org/jaxws 
	http://cxf.apache.org/schemas/jaxws.xsd">

	<import resource="classpath*:spring-xsd.xml" />
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<http:conduit name="https://localhost:.*">
		<http:tlsClientParameters disableCNCheck="true">
			<!-- <sec:trustManagers> -->
			<!-- <sec:keyStore type="jks" password="cspass" resource="clientKeystore.jks" 
				/> -->
			<!-- </sec:trustManagers> -->
		</http:tlsClientParameters>
	</http:conduit>

	<cxf:bus>
		<cxf:features>
			<cxf:logging />
		</cxf:features>
		<cxf:inInterceptors>
			<ref bean="SignResponse" />
			<bean class="org.apache.cxf.ws.security.wss4j.DefaultCryptoCoverageChecker" />
		</cxf:inInterceptors>
		<cxf:outInterceptors>
			<ref bean="SignRequest" />
		</cxf:outInterceptors>
	</cxf:bus>

	<util:map id="mapKeystorePasswords">
		<entry key="${org.apache.ws.security.crypto.merlin.keystore.alias}" value="${org.apache.ws.security.crypto.merlin.keystore.password}" />
	</util:map>
	
	<bean id="clientPasswordCallback"
		class="es.una.ruta.callback.ClientPasswordCallback" >
		</bean>

	<bean id="url" class="java.lang.String">
		<constructor-arg
			value="https://${paxase.host}:${paxase.port}/${paxase.wsname}" />
	</bean>
	<bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
		<property name="serviceClass" value="es.map.xml_schemas.PeticionPortType" />
		<property name="address" value="#{url}/consultarIdentidad" />
	</bean>
	<bean id="clientConsultaIdentidad" class="es.map.xml_schemas.PeticionPortType"
		factory-bean="clientFactory" factory-method="create" />

	<bean class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor"
		id="SignRequest">
		<constructor-arg>
			<map>
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).IS_BSP_COMPLIANT}"
					value="#{T(java.lang.Boolean).FALSE.toString()}" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).MUST_UNDERSTAND}"
					value="#{T(java.lang.Boolean).FALSE.toString()}" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).ACTION}"
					value="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIGNATURE}" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).USER}"
					value="${org.apache.ws.security.crypto.merlin.keystore.alias}" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_PROP_FILE}"
					value="client_sign.properties" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_KEY_ID}"
					value="${signature.key.identifier}" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_ALGO}"
					value="#{T(org.apache.ws.security.WSConstants).RSA_SHA1}" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_DIGEST_ALGO}"
					value="#{T(org.apache.ws.security.WSConstants).SHA1}" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_C14N_ALGO}"
					value="#{T(org.apache.ws.security.WSConstants).C14N_EXCL_OMIT_COMMENTS}" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIGNATURE_PARTS}"
					value="#{'{}{' + T(org.apache.ws.security.WSConstants).URI_SOAP11_ENV + '}' + T(org.apache.ws.security.WSConstants).ELEM_BODY + ';'}" />
               	<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).PW_CALLBACK_REF}" 
					value-ref="clientPasswordCallback" />
			</map>
		</constructor-arg>
	</bean>

	<bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor"
		id="SignResponse">
		<constructor-arg>
			<map>
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).ACTION}"
					value="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIGNATURE}" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_PROP_FILE}"
					value="client_sign.properties" />
				<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).PW_CALLBACK_REF}" 
					value-ref="clientPasswordCallback" />
				<entry
					key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_ALGO}"
					value="#{T(org.apache.ws.security.WSConstants).RSA_SHA1}" />
			</map>
		</constructor-arg>
	</bean>

</beans>

En mi fichero de propiedades del keystore tengo puesto el tipo de firma:

# Defines which key identifier type to use for signature.
# Valid values are: - "IssuerSerial" - "DirectReference" - "X509KeyIdentifier" - "Thumbprint" - "SKIKeyIdentifier" - "KeyValue" - "EmbeddedKeyName" - "EncryptedKeySHA1"
signature.key.identifier =DirectReference
#
org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
org.apache.ws.security.crypto.merlin.keystore.file=clientKeystore.jks
org.apache.ws.security.crypto.merlin.keystore.password=cspass
org.apache.ws.security.crypto.merlin.keystore.type=jks
org.apache.ws.security.crypto.merlin.keystore.alias=myclientkey
Cliente del «Servicio de Verificación y Consulta de Datos: Plataforma de Intermediación» con CXF

WS-Security WSHandlerConstants

Debido a que la pagina de configuracion de Apache WSS4J no me resulto del todo aclaratoria, voy a dar una pequeña descripcion de cada una de las constantes definidas. Si hay algo que no entiendes, puedes revisar el javadoc de WSHandlerConstants.

Poner toda esta documentacion en una pagina, visualmente no queda bien. Por lo que lo dejo en este fichero.
Existe otra clase de constantes que desde WSHandlerConstants hace referencia: WSConstants. Contiene todos los algoritmos soportados, la declaracion de namespaces, etc.

WS-Security WSHandlerConstants

WS-I Basic Security Profile

Estandar de la industria para los servicios web.

BSP 1.1

Desde el principio, las especificaciones de WS SOAP han ofrecido muchas opciones para los que los implementan los servicios y los que los consumen. En parte, fue por diseño en otros casos se deben a descuidos en las normas: los comportamientos esperados no se han especificado con suficiente detalle, por lo que los que implementan los servicios tenían que adivinar lo que había que hacer. No hay recursos para probar todas las combinaciones posibles. Esta situación crea grandes problemas de interoperabilidad.
El exceso de opciones, fue un problema en los primeros años de SOAP. La Organización de Interoperabilidad de Servicios Web (WS-I) , creo WS-Profile.
La seguridad es una de las áreas de WS-I ha cubierto con WS-Profile. El WS-I Basic Security Profile Version 1.1 (actualmente[2013] esta vigente la version 2.0) es el principal documento en el área de seguridad. BSP 1.1 no es WS-SecurityPolicy, pero algunas de sus necesidades si.
Cuando se utiliza la firma digital, BSP 1.1 requiere que se siga la recomendación del W3C Exclusive XML Canonicalization , un algoritmo de canonización XML que hace caso omiso de los comentarios y la información contextual necesaria. Este algoritmo es el predeterminado por WS-SecurityPolicy.
BSP 1.1 también añade otros requisitos para firmas y cifrado, especificando que los algoritmos a usar sean: TripleDes, AES128, AES256 y SHA1 (excluyendo AES192 y SHA256 opciones ofrecidas por WS-SecurityPolicy).

Apache WSS4j

En su version 1.5, no aplica BSP de manera significativa. La clase: org.apache.ws.security.WSSConfig, tiene una variable: isWsiBSPCompliant que por defecto esta a falso. Esta variable permitir la generación de una lista InclusivePrefix para la generación de la firma, algo que es obligatorio en la especificación BSP.

En su version 1.6, soporta BSP1.1, solo las especificaciones básicas de WS-Security. Se puede controlar mediante Handler.
org.apache.ws.security.handler.WSHandlerConstants.IS_BSP_COMPLIANT

En Apache CXF, tambien se puede usar BSP1.1 junto con WS-Policy mediante org.apache.cxf.ws.security.SecurityConstants.IS_BSP_COMPLIANT

WS-I Basic Security Profile

Constantes en Spring description file

El fichero de spring:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd>

	<util:constant id="constant1" static-field="org.apache.ws.security.handler.WSHandlerConstants.ACTION"/>
	<bean id="constant2" class="java.lang.String">
		<constructor-arg value="#{T(org.apache.ws.security.handler.WSHandlerConstants).ACTION}" />
	</bean>
	<util:map id="mapProperties">
		<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).IS_BSP_COMPLIANT}" value="#{T(java.lang.Boolean).FALSE.toString()}"/>
		<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).ACTION}" value="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIGNATURE}"/>
		<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).USER}" value="myclientkey" />
		<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_PROP_FILE}" value="client_sign.properties" />
		<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_KEY_ID}" value="DirectReference"/>
		<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_ALGO}" value="#{T(org.apache.ws.security.WSConstants).RSA_SHA1}" />
		<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_DIGEST_ALGO}" value="#{T(org.apache.ws.security.WSConstants).SHA1}" />
		<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIG_C14N_ALGO}" value="#{T(org.apache.ws.security.WSConstants).C14N_OMIT_COMMENTS}" />
		<entry key="#{T(org.apache.ws.security.handler.WSHandlerConstants).SIGNATURE_PARTS}" 
			value="#{'{}{' + T(org.apache.ws.security.WSConstants).URI_SOAP11_ENV + '}' + T(org.apache.ws.security.WSConstants).ELEM_BODY + ';'}" />
	</util:map>

La clase test:

package es.depontevedra.soap.interoperabilidad.identidad.paxase;

import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;

import static org.testng.Assert.assertTrue;

@ContextConfiguration(locations = { "classpath:spring-properties.xml" })
public class Testing extends AbstractTestNGSpringContextTests {

	@Autowired
	private String constant1;
	
	@Autowired
	private String constant2;
	
	@Resource(name="mapProperties")
	private Map<String, String> mapProperties;
	
	@Test
	public void test(){
		System.out.println("Constante 1: " + constant1);
		System.out.println("Constante 2: " + constant2);
		for(Entry<String, String> entry: mapProperties.entrySet()){
			System.out.println("Clave: " + entry.getKey());
			System.out.println("Valor: " + entry.getValue());
		}
		
		assertTrue(true);
	}
	
}

el resultado:

Constante 1: action
Constante 2: action
Clave: isBSPCompliant
Valor: false
Clave: action
Valor: Signature
Clave: user
Valor: myclientkey
Clave: signaturePropFile
Valor: client_sign.properties
Clave: signatureKeyIdentifier
Valor: DirectReference
Clave: signatureAlgorithm
Valor: http://www.w3.org/2000/09/xmldsig#rsa-sha1
Clave: signatureDigestAlgorithm
Valor: http://www.w3.org/2000/09/xmldsig#sha1
Clave: signatureC14nAlgorithm
Valor: http://www.w3.org/TR/2001/REC-xml-c14n-20010315
Clave: signatureParts
Valor: {}{http://schemas.xmlsoap.org/soap/envelope/}Body;
PASSED: test

librerias que vas a necesitar, en el fichero pom de Maven:

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.ws.security</groupId>
			<artifactId>wss4j</artifactId>
			<version>1.6.13</version>
		</dependency>

		<!-- TEST -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<scope>test</scope>
		</dependency>
Constantes en Spring description file

Renombar espacios en blanco en nombres de ficheros

Este script funciona salvo cuando el nombre del fichero tiene espacios en blanco:]

sed -e 'p;s/evolu/involu/' | xargs -n2 mv

Con sed se pueden quitar los espacios en blanco:
solo el primer espacio:

ls | echo | sed ’s/s/./‘

todos los espacios en blanco:

ls | echo | sed 's/s/./g'

el script que lo soluciona:

for i in *; do mv "${i}" `echo ${i} | sed -e 's/s/./g'`; done
Renombar espacios en blanco en nombres de ficheros