Buscar este blog

martes, 27 de marzo de 2018

X509 Certificate Mock Servlet Filter

This is a way low-technolgy-solution to simulate, in web application, an SSL mutual authentication.  The obvious solution would be to configure Apache httpd as front-end, and let it to ask for the user certificate, but I had some problems with an android web browser...
So, instead configure Apache with a "SSLVerifyClient require" this is my ashamed solution: to configure a servlet filter (at first position in the chain) and, if there is no certificate in the request, just put one and go on.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class X509CertificateFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(X509CertificateFilter.class);
    
    private static final String CERTIFICATE = "-----BEGIN CERTIFICATE-----\r\n" + 
            "MIIIdDCCB1ygAwIBAgIQIDbcJ3psq8FXD6IQBZA15DANBgkqhkiG9w0BAQsFADBN\r\n" +             
            "(...)\r\n" + 
            "740qIwTZlA4=\r\n" + 
            "-----END CERTIFICATE-----";
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {                
    }

    @Override
    public void destroy() {        
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (request.getAttribute("javax.servlet.request.X509Certificate") == null) {
            request.setAttribute("javax.servlet.request.X509Certificate", buildCertificates());
        }
        
        chain.doFilter(request, response);    
    }

    private static X509Certificate[] buildCertificates() {
        try {        
            final InputStream is = new ByteArrayInputStream(CERTIFICATE.getBytes());                    
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
            return new X509Certificate[] {cert};
        }
        catch(Exception e) {
            LOGGER.error("Error injecting certificate", e);
            return null;
        }
    }    
}

You can also configure multiple certificates, for example in a map, and use a request parameter to pick one...

domingo, 25 de marzo de 2018

JBoss datasources and transactions practical tests

Abstract

One question which arouse from time to time is how transactions work and what kind of configuration you need to set in your application in order to make it run, and to keep your databases clean (no lost writes or incosistent states). 

The question about how to make your application run is usually solved by developers with the classic try-and-error approximation. When you face an error, you could begin to change settings until the error disappear. Recently one of these problems was related with the access to two different databases through two JTA Datasources, and in the same transaction. The magic solution found was to change one of these Datasources to non JTA. 

The question about how to keep your databases clean depends on how you solved the error. As you will see later, that solution was not much safe, but probably they didn't know.

So, I decided to prepare a simple web application to try access to two different databases, throught different kinds of datasources, in the same transaction and by ussing different combiantions.

The source code of these tests is in my GitHub: https://github.com/evazquezma/jboss/tree/master/jboss-datasources

Glosary

These are the main terms used here:
  • Local transaction: A transaction which involves only one transactional resource.
  • Global transaction: A transaction which involves multiple transactional resources.
  • Distribuited transaction: A global transaction which spans over multiple hosts (in this case, servers).
  • XA: eXtended Architecture
  • XA Resource: Transactional resource which allows 2PC for global transactions.
  • 1PC: One Phase Commit
  • 2PC: Two Phase Commit

Test structure

The test application will be running in JBoss EAP 6.4. It will use Spring 3.X and Hibernate 4.X (sorry, I have in my to-do list to migrate all these stuff )

For these test there will a set of datasources provided for JBoss. Two of them will be datasources with JTA flag to false, two more with JTA to true (default value) and finally two XA-Datasources.
In each test the application will use different combinations of these datasources, but there will be always two different databases in the pitch.

Database access will be configured through Hibernate SessionFactory and Spring Transaction Manager:
<bean id="dataSource1" class="org.springframework.jndi.JndiObjectFactoryBean">
 <property name="jndiName" value="java:jboss/datasources/ExampleDSNoJTA"/>
</bean>

<bean  id="sessionFactory1" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="false">
 <property name="dataSource" ref="dataSource1"/>
 <property name="packagesToScan" value="es.sisifo.jboss.datasources.entity.one"/>
 <property name="hibernateProperties">
  <props>
   <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
   <prop key="hibernate.show_sql">true</prop>
   <prop key="hibernate.format_sql">true</prop>
   <prop key="hibernate.use_sql_comments">true</prop>
   <prop key="hibernate.hbm2ddl.auto">create</prop>

   <prop key="hibernate.validator.apply_to_ddl">false</prop>
   <prop key="hibernate.validator.autoregister_listeners">false</prop>

   <prop key="hibernate.transaction.factory_class">org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory</prop>
   <prop key="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform</prop>                                
     </props>
 </property>  
