Buscar este blog

martes, 11 de mayo de 2021

WS-Security - UsernameToken - Calculate Password Digest

How to calculate Password Digest WS-Security Soap Header: https://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0.pdf




Soap Header example:

<soapenv:Header>
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
        <wsse:UsernameToken wsu:Id="UsernameToken-C822D870BE48B556D816202993974805">
            <wsse:Username>Bob</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">K1ZqechO0a0UEVYOi4c5AE0neng=</wsse:Password>
            <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">Wa/iIgpLm2ndpHgW8Ys46w==</wsse:Nonce>
            <wsu:Created>2021-05-11T19:03:57.479Z</wsu:Created>
        </wsse:UsernameToken>
    </wsse:Security>
</soapenv:Header>


Source code:

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

public class CalclatePaswordText {
	
	public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		System.out.println(calcularPasswordDigest("P606+84STYF8yIsGfey1iw==", "2021-05-11T19:03:57.479Z", "secret"));
	}

	
	private static String calcularPasswordDigest (String nonce, String created, String password) throws UnsupportedEncodingException {
		ByteBuffer buf = ByteBuffer.allocate(1000);
		buf.put(Base64.decodeBase64(nonce));
		buf.put(created.getBytes("UTF-8"));
		buf.put(password.getBytes("UTF-8"));
		byte[] toHash = new byte[buf.position()];
		buf.rewind();
		buf.get(toHash);
		byte[] hash = DigestUtils.sha(toHash);
		return Base64.encodeBase64String(hash);
	}
}


sábado, 21 de noviembre de 2020

qperf - Monitoring network bandwidth and latency

 

I will use qperf: https://docs.oracle.com/cd/E86824_01/html/E54763/qperf-1.html

You can check a detailed example here: https://access.redhat.com/solutions/2122681


In destination machine you need to run the following command:

qperf &

You need to open ports 19765 and 19766 in this machine.


In source machine you need to create the following script, in my case, network-monitoring.sh:

#!/bin/sh

echo "$(date +'%Y/%m/%d %H:%M:%S') comprobando red"
HOSTNAME=$(hostname)
DESTINO=[destinationMachine]

ANCHO_BANDA=$(qperf -v -ip 19766  -t 5 --use_bits_per_sec  $DESTINO  tcp_bw | grep bw | awk '{print $3";"$4}' | sed -n '2 p')
LATENCIA=$(qperf -v -ip 19766  -t 5 --use_bits_per_sec  $DESTINO  tcp_lat | grep latency | awk '{print $3";"$4}')


echo "$(date +'%d/%m/%Y');$(date +'%H:%M:%S');$HOSTNAME;$DESTINO;$ANCHO_BANDA;$LATENCIA" >> /root/network-monitoring.csv

 

jueves, 8 de octubre de 2020

Oracle - Count all rows in all tables in a database

 Count all rows in all tables in a database

CREATE GLOBAL TEMPORARY TABLE TMP_TOTALES (
  TABLA VARCHAR2(32),
  TOTAL NUMBER
)
ON COMMIT DELETE ROWS;
         
         

set serveroutput ON;
DECLARE        
          total NUMBER:=NULL;
          cursor tablas_cursor IS select TABLE_NAME from all_Tables where owner = 'myUser' AND NOT table_name like '%$%' ORDER BY TABLE_NAME ASC;
           
          v_sqltxt        varchar2(32767);
          no_privs        exception;
         pragma exception_init(no_privs, -1031);
 BEGIN
     FOR tabla IN tablas_cursor loop
        v_sqltxt:='select count(1) from '|| tabla.TABLE_NAME ||'';      
        BEGIN
          EXECUTE immediate v_sqltxt INTO total;
          INSERT INTO TMP_TOTALES(TABLA, TOTAL) VALUES (tabla.TABLE_NAME, total);
          dbms_output.put_line(tabla.TABLE_NAME || ' ' || total);                  
         END;     
      END loop;        
END;
/


select * from TMP_TOTALES ORDER BY TOTAL DESC;

domingo, 23 de agosto de 2020

Oracle DB - Check tablespaces usage

 Tablespaces and datafiles usage:

select
    DTFIL.tablespace_name, DTFIL.file_name,
    ROUND(DTFIL.bytes/power(1024,2),2) USED_MB,
    DTFIL.autoextensible,
    Round(DTFIL.maxbytes/power(1024,3), 2) Maxsize_GB,
    Round((DTFIL.bytes / DTFIL.maxbytes)*100, 2) USED,
    round((DTFIL.increment_by * TBSP.block_size)/power(1024,2), 2) step_MB,
    DTFIL.increment_by
from
    dba_data_files DTFIL join dba_tablespaces TBSP on DTFIL.TABLESPACE_NAME = TBSP.TABLESPACE_NAME
order by DTFIL.tablespace_name, DTFIL.file_name;

