include::../shared-doc/attributes.adoc[]

= helloworld-mutual-ssl-secured: Securing a Web Application with Mutual (two-way) SSL Configuration and Role-based Access Control
:author: Giriraj Sharma, Stefan Guilhen
:level: Intermediate
:technologies: Mutual SSL, Security, Undertow

[abstract]
The `helloworld-mutual-ssl-secured` quickstart demonstrates securing a Web application using client mutual SSL authentication and role-based access control

:standalone-server-type: default
:archiveType: war
:includes-cli-scripts:
:restoreScriptName: restore-configuration.cli
:app-user-groups: JBossAdmin

== What is it?

This example demonstrates the configuration of _mutual SSL authentication_ in {productNameFull} {productVersion} to secure a war application.

Mutual SSL provides the same security as SSL, with the addition of authentication and non-repudiation of the client authentication, using digital signatures. When mutual authentication is used, the server would request the client to provide a certificate in addition to the server certificate issued to the client. Mutual authentication requires an extra round trip time for client certificate exchange. In addition, the client must buy and maintain a digital certificate. We can secure our war application deployed over {productName} with mutual(two-way) client certificate authentication and provide access permissions or privileges to legitimate users.

This quickstart shows how to configure {productName} to enable TLS/SSL configuration for the new {productName} `undertow` subsystem and enable mutual (two-way) SSL authentication for clients in order to secure a WAR application with restricted access.

// System Requirements
include::../shared-doc/system-requirements.adoc[leveloffset=+1]
// Use of {jbossHomeName}
include::../shared-doc/use-of-jboss-home-name.adoc[leveloffset=+1]
//  Add the Authorized Application User
include::../shared-doc/add-application-user.adoc[leveloffset=+1]

IMPORTANT: For the purpose of this quickstart the password can contain any valid value because the `ApplicationRealm` will be used for authorization only, for example, to obtain the security roles.

[[set_up_client_and_server_keystores_using_java_keytool]]
== Set Up Client and Server Keystores Using Java Keytool

. Open a terminal and navigate to the {productName} server `configuration` directory:
+
[source,subs="+quotes,attributes+",options="nowrap"]
----
$ cd __{jbossHomeName}__/standalone/configuration/
----

. Create a certificate for your server using the following command.
+
[source,options="nowrap"]
----
$>keytool -genkey -keyalg RSA -keystore server.keystore -storepass secret -keypass secret -validity 365

What is your first and last name?
   [Unknown]:  localhost
What is the name of your organizational unit?
   [Unknown]:  wildfly
What is the name of your organization?
   [Unknown]:  jboss
What is the name of your City or Locality?
   [Unknown]:  Raleigh
What is the name of your State or Province?
   [Unknown]:  Carolina
What is the two-letter country code for this unit?
   [Unknown]:  US
Is CN=localhost, OU=wildfly, O=jboss, L=Raleigh, ST=Carolina, C=US correct?
   [no]:  yes
----

. Create the client certificate, which is used to authenticate against the server when accessing a resource through SSL.
+
[source,options="nowrap"]
----
$>keytool -genkey -keystore client.keystore -storepass secret -validity 365 -keyalg RSA -keysize 2048 -storetype pkcs12

What is your first and last name?
    [Unknown]:  quickstartUser
What is the name of your organizational unit?
    [Unknown]:  Sales
What is the name of your organization?
    [Unknown]:  My Company
What is the name of your City or Locality?
    [Unknown]:  Sao Paulo
What is the name of your State or Province?
    [Unknown]:  Sao Paulo
What is the two-letter country code for this unit?
    [Unknown]:  BR
Is CN=quickstartUser, OU=Sales, O=My Company, L=Sao Paulo, ST=Sao Paulo, C=BR correct?
    [no]:  yes
----

+
Notice that it sets the `first and last name` to `quickstartUser` and that this matches the user that was added to the `ApplicationRealm`. When authorizing access to a resource, the CN (common name) of the client's certificate is extracted by a principal decoder and this name is then used by the `ApplicationRealm` to obtain the client's roles.