</bean>

<!-- The same to sessionFactory2 -->

<!-- TX config -->
<tx:annotation-driven/>
<tx:jta-transaction-manager/>

During startup Spring will try to find the server transaction manager by checking the following JNDI entries:
  • java:comp/TransactionManager
  • java:appserver/TransactionManager
  • java:pm/TransactionManager
  • java:/TransactionManager. Bingo, it will use com.arjuna.ats.jbossatx.jta.TransactionManagerDelegate

In each database there will be one table/entity: EntityOne and EntityTwo, with the same dummy structure:
@Entity
@Table(name = "tableOne")
public class EntityOne {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;

 private String code;

 private Date time;
 
 (...) 
}

Each test will consists of calling three transactional methods in a service:
@Override
@Transactional
public void testInsertOK() {
 final EntityOne entityOne = new EntityOne();
 entityOne.setTime(new Date());
 entityOne.setCode("Insert OK");
 entityOneDao.save(entityOne);

 final EntityTwo entityTwo = new EntityTwo();
 entityTwo.setTime(new Date());
 entityTwo.setCode("Insert OK");
 entityTwoDao.save(entityTwo);
}

@Override
@Transactional(rollbackFor=Exception.class)
public void testInsertMiddleError() {
 final EntityOne entityOne = new EntityOne();
 entityOne.setTime(new Date());
 entityOne.setCode("Insert with Middle Error");
 entityOneDao.save(entityOne);

 if (System.currentTimeMillis() > 0) {
  throw new RuntimeException("Kaboom in the middle");
 }

 final EntityTwo entityTwo = new EntityTwo();
 entityTwo.setTime(new Date());
 entityTwo.setCode("Insert with Middle Error");
 entityTwoDao.save(entityTwo);
}


@Override
@Transactional(rollbackFor=Exception.class)
public void testInsertFinalError() {
 final EntityOne entityOne = new EntityOne();
 entityOne.setTime(new Date());
 entityOne.setCode("Insert with Final Error");
 entityOneDao.save(entityOne);

 final EntityTwo entityTwo = new EntityTwo();
 entityTwo.setTime(new Date());
 entityTwo.setCode("Insert with Final Error");
 entityTwoDao.save(entityTwo);

 throw new RuntimeException("Kaboom at the end");
}

At the end of the tests, both tables will be listed in order to check which writes persisted and which were rolled back.

Summary


Tests results

Non JTA Datasource + Non JTA Datasource

Result:
EntityOne [id=1, code=Insert OK, time=2018-03-25 20:03:22.577]
EntityOne [id=2, code=Insert with Middle Error, time=2018-03-25 20:03:22.683]
EntityOne [id=3, code=Insert with Final Error, time=2018-03-25 20:03:22.698]

EntityTwo [id=1, code=Insert OK, time=2018-03-25 20:03:22.663]
EntityTwo [id=2, code=Insert with Final Error, time=2018-03-25 20:03:22.701]

Database writes are auto-commited inmeditely in both resources.
You can use both resources inside the same transaction, but they are not enlisted.
Each resource has its own "transaction boundary". If there is an error inside the transaction, as there is no rollback, you can get data inconsistency.

JTA Datasource + Non JTA Datasource

Result:
EntityOne [id=1, code=Insert OK, time=2018-03-24 19:16:51.645]

EntityTwo [id=1, code=Insert OK, time=2018-03-24 19:16:51.709]
EntityTwo [id=2, code=Insert with Final Error, time=2018-03-24 19:16:51.733]

JTA resource is managed inside a JTA Transaction, so transaction boundary is demarcated by the transaction manager.
Database writes are committed on transaction completion for JTA resource, and auto-committed inmediately for non JTA resource .
Thus, non JTA resource is not managed by transaction manager, if there is an error during the transaction, JTA resource is rolled back and non JTA resource is autocommitted.
You can get database inconsistencies.

Non JTA Datasource + JTA Datasource