Tablespaces usage, including datafiles:

select
    DTFIL.tablespace_name,
    Round((sum(DTFIL.bytes) / sum(DTFIL.maxbytes))*100, 2) USED
from
    dba_data_files DTFIL join dba_tablespaces TBSP on DTFIL.TABLESPACE_NAME = TBSP.TABLESPACE_NAME
group by DTFIL.tablespace_name
order by 2 desc;


Tablespaces usage acording with actual allocated space:

-- Work tablespaces
SELECT
       a.tablespace_name AS tablespace_name,
       (100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc)* 100)) percent_used,
       (100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc)* 100, 2)) pct_used,
       round(a.bytes_alloc / 1024/ 1024,2) allocated,
       round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024/ 1024,2) used,      
       round(nvl(b.bytes_free, 0) / 1024/ 1024,2) free,
       a.datafiles
from (select
        f.tablespace_name,
        sum(f.bytes) bytes_alloc,
        sum(decode(f.autoextensible, 'yes', f.maxbytes, 'N0',f.bytes)) maxbytes,
        count(1) datafiles
      FROM
        dba_data_files f
      GROUP BY tablespace_name) a,
    (SELECT 
        f.tablespace_name,
        SUM(f.bytes) bytes_free
     FROM
        dba_free_space f
     GROUP BY tablespace_name) b
WHERE
    a.tablespace_name = b.tablespace_name(+)
 
UNION ALL
 
-- TEMP Tablespaces
select
    t.tablespace_name,
    t.percent_used,
    t.pct_used,
    t.allocated,
    t.used,
    t.free,
    f.datafiles
from
    (select
        h.tablespace_name as tablespace_name,
        (100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free))* 100)) percent_used,
        (100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free))* 100,2)) pct_used,
        round(sum(h.bytes_free + h.bytes_used) / 1048576,2) allocated,
        round(sum(nvl(p.bytes_used, 0))/ 1048576,2) used,
        round(sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / 1048576,2) free
    from
        sys.gv_$TEMP_SPACE_HEADER h,
        sys.gv_$Temp_extent_pool p,
        dba_temp_files f
        where
            p.file_id(+) = h.file_id
            and p.tablespace_name(+) = h.tablespace_name
            and f.file_id = h.file_id
            and f.tablespace_name = h.tablespace_name
        group by h.tablespace_name ) t,
    (select tablespace_name, count(1) datafiles from dba_temp_files group by tablespace_name ) f
where
    t.tablespace_name = f.tablespace_name
ORDER BY 3 desc

Oracle DB - SQLPLUS connect

Setup

System properties configuration
export ORACLE_HOME=/usr/lib/oracle/11.2/client64
export TNS_ADMIN=$ORACLE_HOME/network/admin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib
export PATH=$PATH:$ORACLE_HOME/bin

Connection

Connect with tnsnames from command line.
sqlplus username/pass@'(description=(address=(protocol=tcp)(host=myServer)(port=1521))(connect_data=(sid=mySID)))'



Connect with tnsnames from file
sqlplus username/pass@ORCL

Where tnsnames.ora file is as follows.
ORCL=
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = myServer)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = myService)
    )
  )

Run SQL file

Run SQL from command line
sqlplus username/pass@'(description=(address=(protocol=tcp)(host=myServer)(port=1521))(connect_data=(sid=mySID)))' @myFile.sql

SQL file
set linesize 100 pagesize 50

select
    DTFIL.tablespace_name,
    Round((sum(DTFIL.bytes) / sum(DTFIL.maxbytes))*100, 2) USED
from
    dba_data_files DTFIL join dba_tablespaces TBSP on DTFIL.TABLESPACE_NAME = TBSP.TABLESPACE_NAME
group by DTFIL.tablespace_name
order by 2 desc;

exit;

martes, 14 de abril de 2020

CentOS check system info

Show system inf for a CentOS server:
# CPU info
 more /proc/cpuinfo

# Memory info
 dmidecode -t memory
 dmidecode -t memory | grep -i "installed size"

# Operatin System
 cat /etc/os-release
 hostnamectl
 uname -r

viernes, 10 de abril de 2020

Axis 1 - SLF4J Logging

In this post I´ll show you how to configure Axis 1 Logging with SLF4J-Log4j. The main purpose is to trace incoming and outcoming messages.

Axis uses Apache commons-logging as logging implementation. This dependecy is configured as runtime in Axis pom, so it will not be imported as transitive.
Any way, if you have commons-logging library in your project, exclude it.

As you exclude commons-logging, you need to add the corresponding slf4j bridge, i.e., jcl-over-slf4j library.

Add a file called common-logging.properties in src/main/resoruces with the following content:
org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.SLF4JLogFactory

When you configure log4j logging, for example in log4j.xml file,  add the following categories:
<logger name="org.apache.axis.providers" additivity="false">
 <level value="debug"/>
 <appender-ref ref="FILE"/>
