Buscar este blog

sábado, 23 de febrero de 2019

Connect Apache Web Server and Apache Tomcat

We have Apache Web Server (httpd) as front-end and Apache Tomcat as back-end.
This solution is based on mod_proxy and AJP connector.

Apache web server config

You have to configure mod_proxy in apache httpd.
I added the following conf file in conf.d directory:

<VirtualHost 172.22.215.219:80>
    Servername sisifo.domain1
 
    RewriteEngine on
    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]
 
 
    LogLevel info
    ErrorLog  /var/log/httpd/sisifo.domain1_error_log
    CustomLog /var/log/httpd/sisifo.domain1_access_log combined
</VirtualHost>
 
 
 
<VirtualHost 172.22.215.219:443>
    Servername sisifo.domain1
 
    SSLEngine on
    SSLProtocol all -SSLv2 -SSLv3
    SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA128:DHE-RSA-AES128-GCM-SHA384:DHE-RSA-AES128-GCM-SHA128:ECDHE-RSA-AES128-SHA384:ECDHE-RSA-AES128-SHA128:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA128:DHE-RSA-AES128-SHA128:DHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA384:AES128-GCM-SHA128:AES128-SHA128:AES128-SHA128:AES128-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4
 
    SSLCertificateKeyFile /etc/pki/tls/private/localhost.key
    SSLCertificateFile /etc/pki/tls/certs/localhost.crt
    #SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt
    #SSLCACertificatePath /etc/httpd/certs/ca
 
    <Location "/">
    Order Deny,Allow
                    Deny from all
                    Allow from all
                    #Allow from 10.224.0.0/12
    </Location>
 
    ##########
 
    ProxyRequests Off
    ProxyPassMatch ^/(.*)$ balancer://tomcat_cluster/$1$2 stickysession=JSESSIONID|jsessionid
 
    <Proxy balancer://tomcat_cluster>
      BalancerMember ajp://[TOMCAT1]:8009 loadfactor=1 route=jvmTomcat1 ping=1
   BalancerMember ajp://[TOMCAT2]:8009 loadfactor=1 route=jvmTomcat2 ping=1
       
      ProxySet lbmethod=byrequests
      ProxySet nofailover=off
      ProxySet timeout=300
    </Proxy>
     
    ##########
 
    LogLevel info  
    ErrorLog /var/log/httpd/sisifo.domain1_ssl_error_log
    CustomLog /var/log/httpd/sisifo.domain1_ssl_access_log combined
</VirtualHost>

Tomcat config

You have to edit $TOMCAT_HOM/config/server.xml of each tomcat instance and set an unique value for  jvmRoute attribute. This attribute is in Engine tag.

<Engine defaultHost="localhost" name="Catalina" jvmRoute="jvmTomcat1">

ORA-00942 Table or View Does Not Exist - Identify target table

During the installation of a third party application which uses Oracle Database, I found the following error in server log:
ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
The error was clear, the application was trying to execute an SQL statement against a table that was not in database, or the user did not have permissions. But, which table or view was that?

In order to discover the SQL the client was invoking I found this post: https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2975793633621#284628100346267414. In my post I´ll just refactor it in order to easy understanding.

The idea behind of this is to register a trigger for server error 942, obtain  context information and the sql being executed, and save all this info in other table. The complete code is as follow:
-- Table to store errors
create table ERROR942 (id number, 
    "time" timestamp,
    "event" varchar(100), 
    "user" varchar(100),
    "server_error" varchar2(4000),
    "sql" varchar2(4000) );

-- Sequence to generate the table id
create sequence SEQ_ERROR942;


-- Trigger to insert errors in table
create or replace trigger TGR_SERVER942
after servererror on database
declare
   l_sql_text ora_name_list_t;
   full_sql varchar2(4000);
   l_n number;
begin
    if ( is_servererror(942) )
    then        
        full_sql := '';
        l_n := ora_sql_txt( l_sql_text );
        for i in 1 .. l_n
        loop
           full_sql := full_sql || l_sql_text(i);
        end loop;
        
         insert into ERROR942 values (SEQ_ERROR942.nextval, current_date, ora_sysevent, ora_login_user,  ora_server_error(1), full_sql);
    end if;
end;

commit;

The main aspects here are:
  • We create ERROR942 table in order to store all errors
  • We create SEQ_ERROR942 in order to generate the previous table ids
  • We create TGR_SERVER942 trigger in order to capture server errors and store then in the table. 
You can test the solution as follow:
select * from UNEXIST_TABLE;

select * ERROR942;

jueves, 17 de enero de 2019

Apache httpd - Windows 10

In order to disable port 80 in windows 10 and to allow Apache Web Server start, execute de following command as administrator:
net stop branchcache


sábado, 1 de diciembre de 2018

Create timestamp certificate