Result:
EntityOne [id=1, code=Insert OK, time=2018-03-24 19:25:33.252]
EntityOne [id=2, code=Insert with Middle Error, time=2018-03-24 19:25:33.325]
EntityOne [id=3, code=Insert with Final Error, time=2018-03-24 19:25:33.335]

EntityTwo [id=1, code=Insert OK, time=2018-03-24 19:25:33.312]

Similar to previous scenario. In this case, the difference is due to the insertions order.
During an exception inside the transaction, only JTA resource is rolled back.

JTA Datasource + JTA Datasource

You get the following error:
19:37:52,308 WARN  [com.arjuna.ats.arjuna] (http-localhost/127.0.0.1:8080-2) ARJUNA012140: Adding multiple last resources is disallowed. Trying to add LastResourceRecord(XAOnePhaseResource(LocalXAResourceImpl@434c39c8[connectionListener=27aa95d connectionManager=5209886e warned=false currentXid=< formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffffc0a80133:17004d06:5ab68ccc:26e, node_name=1, branch_uid=0:ffffc0a80133:17004d06:5ab68ccc:275, subordinatenodename=null, eis_name=java:jboss/datasources/ExampleDS2 > productName=H2 productVersion=@PROJECT_VERSION@ (2012-07-13) jndiName=java:jboss/datasources/ExampleDS2])), but already have LastResourceRecord(XAOnePhaseResource(LocalXAResourceImpl@414aa356[connectionListener=501a920b connectionManager=1519056b warned=false currentXid=< formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffffc0a80133:17004d06:5ab68ccc:26e, node_name=1, branch_uid=0:ffffc0a80133:17004d06:5ab68ccc:272, subordinatenodename=null, eis_name=java:jboss/datasources/ExampleDS > productName=H2 productVersion=@PROJECT_VERSION@ (2012-07-13) jndiName=java:jboss/datasources/ExampleDS]))
19:37:52,309 INFO  [stdout] (http-localhost/127.0.0.1:8080-2) [2018-03-24 19:37:52,309] (SqlExceptionHelper.java:145) WARN http-localhost/127.0.0.1:8080-2 org.hibernate.engine.jdbc.spi.SqlExceptionHelper SQL Error: 0, SQLState: null

19:37:52,309 INFO  [stdout] (http-localhost/127.0.0.1:8080-2) [2018-03-24 19:37:52,309] (SqlExceptionHelper.java:147) ERROR http-localhost/127.0.0.1:8080-2 org.hibernate.engine.jdbc.spi.SqlExceptionHelper javax.resource.ResourceException: IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.connectionmanager.listener.TxConnectionListener@27aa95d[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection@1a5a5cf8 connection handles=0 lastUse=1521916672308 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool@11371f69 pool internal context=SemaphoreArrayListManagedConnectionPool@6f62844[pool=ExampleDS2] xaResource=LocalXAResourceImpl@434c39c8[connectionListener=27aa95d connectionManager=5209886e warned=false currentXid=null productName=H2 productVersion=@PROJECT_VERSION@ (2012-07-13) jndiName=java:jboss/datasources/ExampleDS2] txSync=null]

You are trying to enlist two transactional resources in the same transaction, i.e., you are running in a global transaction. This scenario is only allowed with XA resources.

The error is quite clear:
ARJUNA012140: Adding multiple last resources is disallowed.
Trying to add LastResourceRecord(XAOnePhaseResource(... jndiName=java:jboss/datasources/ExampleDS2])), but already have LastResourceRecord(XAOnePhaseResource(... jndiName=java:jboss/datasources/ExampleDS]))

What it's saying is that you have a 1P resource (ExampleDS) in an active transaction, and you are trying to enlist a second 1P Resource (ExampleDS) in the same transaction. You can only do that with XA resources.

JTA Datasource + JTA XA Datasource

Response:
EntityOne [id=1, code=Insert OK, time=2018-03-25 12:29:42.584]

EntityTwo [id=1, code=Insert OK, time=2018-03-25 12:29:42.695]

OK, this can sound weird. You have one JTA resource (which only supports 1PC) enlisted in a global transaction with other XA resource (which do supports 2PC). This should be an error, because you can not ensure the 2PC, i.e, the transaction coordinator can not ask the JTA resource if it is prepared.