. Export the client certificate and create a truststore by importing this certificate.
+
[source,options="nowrap"]
----
$>keytool -exportcert -keystore client.keystore  -storetype pkcs12 -storepass secret -keypass secret -file client.crt
$>keytool -import -file client.crt -alias quickstartUser -keystore client.truststore -storepass secret

Owner: CN=quickstartUser, OU=Sales, O=My Company, L=Sao Paulo, ST=Sao Paulo, C=BR
Issuer: CN=quickstartUser, OU=Sales, O=My Company, L=Sao Paulo, ST=Sao Paulo, C=BR
Serial number: 7fd95ce4
Valid from: Mon Jul 24 16:14:03 BRT 2017 until: Tue Jul 24 16:14:03 BRT 2018
Certificate fingerprints:
     MD5:  87:41:C5:CC:E6:79:91:F0:9D:90:AD:9E:DD:57:81:80
     SHA1: 55:35:CA:B0:DC:DD:4F:E6:B8:9F:45:4B:4B:98:93:B5:3B:7C:55:84
     SHA256: 0A:FC:93:B6:25:5A:74:42:B8:A1:C6:5F:69:88:72:7F:27:A9:81:B0:17:0C:F1:AF:3D:DE:B7:E5:F1:69:66:4B
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 95 84 BE C6 32 BB 2B 13   4C 7F 5D D4 C4 C8 22 12  ....2.+.L.]...".
0010: CB 09 39 09                                        ..9.
]
]

Trust this certificate? [no]:  yes
Certificate was added to keystore
----
+
It is worth noticing that the client certificate was imported under the `quickstartUser` alias. When authenticating a client in a `CLIENT_CERT` configuration, the CN (common name) of the client's certificate is extracted by a principal decoder and this name is then used by the `KeyStoreRealm` to match an alias in the trust store. If a trusted certificate is found under this alas, the client is considered authenticated.

. Export client certificate to pkcs12 format.
+
[source,options="nowrap"]
----
$>keytool -importkeystore -srckeystore client.keystore -srcstorepass secret -destkeystore clientCert.p12 -srcstoretype PKCS12 -deststoretype PKCS12 -deststorepass secret
----

. The certificates and keystores are now properly configured.

// Back Up the {productName} Standalone Server Configuration
include::../shared-doc/back-up-server-standalone-configuration.adoc[leveloffset=+1]
// Start the {productName} Standalone Server
include::../shared-doc/start-the-standalone-server.adoc[leveloffset=+1]

[[configure_the_server]]
== Configure the Server

You configure the SSL context and required security domain by running JBoss CLI commands. For your convenience, this quickstart batches the commands into a `configure-ssl.cli` script provided in the root directory of this quickstart.

. Before you begin, make sure you do the following:

* xref:back_up_standalone_server_configuration[Back up the {productName} standalone server configuration] as described above.
* xref:start_the_eap_standalone_server[Start the {productName} server with the standalone default profile] as described above.

. Review the `configure-ssl.cli` file in the root of this quickstart directory. Comments in the script describe the purpose of each block of commands.
. Open a new terminal, navigate to the root directory of this quickstart, and run the following command, replacing __{jbossHomeName}__ with the path to your server:
+
[source,subs="+quotes,attributes+",options="nowrap"]
----
$ __{jbossHomeName}__/bin/jboss-cli.sh --connect --file=configure-ssl.cli
----
+
NOTE: For Windows, use the `__{jbossHomeName}__\bin\jboss-cli.bat` script.

+
You should see the following result when you run the script.
+
[source,options="nowrap"]
----
The batch executed successfully
process-state: reload-required
----

. Stop the {productName} server.

== Review the Modified Server Configuration

After stopping the server, open the `__{jbossHomeName}__/standalone/configuration/standalone.xml` file and review the changes.

. The following `key-store`s were added to the `elytron` subsystem:
+
[source,xml,options="nowrap"]
----
<key-store name="qsKeyStore">
    <credential-reference clear-text="secret"/>
    <implementation type="JKS"/>
    <file path="server.keystore" relative-to="jboss.server.config.dir"/>
