Java

java

Securely Storing Database Password on JBoss EAP 8

Typically, we store database passwords in plain text on JBoss EAP 8. However, this approach is not considered a best practice due to security concerns. Therefore, it is important to encrypt the password thru several ways of password encryption method. And on this article we’ll try to do encryption using the JBoss EAP’s credential-store.

First we need to create a credential store to be stored in JBoss EAP, with the name of “my_custom_store” and “longpassword” as its password which is located in the JBoss data directory.


$ jboss-cli.sh
You are disconnected at the moment. Type 'connect' to connect to the server or 'help' for the list of supported commands.

[disconnected /] connect

[standalone@localhost:9990 /] /subsystem=elytron/credential-store=my_custom_store:add(path="my_custom_store.jceks", relative-to=jboss.server.data.dir, credential-reference={clear-text=longpassword}, create=true)
{"outcome" => "success"}

Next is storing my database password there,

[standalone@localhost:9990 /]  /subsystem=elytron/credential-store=my_custom_store:add-alias(alias=db_password, secret-value=mysecuredatabasepassword)

And validate it,

[standalone@localhost:9990 /] /subsystem=elytron/credential-store=my_custom_store:read-aliases()
{
    "outcome" => "success",
    "result" => ["db_password"]
}

Next is injecting the value of our secure password from credential store into our database connection. This is happen in our standalone.xml file,

<datasource jndi-name="java:/my-db" pool-name="my-db">
	<connection-url>jdbc:mysql://localhost:3306/test_db</connection-url>
	<driver-class>com.mysql.cj.jdbc.Driver</driver-class>
	<driver>mysql</driver>
	<security>
		<user-name>root</user-name>
		<credential-reference store="my_custom_store" alias="db_password"/>
	</security>
</datasource>

A successful database connection can be tested thru JBoss EAP web console,

Maven Error PKIX When Connecting to Self Signed Nexus Repository

Had this error while doing a maven build

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

With a complete error log,

$ mvn clean package -s settings.xml

.......