Here is where ARJUNA came to scene. JBoss uses ARJUNA as transaction core, and it uses a LRCO - Last Resource Commit Optimization:
The doc is surprisingly clear. You do can have a single non-XA resource inside a global transaction, but only if all the other resources do are XA. In order to perform the 2PC, in the first phase the non XA resource is processed last, and only if all the XA resources responded affirmatively to the prepare request, the non-XA Resources is committed immediately. During second phase the rest of XA Resources are committed normally.

The operations are as follow:
  1. Prepare 2PC (The XA Resources)
  2. Commit LRCO (The non-XA Resource)
  3. Write tx log
  4. Commit 2PC (The XA Resources)
But there is still an error opportunity if something crash in step 3. So, this is not a fully reliable scenario.

In order to improve LRCO there is the CMR - Commit Markable Resource, but it´s only valid for datasource (a transactional resource can be, for example, a JMS Queue, but you can not use CMR here). You need some extra configuration for this:
  • Set the non-XA datasource as connectable
  • Create a new table in database (the one for de non-XA datasource) to store XIDs
  • Link Jboss transaction subsystem with this datasource and this table

JTA Datasource + JTA XA Datasource

Same result as previous test.

XA Datasource + XA Datasource

Same result as previous test.
This is a full global transaction scenario with XA Resources.

JTA XA Datasource + Non JTA Datasource

Same result as "JTA Datasource + Non JTA Datasource"

Non JTA Datasource + JTA XA Datasource

Same result as "Non JTA Datasource + JTA Datasource"

sábado, 17 de febrero de 2018

JBoss - Check Vault, Users and JNDI entries

Almost all applications that we develop requires the use of encrypted strings, users with some specific role, or jndi entries. It is very common that, during the process of configuration, something goes wrong and you will have to lost much time trying to figure out what.

For example, your application publishes a web service, which is secured with security constraints, and only users with a proper role can consume it. The server is configured, the application is deployed, but when you try to invoke the service you get an 403 Unauthorized error. What it's wrong?, the user is not in the Application Realm of the server, the user credentials are not right, the vault password is wrong, the user has not the suitable rol?

I prepared a quite simple web app in order to test these problems easily: https://github.com/evazquezma/jboss/releases
Once deployed, from the index page, you can go to these pages:
  • http://localhost:8080/jboss-utils/vault
    Introduce a string in vault format and check the clear value.
  • http://localhost:8080/jboss-utils/users
    Introduce an user credentials and check if she exists, and which roles she has.
  • http://localhost:8080/jboss-utils/jndi
    Introduce a jndi key and check if it exists, its value and its class name.

viernes, 16 de febrero de 2018

Autofirma - Análisis de firma en Android

Siguiendo con el tema de Autofirma, en esta ocasión voy analizar los distintos mensajes intercambiados entre el navegador, Autofirma y los servidores de backend cuando se realiza una firma trifásica en Android.

Entorno

El entorno de la prueba es el siguiente:
  • Apache: 2.2
  • JBoss EAP 6.4
  • Android: 4.4.4
Además, los componentes involucrados son:
Componente Versión URL
Página de firma N/A http://192.168.43.239/sdxc/test/storageRetrieve
Autofirma Cliente movil firma 1.5 N/A
Server trifase 1.5 http://192.168.43.239/afirma-server-triphase-signer/SignatureService
Signature Storage 1.5 http://192.168.43.239/afirma-signature-storage/StorageService
Signature Retrieve 1.5 http://192.168.43.239/afirma-signature-retriever/RetrieveService
Directorio entrada server trifase N/A D:\tmp\afirma\entrada
Directorio salida server trifase N/A D:\tmp\afirma\salida
Directorio temporal servlets N/A D:\tmp\afirma\TriStorageRetrieve

Visión general

En esta prueba se lanzará una firma de tipo PAdES, sobre el fichero "prueba1.pdf", empleando el servidor trifase y los servlets de almacenamiento Sotrage y Retrieve.