</key-store>
<key-store name="qsTrustStore">
    <credential-reference clear-text="secret"/>
    <implementation type="JKS"/>
    <file path="client.truststore" relative-to="jboss.server.config.dir"/>
</key-store>
----

. The following `key-manager` was added to the `elytron` subsystem:
+
[source,xml,options="nowrap"]
----
<key-managers>
    <key-manager name="qsKeyManager" key-store="qsKeyStore">
        <credential-reference clear-text="secret"/>
    </key-manager>
</key-managers>
----

. The following `trust-manager` was added to the `elytron` subsystem:
+
[source,xml,options="nowrap"]
----
<trust-managers>
    <trust-manager name="qsTrustManager" key-store="qsTrustStore"/>
</trust-managers>
----

. The following `ssl-context` was added to the `elytron` subsystem:
+
[source,xml,options="nowrap"]
----
<server-ssl-contexts>
    <server-ssl-context name="qsSSLContext" protocols="TLSv1.2" need-client-auth="true" key-manager="qsKeyManager" trust-manager="qsTrustManager"/>
</server-ssl-contexts>
----

. The following realms were added to the `elytron` subsystem:
+
[source,xml,options="nowrap"]
----
<key-store-realm name="KeyStoreRealm" key-store="qsTrustStore"/>

<aggregate-realm name="QuickstartRealm" authentication-realm="KeyStoreRealm" authorization-realm="ApplicationRealm"/>
----
+
The `aggregate-realm` defines different security realms for authentication and authorization. In this case, the `KeyStoreRealm` is responsible for authenticating the principal extracted from the client's certificate and the `ApplicationRealm` is responsible for obtaining the roles required to access the application.

. The following `principal-decoder` and `security-domain` were added to the `elytron` subsystem:
+
[source,xml,options="nowrap"]
----
<x500-attribute-principal-decoder name="QuickstartDecoder" attribute-name="cn"/>

<security-domain name="QuickstartDomain" default-realm="QuickstartRealm" permission-mapper="default-permission-mapper" principal-decoder="QuickstartDecoder">
    <realm name="QuickstartRealm" role-decoder="groups-to-roles"/>
</security-domain>
----
+
The `x500-attribute-principal-decoder` creates a new `Principal` from the CN attribute of the `X500Principal` obtained from the client's certificate. This new principal is supplied to the security realms and is also the principal returned in methods like `getUserPrincipal` and `getCallerPrincipal`.

. The following `http-authentication-factory` was added to the `elytron` subsystem:
+
[source,xml,options="nowrap"]
----
<http-authentication-factory name="quickstart-http-authentication" http-server-mechanism-factory="global" security-domain="QuickstartDomain">
    <mechanism-configuration>
        <mechanism mechanism-name="CLIENT_CERT"/>
    </mechanism-configuration>
</http-authentication-factory>
----
+
It defines the security domain that will handle requests using the `CLIENT_CERT` HTTP mechanism.

. The `https-listener` in the `undertow` subsystem was changed to reference the `qsSSLContext` `ssl-context`:
+
[source,xml,options="nowrap"]
----
<https-listener name="https" socket-binding="https" ssl-context="qsSSLContext" enable-http2="true"/>
----

. The following `application-security-domain` was added to the `undertow` subsystem:
+
[source,xml,options="nowrap"]
----
<application-security-domains>
    <application-security-domain name="client_cert_domain" http-authentication-factory="quickstart-http-authentication"/>
</application-security-domains>
----
+
It maps the `client_cert_domain` from the quickstart application to the `http-authentication-factory` shown above, so requests made to the application go through the configured HTTP authentication factory.

[[test_the_server_ssl_configuration]]
== Test the Server SSL Configuration

To test the SSL configuration, access: https://localhost:8443

If it is configured correctly, you should be asked to trust the server certificate.

[[import_the_client_certificate_into_your_browser]]
== Import the Certificate into Your Browser

Before you access the application, you must import the _clientCert.p12_, which holds the client certificate, into your browser.

[[import_the_client_certificate_into_google_chrome]]
=== Import the Certificate into Google Chrome