[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[ERROR] Unresolveable build extension: Plugin com.redhat.quarkus.platform:quarkus-maven-plugin:3.15.3.SP1-redhat-00002 or one of its dependencies could not be resolved: Failed to collect dependencies at com.redhat.quarkus.platform:quarkus-maven-plugin:jar:3.15.3.SP1-redhat-00002 -> io.quarkus:quarkus-bootstrap-maven-resolver:jar:3.15.3.redhat-00004 -> io.smallrye.beanbag:smallrye-beanbag-maven:jar:1.5.2.redhat-00001 -> io.smallrye.beanbag:smallrye-beanbag-sisu:jar:1.5.2.redhat-00001 -> javax.inject:javax.inject:jar:1.0.0.redhat-00014 @
[ERROR] Non-resolvable import POM: The following artifacts could not be resolved: com.redhat.quarkus.platform:quarkus-camel-bom:pom:3.15.3.SP1-redhat-00002 (present, but unavailable): Could not transfer artifact com.redhat.quarkus.platform:quarkus-camel-bom:pom:3.15.3.SP1-redhat-00002 from/to mvn-repository (https://nexus/maven-group/): PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target @ line 32, column 25
[ERROR] 'dependencies.dependency.version' for org.apache.camel.quarkus:camel-quarkus-direct:jar is missing. @ line 45, column 21
[ERROR] 'dependencies.dependency.version' for org.apache.camel.quarkus:camel-quarkus-jackson:jar is missing. @ line 49, column 21
[ERROR] 'dependencies.dependency.version' for org.apache.camel.quarkus:camel-quarkus-rest-openapi:jar is missing. @ line 53, column 21
[ERROR] 'dependencies.dependency.version' for org.apache.camel.quarkus:camel-quarkus-rest:jar is missing. @ line 57, column 21
 @
[ERROR] The build could not read 1 project -> [Help 1]

Workaround is quite simple,

$ mvn -Dmaven.wagon.http.ssl.insecure=true clean package -s settings.xml

Script to Generate Series of Thread Dump

There are times when we want to see which threads are blocking our requests, and generating a thread dump is one way to find it out. The thing is sometimes we need to create a series of thread dumps, that’s why i have this script to do it for me. Create a file with the name of “jstack.sh”, with below script as its content

# number of cycles.
LOOP=3
# seconds between cycles.
INTERVAL=10

for ((i=1; i <= $LOOP; i++))
do
   _now=$(date)
   echo "\n \n ${_now}" >> cpu.out
   top -l 1 -o cpu -pid $1 >> cpu.out
   echo "\n \n ${_now}" >> tdump.out
   jstack -l $1 >> tdump.out
   echo "thread dump #" $i
   if [ $i -lt $LOOP ]; then
      echo "Sleeping..."
      sleep $INTERVAL
   fi
done

Repository for above script can be found below,

https://github.com/edwin/java-thread-dump

Debugging HTTP Request and Responses in Red Hat Single Sign On

Red Hat Single Sign On (RHSSO) or its opensource project, which is Keycloak, is an open-source software product to allow single sign-on with identity and access management which can be deployed as a cloud service or containerized application. For this sample, we are trying to debug and print all http requests and responses that comes to RHSSO 7.4.6 which is being deployed on Openshift, for debugging purpose. But we also need to be very careful since it will print all http content which might contains sensitive values.

Okay, so lets start with creating a file “sso.cli” which have below content,

/subsystem=undertow/configuration=filter/expression-filter=requestDumperExpression:add(expression="dump-request")
/subsystem=undertow/server=default-server/host=default-host/filter-ref=requestDumperExpression:add

And deploy it as a ConfigMap,

$ oc create configmap jboss-cli --from-file=sso-extensions.cli=sso.cli

Next is mount it as a volume to RHSSO DeploymentConfig

$ oc set volume dc/sso --add --name=jboss-cli \
		-m /opt/eap/extensions -t configmap --configmap-name=jboss-cli \ 
		--default-mode='0755' --overwrite

Rollout the corresponding DeploymentConfig and we can observe that http request-response logs now is showing, we can use this curl command to test

$ curl --location --request POST 'https://sso.url/auth/realms/realm/protocol/openid-connect/userinfo' \
--header 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiw......YXNzPlSVE2Oj0ImIQd6zQkw2UEMiEyJz8FrsVaS7x2M8mQjy-xQrSTGZVXKWR7KLHa-MCRx4S33Ja5nQuD3K_VVihKTyn4cOHnQ'

with below logs as the result

21:46:28,071 INFO  [io.undertow.request.dump] (default task-1) 
----------------------------REQUEST---------------------------
               URI=/auth/realms/realm/protocol/openid-connect/userinfo
 characterEncoding=null
     contentLength=0
       contentType=null
            header=accept=*/*
            header=accept-encoding=gzip, deflate, br
            header=forwarded=for=10.161.5.3;host=sso.url;proto=https
            header=authorization=Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiw......YXNzPlSVE2Oj0ImIQd6zQkw2UEMiEyJz8FrsVaS7x2M8mQjy-xQrSTGZVXKWR7KLHa-MCRx4S33Ja5nQuD3K_VVihKTyn4cOHnQ
            header=x-forwarded-proto=https
            header=x-forwarded-port=443
            header=x-forwarded-for=10.161.5.3
            header=content-length=0
            header=host=sso.url
            header=x-forwarded-host=sso.url
            locale=[]
            method=POST
          protocol=HTTP/1.1
       queryString=
        remoteAddr=/10.161.5.3:0
        remoteHost=10.161.5.3
            scheme=https
              host=sso.url
        serverPort=8443
          isSecure=true
--------------------------RESPONSE--------------------------
     contentLength=73
       contentType=application/json
            header=X-XSS-Protection=1; mode=block
            header=X-Frame-Options=SAMEORIGIN
            header=Referrer-Policy=no-referrer
            header=Date=Wed, 06 Nov 2024 14:46:28 GMT
            header=Connection=keep-alive
            header=WWW-Authenticate=Bearer realm="realm", error="invalid_token", error_description="Token verification failed"
            header=Strict-Transport-Security=max-age=31536000; includeSubDomains
            header=X-Content-Type-Options=nosniff
            header=Content-Type=application/json
            header=Content-Length=73
            status=401

==============================================================

Error “No marshaller registered for object of Java type” in Infinispan

Had this error whenc trying to put a Java bean to Infinispan 15,

java.lang.IllegalArgumentException: No marshaller registered for object of Java type com.edw.model.User : com.edw.model.User@1a8d9c94
	at org.infinispan.protostream.impl.SerializationContextImpl.getMarshallerDelegate(SerializationContextImpl.java:517) ~[protostream-5.0.4.Final.jar:5.0.4.Final]
	at org.infinispan.protostream.WrappedMessage.writeCustomObject(WrappedMessage.java:300) ~[protostream-5.0.4.Final.jar:5.0.4.Final]
	at org.infinispan.protostream.WrappedMessage.writeMessage(WrappedMessage.java:250) ~[protostream-5.0.4.Final.jar:5.0.4.Final]
	at org.infinispan.protostream.WrappedMessage.write(WrappedMessage.java:243) ~[protostream-5.0.4.Final.jar:5.0.4.Final]
	at org.infinispan.protostream.ProtobufUtil.toWrappedByteBuffer(ProtobufUtil.java:152) ~[protostream-5.0.4.Final.jar:5.0.4.Final]
	at org.infinispan.commons.marshall.ImmutableProtoStreamMarshaller.objectToBuffer(ImmutableProtoStreamMarshaller.java:55) ~[infinispan-commons-15.0.7.Final.jar:15.0.7.Final]
	at org.infinispan.commons.marshall.AbstractMarshaller.objectToByteBuffer(AbstractMarshaller.java:70) ~[infinispan-commons-15.0.7.Final.jar:15.0.7.Final]
	at org.infinispan.client.hotrod.marshall.MarshallerUtil.obj2bytes(MarshallerUtil.java:117) ~[infinispan-client-hotrod-15.0.7.Final.jar:15.0.7.Final]
	at org.infinispan.client.hotrod.DataFormat$DataFormatImpl.valueToBytes(DataFormat.java:92) ~[infinispan-client-hotrod-15.0.7.Final.jar:15.0.7.Final]
	at org.infinispan.client.hotrod.DataFormat.valueToBytes(DataFormat.java:211) ~[infinispan-client-hotrod-15.0.7.Final.jar:15.0.7.Final]
	at org.infinispan.client.hotrod.impl.RemoteCacheImpl.valueToBytes(RemoteCacheImpl.java:628) ~[infinispan-client-hotrod-15.0.7.Final.jar:15.0.7.Final]
	at org.infinispan.client.hotrod.impl.RemoteCacheImpl.putAsync(RemoteCacheImpl.java:315) ~[infinispan-client-hotrod-15.0.7.Final.jar:15.0.7.Final]
	at org.infinispan.client.hotrod.impl.RemoteCacheSupport.put(RemoteCacheSupport.java:196) ~[infinispan-client-hotrod-15.0.7.Final.jar:15.0.7.Final]
	at org.infinispan.client.hotrod.impl.RemoteCacheSupport.put(RemoteCacheSupport.java:186) ~[infinispan-client-hotrod-15.0.7.Final.jar:15.0.7.Final]

Actually it happen because of my Java bean (com.edw.model.User) doesnt have any marshaller. This is how my configuration files looks like,

@Configuration
public class InfinispanConfiguration {
    @Bean
    public RemoteCacheManager remoteCacheManager() {
        return new RemoteCacheManager(
                new org.infinispan.client.hotrod.configuration.ConfigurationBuilder()
                        .addServers("localhost:11222")
                        .security().authentication().username("admin2").password("password")
                        .clientIntelligence(ClientIntelligence.HASH_DISTRIBUTION_AWARE)
                        .marshaller(ProtoStreamMarshaller.class)
                        .build());
    }
}

And everything works well after i register a marshaller for User bean

@Configuration
public class InfinispanConfiguration {
    @Bean
    public RemoteCacheManager remoteCacheManager() {
        return new RemoteCacheManager(
                new org.infinispan.client.hotrod.configuration.ConfigurationBuilder()
                        .addServers("localhost:11222")
                        .security().authentication().username("admin2").password("password")
                        .clientIntelligence(ClientIntelligence.HASH_DISTRIBUTION_AWARE)
                        .marshaller(ProtoStreamMarshaller.class)
                        .addContextInitializer(new UserIndexSchemaInitializerImpl())
                        .build());
    }
}

Where UserIndexSchemaInitializerImpl is a generated code coming from interface that extending SerializationContextInitializer class.

Full code for this can be found on my Github repository,

https://github.com/edwin/spring-boot-2-and-infinispan-15