</logger>

<logger name="org.apache.axis.transport.http" additivity="false">
 <level value="debug"/>
 <appender-ref ref="FILE"/>
</logger>

org.apache.axis.providers is used by web service providers in order to trace incoming messages and outcoming responses.

org.apache.axis.transport.http is used by web service clientes in order to trace outcoming messages and incoming responses.

sábado, 28 de marzo de 2020

CentOS 6 - Port forwarding

I have the following scenario:
  1. My computer
  2. CentOS 6.5 intermediate server IP_CENTOS
  3. Third party service: https://IP_SERVICE/domain/service-path 
From my computer I can reach the CentOS server, but not the third party service.
From CentOS server you can reach the third party service.

I want to use CentOS server as a bridge in order to forward traffic from my computer to the third party service and vice versa.

Set configuration

Step 1

Enable ip forward in iptables:
 
    echo 1 >/proc/sys/net/ipv4/ip_forward

Step 2

Configure forwarding:
    iptables -t nat -A PREROUTING -p tcp --dport 9443 -j DNAT --to-destination [IP_SERVICE]:443
    iptables -t nat -A POSTROUTING -p tcp -d [IP_SERVICE] --dport 443 -j SNAT --to-source [IP_CENTOS]


Here you have:
  • 9443 is the fake port used in CentOS server.
  • IP_SERVICE is the IP address of the third party service
  • 443 is the default HTTPS port, as the third party service is in https://xxxxxx
  • IP_CENTOS is the IP address of the CentOS server

Step 3

Save the rules:
    service iptables save
    service iptables reload

You can check the configuration as follow:
    iptables -t nat --line-numbers -L

    more /etc/sysconfig/iptables

Test

From My Computer you can check to access to https://IP_CENTOS:9443/domain/service-path 

Rollback configuration

In order to restore configuration and delete all previous work, do as follows:
    echo 0 >/proc/sys/net/ipv4/ip_forward

Check the rules and delete them one by one:
    iptables -t nat --line-numbers -L

    iptables -t nat -D PREROUTING|POSTROUTING [num]

jueves, 19 de marzo de 2020

Apache Camel - Proxy route

In this example I will configure a Camel route proxy. Camel will publish a http servlet and redirect all request to a external provider.

Configuration

You need to configure as follow:
  • Configure dependencies
  • Configure Camel servlet
  • Configure Camel route

Configure dependencies

In pom.xml:
<dependency>
 <groupId>org.apache.camel</groupId>
 <artifactId>camel-servlet</artifactId>
 <version>${camel.version}</version> 
</dependency>

<dependency>
 <groupId>org.apache.camel</groupId>
 <artifactId>camel-http4</artifactId>
 <version>${camel.version}</version> 
</dependency>

Configure Camel servlet

In web.xml:
<servlet>
 <servlet-name>CamelServlet</servlet-name>
 <display-name>Camel Http Transport Servlet</display-name>
 <servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
</servlet>