. Click the Chrome menu icon (3 dots) in the upper right on the browser toolbar and choose *Settings*. This takes you to chrome://settings/.
. Scroll to the bottom of the page and click on the *Advanced* link to reveal the advanced settings.
. Search for the *Manage Certificates* line under *Privacy and security* and then click on it.
. In the *Manage certificates* screen, select the *Your Certificates* tab and click on the *Import* button.
. Select the *clientCert.p12* file. You will be prompted to enter the password: `secret`.
. The client certificate is now installed in the Google Chrome browser.

[[import_the_client_certificate_into_mozilla_firefox]]
=== Import the Certificate into Mozilla Firefox

. Click the *Edit* menu item on the browser menu and choose *Preferences*.
. A new window will open. Select the *Advanced* icon and after that the *Certificates* tab.
. On the *Certificates* tab, mark the option *Ask me every time* and click the *View Certificates* button.
. A new window will open. Select the *Your Certificates* tab and click the *Import* button.
. Select the *clientCert.p12* file. You will be prompted to enter the password: `secret`.
. The certificate is now installed in the Mozilla Firefox browser.

// Build and Deploy the Quickstart
include::../shared-doc/build-and-deploy-the-quickstart.adoc[leveloffset=+1]

// Additional deployment information
If mutual SSL is configured properly and the WAR application is secured, you will be able to access the application only if the DN of client certificate, for example `clientCert.p12`, is same as the one defined in `app-roles.properties` file. Otherwise, it will result in an HTTP error status code of `403 Access Denied/Forbidden`.

== Access the Application

The application will be running at the following URL: https://localhost:8443/{artifactId}

A page displaying the caller principal and the client certificate used for mutual SSL should be visible:

[source,options="nowrap"]
----
Hello World ! Mutual SSL client authentication is successful and your war app is secured.!!

Caller Principal: quickstartUser

Client Certificate Pem: MIIDhTCCAm2gAwIBAgIEf9lc5DANBgkqhkiG9w0BAQsFADBzMQswCQYDVQQGEwJCUjESMBAGA1UECBMJU2FvIFBhdW
xvMRIwEAYDVQQHEwlTYW8gUGF1bG8xEzARBgNVBAoTCk15IENvbXBhbnkxDjAMBgNVBAsTBVNhbGVzMRcwFQYDVQQDEw5xdWlja3N0YXJ0VXNlcjAe
Fw0xNzA3MjQxOTE0MDNaFw0xODA3MjQxOTE0MDNaMHMxCzAJBgNVBAYTAkJSMRIwEAYDVQQIEwlTYW8gUGF1bG8xEjAQBgNVBAcTCVNhbyBQYXVsbz
ETMBEGA1UEChMKTXkgQ29tcGFueTEOMAwGA1UECxMFU2FsZXMxFzAVBgNVBAMTDnF1aWNrc3RhcnRVc2VyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEAnHwflE8K/ArTPbTeZZEFK+1jtpg9grPSD62GIz/awoIDr6Rf9vCBTpAg4lom62A0BNZDEJKdab/ExNOOBRY+/pOnYlXZTYlDpdQQap
0E7UP5EfHNZsafgpfILCop2LdTuUbcV7tLKBsthJLJ0ZCoG5QJFble+OPxEbissOvIqHfvUJZi34k9ULteLJc330g0uTuDrLgtoFQ0cbHa4FCQ86o8
5EuRPpFeW6EBA3iYE/tKHSYsK7QSajefX6jZjXoZiUflw97SAGL43ZtvNbrKRywEfsVqDpDurjBg2HI+YahuDz5R1QWTSyTHWMZzcyJYqxjXiSf0oK
1cUahn6m5t1wIDAQABoyEwHzAdBgNVHQ4EFgQUlYS+xjK7KxNMf13UxMgiEssJOQkwDQYJKoZIhvcNAQELBQADggEBADkp+R6kSNXJNfihqbDRp3uF
tNMG6OgaYsfC7RtNLMdrhvoLlU7uWzxVCFuifvNlWVRiADBHDCRQU2uNRFW35GQSfHQyok4KoBuKlfBtQ+Xu7c8R0JzxN/rPJPXoCbShzDHo1uoz5/
dzXZz0EjjWCPJk+LVEhEvH0GcWAp3x3irpNU4hRZLd0XomY0Z4NnUt7VMBNYDOxVxgT9qcLnEaEpIfYULubLLCFHwAga2YgsKzZYLuwMaEWK4zhPVF
ynfnMaOxI67FC2QzhfzERyKqHj47WuwN0xWbS/1gBypS2nUwvItyxaEQG2X5uQY8j8QoY9wcMzIIkP2Mk14gJGHUnA8=
----