El servidor trifase sirve para que la gestión del fichero que se va a firmar se haga en servidor y, por tanto, nunca se envíe completo al dispositivo del usuario. Este modo de funcionamiento se basa en tres etapas:
  1. Autofirma llama al servidor trifase para indicarle que prepare la firma. Es decir, que coja el fichero y prepare el hash que hay que firmar.
  2. Autofirma recibe el hash y lo firma con la clave privada del certificado de usuario.
  3. Autofirma llama al servidor trifase para indicarle que complete la firma. Es decir, que coja el hash firmado y lo "incruste" en el fichero a firmar.
Los servlets de almacenamiento sirven para permitir una comunicación bidireccional entre el navegador de usuario y Autofirma cuando ésta no puede hacerse de forma directa. Si el navegador o el dispositivo de usuario no permiten el uso de sockets (tanto por restricciones tecnológicas como de seguridad), se emplean estos servlets a modo de repositorio intermedio. Autofirma escribe datos y el navegador de usuario los lee. Según he visto, el contenido que se guarda en estos ficheros intermedios va cifrado con una clave generada por el navegador al comienzo del proceso.

El uso de server trifase y de los servlets de almacenamiento es independiente entre sí. Es decir, se puede usar server trifase sin servlets, y se pueden usar servlets sin server trifase. También se puede realizar la firma sin ninguno de los dos.
  1. Si sólo se emplea server trifase, el navegador obligatoriamente debe soportar sockets. La comunicación entre navegador y autofirma se hace de forma directa. La ventaja es que el fichero a firmar no sale del backend.
  2. Si sólo se emplean los servlets, el navegador envía a Autofirma el fichero a firmar (se envía como cadena Base 64 durante la invocación). Al terminar la firma, Autofirma deja el fichero firmado (completo) en el repositorio intermedio para que lo lea el navegador. La ventaja es que el navegador no necesita soportar sockets.
  3. Si no se emplea ninguno de los dos mecanismos anteriores, el navegador debe soportar sockets. El fichero a firmar se envía durante la invocación y, una vez firmado, se recupera a través de un socket. La ventaja es que es el método más simple.
Combinando server trifase y servlets de almacenamiento se consigue que el navegador no tenga que soportar sockets, que el fichero no salga del backend, y que los mensajes intercambiados con los servlets de almacenamiento no contengan la firma en sí, sino información acerca de su finalización.

Mensajería

A continuación un ejemplo de firma correcta. Las trazas que incorporo provienen de dos fuentes:

1 - Navegador - Autofirma

Dese el navegador se hace una invocación por protocolo a autofirma pasándole los siguientes parámetros: 
intent://sign?ver=1&op=sign&id=8wp29aKd7L4486I60UrR&key=11095593&stservlet=http://192.168.43.239/afirma-signature-storage/StorageService&format=PAdEStri&algorithm=SHA512withRSA&properties=c2VydmVyVXJsPWh0dHA6Ly8xOTIuMTY4LjQzLjIzOS9hZmlybWEtc2VydmVyLXRyaXBoYXNlLXNpZ25lci9TaWduYXR1cmVTZXJ2aWNl&dat=cHJ1ZWJhMS5wZGY=#Intent;scheme=afirma;package=es.gob.afirma;end

Aquí, los parámetros relevantes son:
  • op. Operación de firma
  • id. Es un identificador que se empleará para nombrar los ficheros de "intercambio" que gestionará el Signature Storage y Retrieve.
  • key. Algún tipo de clave generada para cifrar ciertos mensajes.
  • Dirección de estos servlets
  • formato y algortimo de firma
  • properties. Contiene los parámetros adicionales, en este caso la dirección del server trifase.
  • dat. Identificador del fichero que se va a firmar (cHJ1ZWJhMS5wZGY=) 

2 - Autofirma - Server trifase (Prefirma)

Después de que el usuario selecciona el certificado de firma, Autofirma lanza un petición contra server trifase indicándole los datos del fichero que se quiere firmar y el certificado del firmate (sólo clave pública e identificación):
POST /afirma-server-triphase-signer/SignatureService

op=pre&cop=sign&format=pades&algo=SHA512withRSA&cert=MIII(...)A4=&doc=cHJ1ZWJhMS5wZGY=&params=IwojRnJpIEZlYiAxNiAxMjowMTo0OCBDRVQgMjAxOApzZXJ2ZXJVcmw9aHR0cFw6Ly8xOTIuMTY4LjQzLjIzOS9hZmlybWEtc2VydmVyLXRyaXBoYXNlLXNpZ25lci9TaWduYXR1cmVTZXJ2aWNlCg==