This procedure is explained with KeystoreExplorer (http://keystore-explorer.org/)

1 - Create the CA

The important thing is to set the following extensions:
  • Basic Constraints: Subject is a CA
  • Key Usage: Certificate Signing


















2 - Create the timestamp certificate

The important thing is to set the following extensions:
  • Extended Key Usage: Time Stamping [Critial extension]



sábado, 28 de julio de 2018

Autofirma - Gestión de actualizaciones

Un tema bastante molesto relacionado con Autofirma es el control de las actualizaciones. Al ser un componente instalado en el equipo del usuario es él quien, en última instancia, decide qué versión instalar y cuándo actualizarla.

Cuando se desarrolla una aplicación web generalmente se prueba contra una versión concreta de @Firma, Autofirma incluida, y se certifica para su uso con ella. La parte de servidor no presenta ningún problema, puesto que se tiene control total sobre ella, no así la parte cliente. En cualquier momento puede publicarse una nueva versión de Autofirma y, gracias a la función automática de comprobación de actualizaciones, el usuario puede actualizarla. En este caso podrían presentarse problemas si esta nueva versión no es totalmente compatible con la anterior.

En este post se explicará cómo hace Autofirma la gestión y control de las actualizaciones y de qué forma se podría intervenir para prevenir los avisos al usuario.


Cada vez que se inicia Autofirma, ésta revisa si está configurada para comprobar de forma automática si existe una nueva actualización. En caso afirmativo, consulta en una URL pública cuál es la última versión disponible y la compara con su versión interna. Si la primera es mayor a la segunda, entonces redirige al usuario a una segunda URL para que proceda a su descarga manual.


Concretamente, al URL de descarga a día de hoy es http://firmaelectronica.gob.es/Home/Descargas.html



Existe una opción de configuración del componente que permite deshabilitar la consulta automática de actualizaciones, pero debe establecerlo explícitamente así el usuario, puesto que por defecto ya viene marcada.




A nivel técnico, el proceso descrito se controla de dos modos:
  1. Gestión de preferencias de usuario
  2. Consulta de actualizaciones
La gestión de preferencias de usuario se hace desde la  clase es.gob.afirma.standalone.ui.preferences.PreferencesManager. Esta clase gestiona dos objetos de propiedades, las preferencias guardadas y las preferencias por defecto.
static {
 preferences = Preferences.userNodeForPackage(PreferencesManager.class);

 properties = new Properties();
 try {

  properties.load(PreferencesManager.class.getResourceAsStream("/properties/preferences.properties" //$NON-NLS-1$
  ));
 } catch (final Exception e) {
  LOGGER.severe(
    "No han podido cargarse los valores por defecto del fichero de configuracion de preferencias, se usaran los valores por defecto: " //$NON-NLS-1$
      + e);
 }

}

Las preferencias se guardan empleando la clase java.util.java.util.prefs.Preferences, que en el caso de windows, persiste bajo la clave de registro HKEY_CURRENT_USER\Software\JavaSoft\Prefs\es\gob\afirma\standalone\ui\preferences.
Las preferencias por defecto se guardan dentro del propio jar,en el fichero preferences.properties.
(...)
#Panel General de Preferencias
signatureAlgorithm = SHA256withRSA
omitAskOnClose = false
hideDnieStartScreen = false
checkForUpdates = true
useAnalytics = true
enabledJmulticard = true
defaultSignatureFormatPdf = PAdES
defaultSignatureFormatOoxml = OOXML (Office Open XML)
defaultSignatureFormatFacturae = FacturaE
defaultSignatureFormatOdf = ODF (Open Document Format)
defaultSignatureFormatXml = XAdES
defaultSignatureFormatBin = CAdES
(...)

La consulta de actualizaciones se hace desde la clase es.gob.afirma.standalone.updater.
private static void loadProperties() {
 if (updaterProperties != null) {
  return;
 }
 updaterProperties = new Properties();
 try {
  updaterProperties.load(Updater.class.getResourceAsStream("/properties/updater.properties")); //$NON-NLS-1$
 }
 catch (final Exception e) {
  LOGGER.severe(
   "No se ha podido cargar el archivo de recursos del actualizador: " + e //$NON-NLS-1$
  );
  updaterProperties = new Properties();
 }
}

Las propiedades de consulta de versión se mantienen en un fichero independiente llamado updater.properties:
# Numero de version visible
currentVersionText.WINDOWS=1.6.4
currentVersionText.LINUX=1.6.4
currentVersionText.MACOSX=1.6.4

# Numero de version interno (numero entero). Si es par se trata de una version preliminar.
# Este numero no avanzara dentro de las distintas versiones preliminares anteriores a una
# version final. Cuando se establezca un numero impar, se identifica una version final.
currentVersion.WINDOWS=10
currentVersion.LINUX=10
currentVersion.MACOSX=10

# AutoFirma en Windows buscara si hay nuevas versiones y lo notificara al
# usuario remitiendole a la pagina de descargas
url=http://estaticos.redsara.es/comunes/autofirma/autofirma.version
updateSite=http://firmaelectronica.gob.es/Home/Descargas.html

Tal y como se aprecia la URL de consulta de versión es http://estaticos.redsara.es/comunes/autofirma/autofirma.version, que actualmente devuelve el valor 8.


Por tanto, de cara a tener un mayor control sobre el proceso de actualización se podrían hacer las siguientes modificaciones sobre estos ficheros:
  1. En el fichero preferences.properties configurar que no se marque por defecto la opción de comprobación de actualizaciones. Bastaría con cambiar la propiedad checkForUpdates.
  2. En el fichero updater.properties configurar la URL de comprobación de versión a una dirección controlada, y que se devuelva la versión compatible con la aplicación en la que se use. Bastaría con cambiar la propiedad url.


En cualquier caso, una vez hecho el cambio habría que recompilar el código y generar de nuevo el instalador: Autofirma - Compilación manual para Windows