// Undeploy the Quickstart
include::../shared-doc/undeploy-the-quickstart.adoc[leveloffset=+1]


// Restore the {productName} Standalone Server Configuration
include::../shared-doc/restore-standalone-server-configuration.adoc[leveloffset=+1]

// Additional information about this script
This script reverts the changes made to the `undertow` and `elytron` subsystems. You should see the following result when you run the script:

[source,options="nowrap"]
----
The batch executed successfully
process-state: reload-required
----

// Restore the {productName} Standalone Server Configuration Manually
include::../shared-doc/restore-standalone-server-configuration-manual.adoc[leveloffset=+2]

== Remove the keystores and certificates created for this quickstart

. Open a terminal and navigate to the {productName} server `configuration` directory:
+
[source,subs="+quotes,attributes+",options="nowrap"]
----
$ __{jbossHomeName}__/bin/standalone.sh
----
+
NOTE: For Windows, use the `__{jbossHomeName}__\bin\standalone.bat` script.

. Remove the `clientCert.p12`, `client.crt`, `client.keystore`, `client.truststore` and `server.keystore` files that were generated for this quickstart.

[[remove_the_client_certificate_from_your_browser]]
== Remove the Client Certificate from Your Browser

After you are done with this quickstart, remember to remove the certificate that was imported into your browser.

=== Remove the Client Certificate from Google Chrome

. Click the Chrome menu icon (3 dots) in the upper right on the browser toolbar and choose *Settings*. This takes you to chrome://settings/.
. Scroll to the bottom of the page and click on the *Advanced* link to reveal the advanced settings.
. Search for the *Manage Certificates* line under *Privacy and security* and then click on it.
. In the *Manage certificates* screen, select the *Your Certificates* tab and then click on the arrow to the right of the certificate to be removed.
. The certificate is expanded, displaying the `quickstartUser` entry. Click on the icon (3 dots) to the right of it and then select *Delete*.
. Confirm the deletion in the dialog box. The certificate has now been removed from the Google Chrome browser.

=== Remove the Client Certificate from Mozilla Firefox

. Click the *Edit* menu item on the browser menu and choose *Preferences*.
. A new window will open. Select the *Advanced* icon and after that the *Certificates* tab.
. On the *Certificates* tab click the *View Certificates* button.
. A new window will open. Select the *Your Certificates* tab.
. Select the *quickstartUser* certificate and click the *Delete* button.
. The certificate has now been removed from the Mozilla Firefox browser.

// Run the Quickstart in Red Hat Developer Studio or Eclipse
include::../shared-doc/run-the-quickstart-in-jboss-developer-studio.adoc[leveloffset=+1]

// Additional Red Hat Developer Studio instructions
* Make sure you configure the keystores and client certificates as described under xref:set_up_client_and_server_keystores_using_java_keytool[Set Up Client and Server Keystores Using Java Keytool].
* Depending on the browser you choose, make sure you either xref:import_the_client_certificate_into_google_chrome[import the certificate into Google Chrome] or xref:import_the_client_certificate_into_mozilla_firefox[import the certificate into Mozilla Firefox].
* Make sure you configure the server by running the JBoss CLI commands as described above under xref:configure_the_server[Configure the Server]. Stop the server at the end of that step.
* In {JBDSProductName}, choose *Window* –> *Web Browser*, then select the browser you chose to import the certificate.
* To deploy the application, right-click on the *{artifactId}* project and choose *Run As* –> *Run on Server*.
* Make sure you xref:restore_the_server_configuration[restore the {productName} server configuration] when you have completed testing this quickstart.

// Debug the Application
include::../shared-doc/debug-the-application.adoc[leveloffset=+1]