Parseando los parámetros tenemos:
  • op=pre. Operación de prefirma
  • cop=sign. Código de operación de firma
  • format=pades. Firma PAdES
  • algo=SHA512withRSA. Algoritmo de firma
  • cert=MIII(...). Certificado del firmante (parte pública)
  • doc=cHJ1ZWJhMS5wZGY=. Nombre del documento que se va a firmar. En este caso "prueba1.pdf"
  • params=Iwoj(...). Parámetros adicionales. En este caso contiene la dirección completa del servidor trifase, es decir, se referencia a sí mismo
Cuando el server trifase recibe esta petición, imprime el siguiente log:
12:01:48,611 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) == INICIO FIRMA TRIFASICA ==
12:01:48,614 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Recuperamos el documento mediante el DocumentManager
12:01:48,614 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Recuperamos el documento con identificador: cHJ1ZWJhMS5wZGY=
12:01:48,615 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Buscamos el fichero: D:\tmp\afirma\entrada\prueba1.pdf
12:01:48,617 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Recuperado documento de 175247 octetos
12:01:48,617 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Formato de firma seleccionado: pades
12:01:48,617 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1)  == PREFIRMA en servidor
12:01:48,618 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Prefirma PAdES - Firma - INICIO
12:01:48,618 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Se invocan las funciones internas de prefirma PAdES
12:01:48,641 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Se ha seleccionado la generacion de CAdES para inclusion en PAdES
12:01:48,644 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Se prepara la respuesta de la prefirma PAdES
12:01:48,644 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Prefirma PAdES - Firma - FIN
12:01:48,644 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Se ha calculado el resultado de la prefirma y se devuelve
12:01:48,645 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) == FIN PREFIRMA

Básicamente lee el fichero que se solicita y prepara el hash que tendrá que deberá firmar Autofirma. Con esto se evita devolver todo el fichero.

El resultado es un XML, en base 64, con la siguiente estructura:

<xml>
 <firmas>
  <firma Id="73d6e601-7442-4737-aee2-6aa699cdc393">
   <param n="NEED_PRE">true</param>
   <param n="TIME">1518778908618</param>
   <param n="PRE">(....)</param>
   <param n="PID">WzxkYzQ5NmI1Y2ZjZDAxZDJmNTYwNGQzZWQwNTlhM2RkNz48NGM0YTA2ODc0OTM2MDg1OTNlOTU2MjYxODViYTIyNTI+XQ==</param>
  </firma>
 </firmas>
</xml>

De aquí, lo más salientable es que en el tag "PRE" da la impresión de que se devuelve la el hash a firmar, junto con información del propio certificado.

2 - Autofirma - Server trifase (Postfirma)

Autofirma realiza la firma en local empleando la clave privada del certificado de usuario, que nunca sale del dispositivo. 
Al terminar vuelve llamar al server trifase para que "incruste" esta firma en el PDF.
Los parámetros de la petición son:
POST /afirma-server-triphase-signer/SignatureService

op=post&cop=sign&format=pades&algo=SHA512withRSA&cert=MIII(...)&doc=cHJ1ZWJhMS5wZGY=&session=PHhtb(...)&params=IwojRnJpIEZlYiAxNiAxMjowMTo0OCBDRVQgMjAxOApzZXJ2ZXJVcmw9aHR0cFw6Ly8xOTIuMTY4LjQzLjIzOS9hZmlybWEtc2VydmVyLXRyaXBoYXNlLXNpZ25lci9TaWduYXR1cmVTZXJ2aWNlCg==