<servlet-mapping>
 <servlet-name>CamelServlet</servlet-name>
 <url-pattern>/services/*</url-pattern>
</servlet-mapping>


Or, alternatively, in java:
import javax.servlet.annotation.WebServlet;

@WebServlet(name = "CamelServlet", urlPatterns = { "/services/*" }, loadOnStartup = 1)
public class CamelRestServlet extends org.apache.camel.component.servlet.CamelHttpTransportServlet { 
 private static final long serialVersionUID = 2886685336873526067L;
 //Servlet secuestrado por Camel para procesar las peticiones de entrada a su ruta proxy
}

Configure Camel route

In camel-context.xml:
<camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">
 <route>
  <from uri="servlet:/service1?matchOnUriPrefix=true"/>
  <log message="Redirecting to service1"/>
  <to uri="http4://otherDomain:8080/otherApp/service1?bridgeEndpoint=true&amp;throwExceptionOnFailure=false"/>
 </route>
 
 
 <route>
  <from uri="servlet:/service2?matchOnUriPrefix=true"/>
  <log message="Redirecting to service2"/>
  <to uri="http4://otherDomain:8080/otherApp/service2?bridgeEndpoint=true&amp;throwExceptionOnFailure=false"/>
 </route>
</camelContext>

Testing

In your app is published in http://localhost:8080/myApp, then you will get the following behaviour:

When calling http://localhost:8080/myApp/services/service1/test?a=b Camel will redirect to http://otherDomain:8080/otherApp/service1/test?a=b

viernes, 13 de marzo de 2020

Tomcat -JConsole - Remote connection

This is the procedure to connect JConsole to a remote tomcat server.

[Remote] Configure tomcat

Edit/create a file $TOMCAT_HOME/bin/setenv.sh.

Add de following JAVA_OPTS params:

  • -Dcom.sun.management.jmxremote
  • -Dcom.sun.management.jmxremote.port=9999
  • -Dcom.sun.management.jmxremote.rmi.port=9998
  • -Dcom.sun.management.jmxremote.authenticate=false
  • -Dcom.sun.management.jmxremote.ssl=false
You can add them as follow:
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.rmi.port=9998 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
Restart tomcat.

[Remote] Configure host

You need to open these ports in order to allow remote connections from other machines. You can do that by using "firewall-cmd":
   firewall-cmd --zone=public --add-port=9999/tcp
   firewall-cmd --zone=public --add-port=9998/tcp
   firewall-cmd --zone=public --permanent --list-ports
   firewall-cmd --zone=public --list-ports

[Local] Configure JConsole

From local host launch JConsole targeting 9999 (in my case, the target server is in PRE-C01-SRV01)






If you have problems you can enable JConsole log by creating a logging config file, for example, jconsole-logging.properties:
Logging.properties

handlers = java.util.logging.ConsoleHandler


.level = INFO

java.util.logging.ConsoleHandler.level = FINEST

java.util.logging.ConsoleHandler.formatter = \

java.util.logging.SimpleFormatter

// Use FINER or FINEST for javax.management.remote.level - FINEST is

// very verbose...

javax.management.level = FINEST

javax.management.remote.level = FINEST

Launch JConsole from command line with the following params:
    jconsole -J-Djava.util.logging.config.file=jconsole-logging.properties

jueves, 12 de marzo de 2020

Camel - CXF - Remove SOAP Headers

import java.util.List;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.headers.Header;

public class ReaProcessor implements Processor {  
 
 @Override
 public void process(Exchange exchange) throws Exception {
  @SuppressWarnings("unchecked")
  final List<SoapHeader> soapHeaders = (List<SoapHeader>) exchange.getIn().getHeader(Header.HEADER_LIST);
  soapHeaders.clear();   
 }

}
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://camel.apache.org/schema/cxf"
 xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
              http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd
              http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
              http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd
              http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd">

 <bean id="reaProcessor" class="xxxxxxxxxxx.ReaProcessor"></bean>
 
 <!-- CAMEL CONTEXT -->
 <camelContext id="camelContextRea" xmlns="http://camel.apache.org/schema/spring">
  <!-- CAMEL ROUTE -->
  <route id="ReaWSRoute">
   <description>
    Ruta camel para Rea
   </description>
   
   <from uri="cxf:bean:servicioReaProvider?loggingFeatureEnabled=true&amp;dataFormat=POJO" />
   
   <to uri="cxf:bean:servicioReaClient?loggingFeatureEnabled=true&amp;dataFormat=POJO" />
   
   <process ref="reaProcessor"></process>
  </route>
 </camelContext>

</beans>

domingo, 12 de enero de 2020

MavenReportException: Error while generating Javadoc

Error message:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:3.1.1:jar (attach-javadocs) on project XXXXXX: MavenReportException: Error while generating Javadoc:
[ERROR] Exit code: 1 - /src/main/java/xxxxxxxxxxxxxxxx/Xxxxxxxxxxxxxx.java:28: warning: no description for @param
[ERROR] * @param clazz
[ERROR] ^

Solution, in pom.xml:
<plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-javadoc-plugin</artifactId>
 <version>2.9</version>
 <configuration>
  <additionalparam>-Xdoclint:none</additionalparam>
 </configuration>
</plugin>

jueves, 15 de agosto de 2019

Determine OCSP provider from certificate

Given a certificate, if you want to know whether there is an OCSP provider associated with it, you can get this information from the own certificate.

OCSP information is encoded inside " Authority Information Access" field. Open de certificate with some tool, for example, windows default program, and look for its value. You can also use openssl:
# openssl x509 -in PF_ACTIVO_EIDAS.cer -text -noout | grep OCSP
               OCSP - URI:http://ocspusu.cert.fnmt.es/ocspusu/OcspResponder

# openssl x509 -in PF_ACTIVO_EIDAS.cer -ocsp_uri -noout
http://ocspusu.cert.fnmt.es/ocspusu/OcspResponder


Note that the certificate must be in PEM format.

In order to call the OCSP service you need the certificate serial number (the one you want to check) and the CA chain, as described in a previous post:
# openssl x509 -in PF_ACTIVO_EIDAS.cer -serial -noout
serial=0902999F8486CAA55821C9A36BFAA499

# openssl ocsp -issuer AC_FNMT_Usuarios.pem -serial 0x0902999F8486CAA55821C9A36BFAA499 -url http://ocspusu.cert.fnmt.es/ocspusu/OcspResponder -CAfile AC_Raiz_FNMT-RCM_SHA256.pem
Response verify OK
0x0902999F8486CAA55821C9A36BFAA499: good
        This Update: Aug 15 17:04:27 2019 GMT
        Next Update: Aug 15 18:04:27 2019 GMT


Another important subject with OCSP is that when you ask for a certificate, often, the response is signed by the provider. If you need to determine wich certificate it is, for example, in order to store it in a truststore, you can add the "-resp_text" flag:
# openssl ocsp -resp_text -issuer AC_FNMT_Usuarios.pem -serial 0x0902999F8486CAA55821C9A36BFAA499 -url http://ocspusu.cert.fnmt.es/ocspusu/OcspResponder -CAfile AC_Raiz_FNMT-RCM_SHA256.pem
OCSP Response Data:
    OCSP Response Status: successful (0x0)
    Response Type: Basic OCSP Response
    Version: 1 (0x0)
    Responder Id: C = ES, O = FNMT-RCM, OU = Ceres, CN = Servidor OCSP AC FNMT Usuarios
    Produced At: Aug 15 17:08:28 2019 GMT
    Responses:
    Certificate ID:
      Hash Algorithm: sha1
      Issuer Name Hash: ACB3EDC1572E4DA000C62307BEBBC1953AA27423
      Issuer Key Hash: B1D44FC42379FA440509C6EB39CFE835B0B82064
      Serial Number: 0902999F8486CAA55821C9A36BFAA499
    Cert Status: good
    This Update: Aug 15 17:08:28 2019 GMT
    Next Update: Aug 15 18:08:28 2019 GMT

    Response Extensions:
        OCSP Nonce:
            04109B882F00D026E282BE6D2194DFC96845
    Signature Algorithm: sha256WithRSAEncryption
         14:87:45:a1:ad:37:14:7e:d4:3b:7f:bf:7d:6a:cc:2e:5f:01:
         81:2a:fc:20:96:b4:b7:27:01:64:6d:fd:ab:09:a8:26:49:b1:
         15:16:86:c9:7c:c1:3c:79:d8:d7:a2:55:10:be:2d:a5:b9:ba:
         f8:db:19:7f:9c:8a:ba:44:3e:ec:5d:9a:62:8e:85:1b:6b:7e:
         e9:b9:e0:ce:b2:45:0b:fa:9c:ad:bd:5e:5e:14:0c:ae:15:89:
         68:83:77:92:a7:80:b2:7f:37:94:cc:98:26:73:c8:53:86:4f:
         6a:45:5a:70:0f:30:ce:83:66:72:2c:ae:0f:06:93:17:15:1d:
         9f:1f:14:53:ae:a9:32:cb:7f:14:5f:4d:e9:29:fc:6d:f0:a2:
         f2:c1:fb:e4:1b:b9:ea:6e:5f:2d:0b:9b:e5:5f:6b:58:c8:5a:
         09:43:f6:27:91:db:da:56:c1:dc:48:aa:4a:86:a5:28:5f:94:
         65:f9:36:fe:d1:b3:0c:be:66:ad:5f:3b:26:38:25:a4:67:ff:
         1e:4c:b3:5d:88:46:c0:5a:2b:67:42:47:4e:d8:67:0e:2d:2c:
         45:c2:43:f4:33:4e:ca:bc:df:ff:a9:e0:79:b0:d3:6f:90:c7:
         8b:29:6f:14:52:d9:5a:82:c4:b3:a6:31:9b:12:96:33:dd:41:
         c2:51:9d:92
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            01:f0:a3:e9:d7:e3:93:01:5c:d2:91:e3:26:66:bc:43
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=ES, O=FNMT-RCM, OU=Ceres, CN=AC FNMT Usuarios
        Validity
            Not Before: May  8 08:22:59 2019 GMT
            Not After : Nov  8 09:22:59 2019 GMT
        Subject: C=ES, O=FNMT-RCM, OU=Ceres, CN=Servidor OCSP AC FNMT Usuarios
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:d7:49:d2:98:b6:41:60:3d:28:1b:06:ce:f9:10:
                    53:b6:7b:ff:01:29:43:fc:64:58:22:7b:90:7b:79:
                    07:f5:41:db:e7:ec:3e:27:88:5c:c0:d1:7e:8f:3c:
                    c8:68:c6:8e:33:b4:78:3d:9d:65:30:ec:77:a9:6f:
                    65:ca:c9:62:78:3e:36:d6:1b:eb:cb:da:33:c8:35:
                    94:02:03:60:53:75:df:34:37:42:65:c7:9d:d8:bf:
                    b8:a3:18:5a:ea:17:9d:18:e6:80:0e:6e:5f:27:32:
                    04:93:6c:05:d2:db:ee:aa:dc:98:3f:af:39:ec:aa:
                    f9:eb:39:13:c5:7e:9b:cd:7e:d6:21:82:72:22:46:
                    d5:e1:9d:30:f1:fc:c2:02:3b:32:a5:f8:87:4f:e1:
                    a1:8a:3c:08:7f:e1:e3:84:17:29:2a:d2:7d:f8:82:
                    9b:88:13:38:d1:c1:a8:fd:71:e8:59:d4:e5:6f:9d:
                    97:a8:ef:fa:d3:b7:20:4f:3d:e1:55:19:62:96:1e:
                    94:53:80:18:42:08:6e:24:9c:e6:fd:6e:9e:08:34:
                    f9:fa:75:1d:34:dc:55:89:2e:bf:55:52:9c:ce:0e:
                    8e:bb:2f:9b:91:c5:91:84:cb:06:74:8e:41:54:2a:
                    b3:7e:dc:ee:05:1a:cf:07:8d:62:8f:d7:43:5a:0c:
                    ad:eb
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage: critical
                Digital Signature, Non Repudiation
            X509v3 Extended Key Usage: critical
                OCSP Signing
            X509v3 Subject Key Identifier:
                BB:6F:79:C3:04:25:98:D6:62:C7:CD:71:25:AF:C9:61:B0:12:3A:8B
            X509v3 Authority Key Identifier:
                keyid:B1:D4:4F:C4:23:79:FA:44:05:09:C6:EB:39:CF:E8:35:B0:B8:20:64

            OCSP No Check:

            Authority Information Access:
                CA Issuers - URI:http://www.cert.fnmt.es/certs/ACUSU.crt

            X509v3 Certificate Policies:
                Policy: 1.3.6.1.4.1.5734.3.10.15
                  CPS: http://www.cert.fnmt.es/dpcs/
                  User Notice:
                    Explicit Text: Sujeto a las condiciones de uso expuestas en la DPC de la FNMT-RCM (C/Jorge Juan 106-28009-Madrid-España)

            X509v3 CRL Distribution Points:

                Full Name:
                  URI:ldap://ldapusu.cert.fnmt.es/cn=CRL2503,cn=AC%20FNMT%20Usuarios,ou=CERES,o=FNMT-RCM,c=ES?certificateRevocationList;binary?base?objectclass=cRLDistributionPoint

    Signature Algorithm: sha256WithRSAEncryption
         2f:32:00:b2:e7:42:86:81:9b:87:c8:7c:fe:ff:99:d9:9c:fe:
         31:a1:92:db:2c:cf:6b:38:bd:d2:c4:0d:2d:fb:1e:35:ef:87:
         9f:30:ab:c0:45:3c:ea:e2:e2:67:b4:f2:90:f7:a3:cb:ed:17:
         38:17:c7:06:8e:b9:50:d0:4e:66:c4:89:cf:cb:3a:d8:ac:a3:
         85:18:ba:e4:75:54:66:f3:4c:3c:99:3f:cd:6d:6e:a0:18:c9:
         25:35:cb:4f:1c:42:a8:14:35:61:37:04:c8:e4:41:2f:4f:6a:
         cf:2a:78:7d:a6:2d:00:03:a7:36:c7:1e:cd:98:cc:b2:db:a8:
         82:25:a8:b2:7c:9c:53:54:48:84:f8:36:17:ac:f9:9e:ba:5e:
         18:18:d7:35:ea:a5:4f:68:30:d2:04:fc:fb:ca:95:c8:0b:86:
         6e:16:68:b7:b6:f5:6a:b1:8e:0e:b3:bf:ef:95:65:2a:ef:5e:
         2c:67:f0:80:e0:c3:dd:95:e3:dc:89:46:00:74:73:33:df:77:
         c9:b5:e1:42:0c:fa:76:a2:19:06:d4:73:e5:9e:43:d2:79:b5:
         10:da:d1:3d:e1:64:08:05:ad:04:b0:bd:3e:69:67:88:0f:93:
         66:c5:ab:9f:f2:87:6a:76:bf:ad:30:96:8a:8d:af:c2:2e:00:
         93:52:8c:4e
-----BEGIN CERTIFICATE-----
MIIFejCCBGKgAwIBAgIQAfCj6dfjkwFc0pHjJma8QzANBgkqhkiG9w0BAQsFADBL
MQswCQYDVQQGEwJFUzERMA8GA1UECgwIRk5NVC1SQ00xDjAMBgNVBAsMBUNlcmVz
MRkwFwYDVQQDDBBBQyBGTk1UIFVzdWFyaW9zMB4XDTE5MDUwODA4MjI1OVoXDTE5
MTEwODA5MjI1OVowWTELMAkGA1UEBhMCRVMxETAPBgNVBAoMCEZOTVQtUkNNMQ4w
DAYDVQQLDAVDZXJlczEnMCUGA1UEAwweU2Vydmlkb3IgT0NTUCBBQyBGTk1UIFVz
dWFyaW9zMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA10nSmLZBYD0o
GwbO+RBTtnv/ASlD/GRYInuQe3kH9UHb5+w+J4hcwNF+jzzIaMaOM7R4PZ1lMOx3
qW9lyslieD421hvry9ozyDWUAgNgU3XfNDdCZced2L+4oxha6hedGOaADm5fJzIE
k2wF0tvuqtyYP6857Kr56zkTxX6bzX7WIYJyIkbV4Z0w8fzCAjsypfiHT+GhijwI
f+HjhBcpKtJ9+IKbiBM40cGo/XHoWdTlb52XqO/607cgTz3hVRlilh6UU4AYQghu
JJzm/W6eCDT5+nUdNNxViS6/VVKczg6Ouy+bkcWRhMsGdI5BVCqzftzuBRrPB41i
j9dDWgyt6wIDAQABo4ICSjCCAkYwCQYDVR0TBAIwADAOBgNVHQ8BAf8EBAMCBsAw
FgYDVR0lAQH/BAwwCgYIKwYBBQUHAwkwHQYDVR0OBBYEFLtvecMEJZjWYsfNcSWv
yWGwEjqLMB8GA1UdIwQYMBaAFLHUT8QjefpEBQnG6znP6DWwuCBkMA8GCSsGAQUF
BzABBQQCBQAwQwYIKwYBBQUHAQEENzA1MDMGCCsGAQUFBzAChidodHRwOi8vd3d3
LmNlcnQuZm5tdC5lcy9jZXJ0cy9BQ1VTVS5jcnQwgcIGA1UdIASBujCBtzCBtAYK
KwYBBAGsZgMKDzCBpTApBggrBgEFBQcCARYdaHR0cDovL3d3dy5jZXJ0LmZubXQu
ZXMvZHBjcy8weAYIKwYBBQUHAgIwbAxqU3VqZXRvIGEgbGFzIGNvbmRpY2lvbmVz
IGRlIHVzbyBleHB1ZXN0YXMgZW4gbGEgRFBDIGRlIGxhIEZOTVQtUkNNIChDL0pv
cmdlIEp1YW4gMTA2LTI4MDA5LU1hZHJpZC1Fc3Bhw7FhKTCBtQYDVR0fBIGtMIGq
MIGnoIGkoIGhhoGebGRhcDovL2xkYXB1c3UuY2VydC5mbm10LmVzL2NuPUNSTDI1
MDMsY249QUMlMjBGTk1UJTIwVXN1YXJpb3Msb3U9Q0VSRVMsbz1GTk1ULVJDTSxj
PUVTP2NlcnRpZmljYXRlUmV2b2NhdGlvbkxpc3Q7YmluYXJ5P2Jhc2U/b2JqZWN0
Y2xhc3M9Y1JMRGlzdHJpYnV0aW9uUG9pbnQwDQYJKoZIhvcNAQELBQADggEBAC8y
ALLnQoaBm4fIfP7/mdmc/jGhktssz2s4vdLEDS37HjXvh58wq8BFPOri4me08pD3
o8vtFzgXxwaOuVDQTmbEic/LOtiso4UYuuR1VGbzTDyZP81tbqAYySU1y08cQqgU
NWE3BMjkQS9Pas8qeH2mLQADpzbHHs2YzLLbqIIlqLJ8nFNUSIT4Nhes+Z66XhgY
1zXqpU9oMNIE/PvKlcgLhm4WaLe29Wqxjg6zv++VZSrvXixn8IDgw92V49yJRgB0
czPfd8m14UIM+naiGQbUc+WeQ9J5tRDa0T3hZAgFrQSwvT5pZ4gPk2bFq5/yh2p2
v60wloqNr8IuAJNSjE4=
-----END CERTIFICATE-----
Certificate:
(...)
Response verify OK
0x0902999F8486CAA55821C9A36BFAA499: good
        This Update: Aug 15 17:08:28 2019 GMT
        Next Update: Aug 15 18:08:28 2019 GMT


The first certificate in the response is the OCSP server signer certificate. You can save it in a .CER file. In this example you can see that the subject is "C=ES, O=FNMT-RCM, OU=Ceres, CN=Servidor OCSP AC FNMT Usuarios"


Another example of validation, but this time you send the whole certificate.
openssl ocsp -issuer CHAMBERS_OF_COMMERCE_ROOT-2016.cer -cert AC_CAMERFIRMA_FOR_NATURAL_PERSONS-2016.cer -text -url http://ocsp.camerfirma.com -CAfile CHAMBERS_OF_COMMERCE_ROOT-2016.cer

viernes, 26 de julio de 2019

CentOS 7 - Increase swap memory


[root@archive ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           1839         124        1570           8         144        1554
Swap:          1227           0        1227

[root@archive ~]# df -h
Filesystem               Size  Used Avail Use% Mounted on
/dev/mapper/centos-root  9.8G  1.6G  8.3G  17% /
devtmpfs                 909M     0  909M   0% /dev
tmpfs                    920M     0  920M   0% /dev/shm
tmpfs                    920M  8.4M  912M   1% /run
tmpfs                    920M     0  920M   0% /sys/fs/cgroup
/dev/sda1               1014M  143M  872M  15% /boot
tmpfs                    184M     0  184M   0% /run/user/0

[root@archive ~]# dd if=/dev/zero of=/root/vembuswap bs=1M count=2048
2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB) copied, 24.9862 s, 85.9 MB/s

[root@archive ~]# mv /root/vembuswap /root/customswap

[root@archive ~]# ls -l /root/customswap
-rw-r--r--. 1 root root 2147483648 Jul 26 12:25 /root/customswap

[root@archive ~]# chmod 600 /root/customswap

[root@archive ~]# mkswap /root/customswap
Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=8b5f50f4-3c03-422a-946d-403afbcb3a22

[root@archive ~]# swapon /root/customswap

[root@archive ~]# vi /etc/fstab
Add the following line:
/root/customswap swap   swap    defaults        0 0
 

[root@archive ~]# swapon -s
Filename                                Type            Size    Used    Priority
/dev/dm-1                               partition       1257468 0       -1
/root/customswap                        file    2097148 0       -2

[root@archive ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           1839         124          76           8        1638        1528
Swap:          3275           0        3275
[root@archive ~]#


sábado, 29 de junio de 2019

OCSP - FNMT Testing

FNMT

Certificate Autority: https://www.sede.fnmt.gob.es/descargas/certificados-raiz-de-la-fnmt

In this case I just need the following CA: Certificados AC Raíz de la FNMT
  • AC Raíz FNMT-RCM
    • AC FNMT Usuarios
    • AC Representación
    • AC Administración Pública
    • AC Componentes Informáticos

OCSP service

There are three OCSP services (not for Componentes Informáticos):

Service Testing



Install openssl:
# yum install libtool perl-core zlib-devel

Params:
  • ocsp
  • issuer. Testing certificate's CA in PEM format
  • seriel. Testing certificate's serial number
  • CAfile: issuer's CA in PEM format (the CA of the CA of the certificate :))
  • url: OSCP url

# openssl ocsp -issuer AC_FNMT_Usuarios.pem -serial 0x1b38186910f9667c5821ca627f360420 -url http://ocspusu.cert.fnmt.es/ocspusu/OcspResponder -CAfile AC_Raiz_FNMT-RCM_SHA256.pem
Response verify OK
0x1b38186910f9667c5821ca627f360420: revoked
        This Update: Jun 29 11:15:50 2019 GMT
        Next Update: Jun 29 12:15:50 2019 GMT
        Reason: cessationOfOperation
        Revocation Time: Nov  8 12:53:48 2016 GMT

# openssl ocsp -issuer AC_Administracion_Publica_SHA256.pem -serial 0x433d6899af0072375829d42560d7e733 -url http://ocspap.cert.fnmt.es/ocspap/OcspResponder  -CAfile AC_Raiz_FNMT-RCM_SHA256.pem
Response verify OK
0x433d6899af0072375829d42560d7e733: good
        This Update: Jun 29 11:21:23 2019 GMT
        Next Update: Jun 29 12:21:23 2019 GMT


Note: Here you can check OCSP service status of Camerfirma: https://www.camerfirma.com/ayuda/servicios/

domingo, 9 de junio de 2019

CentOS 7 - Port forwarding

I have three environments:
  1. Local, i.e, my PC
  2. Server 1, a remote CentOS 7 server
  3. Database Server, a remote Oracle Database server
Server 1 has access to Database Server.
Local has access to Server 1.
Local does not have access to Database Server.

By assuming Oracle Database is opened in port 1521 this is the configuration in Server 1 in order to redirect all requests in port 1521 to Database Server port 1521:
# sudo firewall-cmd --add-forward-port=port=1521:proto=tcp:toport=1521:toaddr=DatabaseServer

# sudo firewall-cmd --add-masquerade

# sudo firewall-cmd --zone=public --add-port=1521/tcp

# sudo firewall-cmd --list-all


domingo, 26 de mayo de 2019

Virtual Box Guest connect to Windows Host

You have a Windows Host running Virtual Box, and a CentOS 7 Guest as virtual machine.
Guest needs to connect to some service in Host. As an example, Host has an Apache web server running in port 80.


First, you have to determine the gateway used by the Guest.

enp0s3 is my "host only" network interface in VirtualBox.
In my case, it's 192.168.56.1. This is the IP the Guest knows as Host so, if you call for port 80, you should get Apache home page.

As you see Guest is not able to connecto to Host. In order to allow that, you need to configure Host firewall, in my case, Windows 10.
You can disable firewall for private networks as follow, but this is not a good solition due security concerns.



The proper solution is to configure a firewall rule for this port in the private network.





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;