Los parámetros son casi los mismos que en el mensaje de prefirma, cambiando la operación. Pero, además, en esta ocasión llega un parámetro session que contiene un XML con el resultado de la firma.
El contenido de session se pinta en los logs del server trifase;
12:01:48,757 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) == INICIO FIRMA TRIFASICA ==
12:01:48,764 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Recibidos los siguientes datos de sesion para 'post':
<xml>
 <firmas>
  <firma Id="73d6e601-7442-4737-aee2-6aa699cdc393">
   <param n="PRE">MYI(...)</param>
   <param n="PK1">s/5oZ(...)</param>
   <param n="PID">WzxkYzQ5NmI1Y2ZjZDAxZDJmNTYwNGQzZWQwNTlhM2RkNz48NGM0YTA2ODc0OTM2MDg1OTNlOTU2MjYxODViYTIyNTI+XQ==</param>
   <param n="TIME">1518778908618</param>
   <param n="NEED_PRE">true</param>
  </firma>
 </firmas>
</xml>
12:01:48,765 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Recuperamos el documento mediante el DocumentManager
12:01:48,766 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Recuperamos el documento con identificador: cHJ1ZWJhMS5wZGY=
12:01:48,766 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Buscamos el fichero: D:\tmp\afirma\entrada\prueba1.pdf
12:01:48,767 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Recuperado documento de 175247 octetos
12:01:48,767 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Formato de firma seleccionado: pades
12:01:48,768 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1)  == POSTFIRMA en servidor
12:01:48,804 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Postfirma PAdES - Firma - INICIO
12:01:48,804 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Se invocan las funciones internas de postfirma PAdES
12:01:48,820 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Postfirma PAdES - Firma - FIN
12:01:48,820 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1)  Se ha calculado el resultado de la postfirma y se devuelve. Numero de bytes: 227838
12:01:48,820 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Almacenamos la firma mediante el DocumentManager
12:01:48,826 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Escribiendo el fichero: D:\tmp\afirma\salida\prueba1.pdf
12:01:48,826 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Documento almacenado
12:01:48,827 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) == FIN POSTFIRMA

Dentro del tag "PRE" se manda lo mismo que se recibió en la petición anterior. A mayores en el campo "PK1" irá la firma en sí.

Como resultado se devuelve un mensaje de OK referenciando el fichero que se acaba de firmar.
OK NEWID=cHJ1ZWJhMS5wZGY=

3 - Autofirma - Signature Storage

Cuando la firma ya se completó, Autofirma llama al Signatura Storage para decirle que cree el fichero de intercambio y que dentro guarde cierta información.
POST /afirma-signature-storage/StorageService

op=put&v=1_0&id=8wp29aKd7L4486I60UrR&dat=5.G0z2jkmD9erRoyvk0bCobg==

Se le indica que cree el fichero 8wp29aKd7L4486I60UrR y que escriba en él el texto indicado en la variable dat. Aparentemente es algún tipo de texto cifrado empleando un algoritmo de clave simétrica...

En el servidor, el Signature Storage genera los siguientes mensajes de log:
12:01:48,865 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1)  == INICIO GUARDADO == 
12:01:48,866 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Se solicita guardar un fichero con el identificador: 8wp29aKd7L4486I60UrR
12:01:48,914 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Se guardo correctamente el fichero: D:\tmp\afirma\TriStorageRetrieve\8wp29aKd7L4486I60UrR
12:01:48,915 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) == FIN DEL GUARDADO ==

4 - Navegador - Signature Retrieve

La forma que tiene el navegador de saber si la firma se ha completado o, en su caso, si se ha producido algún error, es invocando al Signature Retrieve. Se le pide el fichero cuyo nombre se preacordó al comienzo, y que contiene un texto cifrado indicativo de que la firma ha ido bien.

En el servidor, el Signature Retrieve genera los siguientes mensajes de log:
12:01:49,019 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) == INICIO DE LA RECUPERACION ==
12:01:49,020 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Se solicita el fichero con el identificador: 8wp29aKd7L4486I60UrR
12:01:49,021 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Se recupera el fichero: 8wp29aKd7L4486I60UrR
12:01:49,022 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) == FIN DE LA RECUPERACION ==
12:01:49,022 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Limpiamos el directorio temporal
12:01:49,023 INFO  [es.gob.afirma] (ajp-/0.0.0.0:8009-1) Fin de la limpieza

Al recuperar el resultado de la firma (el navegador no obtiene la firma en sí, porque esta todavía está en el directorio de salida del server trifase) el navegador sabrá si el proceso ha ido bien y, según proceda, llamar a los callbacks de éxito o error.

sábado, 3 de febrero de 2018

JBoss EAP 6.4 and Hibernate 5 - JBoss Logging problems

Problem

When working with Hibernate 5 in JBoss EAP 6.4 you can get the following error: java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V
Caused by: java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V
 at org.hibernate.internal.NamedQueryRepository.checkNamedQueries(NamedQueryRepository.java:149)
 at org.hibernate.internal.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:769)
 at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:484)
 at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
 at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
 at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
 at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:416)
 at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:401)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)

Cause

The root cause is that Hibernate 5 requires jboss-logging-3.3.0.Final.jar library, while JBoss EAP packs jboss-logging-3.1.4.GA-redhat-2.jar. This error is produced when NamedQueryRepository class is trying to call the debugf(String format, Object param1) method of org.jboss.logging.Logger class.
This method exists in version 3.3.0 but not in version 3.1.4. As Jboss loads the former one, there is one incompatibiltiy.

This is the hibernate code which calls this method, org.hibernate.internal.NamedQueryRepository:


And this is the method implementation in org.jboss.logging.Logger: 


Jboss EAP 6.4 is integrated with hibernate-core-4.2.18.Final (https://access.redhat.com/articles/112673#EAP_6), which in turn required jboss-logging-3.1.0 (https://mvnrepository.com/artifact/org.hibernate/hibernate-core/4.2.18.Final)

Solution

In thease cases the solution is obvious. Just use jboss-deployment-structure and exclude Hibernate and Logging stuff in order to use all dependencies packet in the application´s lib directory. So, the first guess would be something like this:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
 <deployment>     
  <exclude-subsystems>
   <subsystem name="jpa" /> 
   <subsystem name="logging" />
  </exclude-subsystems>
  
  
  <exclusions>     
   <module name="org.hibernate"/>
   <module name="javax.persistence.api"/>
   <module name="org.hibernate.envers"/>
   <module name="org.hibernate.validator"/>
   <module name="org.hibernate.commons-annotations"/>  
   <module name="org.jboss.as.jpa.hibernate"/> 
   <module name="org.jboss.as.jpa"/> 
   <module name="org.jboss.as.jpa.util"/>  
   <module name="org.jboss.as.jpa.hibernate "/> 
   <module name="org.jboss.as.jpa.spi"/>  
   <module name="org.jboss.as.osgi.jpa"/>
   
   <module name="org.jboss.logging" /> 
   <module name="org.apache.commons.logging" />  
   <module name="org.apache.log4j" />  
   <module name="org.slf4j" />  
   <module name="org.jboss.logging.jul-to-slf4j-stub" />  
  </exclusions>
       
 </deployment>
</jboss-deployment-structure>

Unfortunately this doesn't work. There must be some kind of bug in Jboss EAP 6.4 and jboss-logging 3.1.0 is still be using. For the record, this do works with Jboss EAP 6.2.

After some digging, the solution appears to be to exclude org.jboss.resteasy.resteasy-jaxrs too. The final jboss-deployment-structure will be this:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
 <deployment>     
  <exclude-subsystems>
   <subsystem name="jpa" /> 
   <subsystem name="logging" />
  </exclude-subsystems>
  
  
  <exclusions>
   <module name="org.jboss.resteasy.resteasy-jaxrs"/>     
   <module name="org.hibernate"/>
   <module name="javax.persistence.api"/>
   <module name="org.hibernate.envers"/>
   <module name="org.hibernate.validator"/>
   <module name="org.hibernate.commons-annotations"/>  
   <module name="org.jboss.as.jpa.hibernate"/> 
   <module name="org.jboss.as.jpa"/> 
   <module name="org.jboss.as.jpa.util"/>  
   <module name="org.jboss.as.jpa.hibernate "/> 
   <module name="org.jboss.as.jpa.spi"/>  
   <module name="org.jboss.as.osgi.jpa"/>
   
   <module name="org.jboss.logging" /> 
   <module name="org.apache.commons.logging" />  
   <module name="org.apache.log4j" />  
   <module name="org.slf4j" />  
   <module name="org.jboss.logging.jul-to-slf4j-stub" />  
  </exclusions>
       
 </deployment>
</jboss-deployment-structure>