├── src
└── main
│ ├── resources
│ └── META-INF
│ │ ├── services
│ │ └── org.keycloak.authentication.AuthenticatorFactory
│ │ └── jboss-deployment-structure.xml
│ └── java
│ └── org
│ └── keycloak
│ └── authentication
│ └── authenticators
│ └── x509
│ ├── CnsX509ClientCertificateAuthenticatorFactory.java
│ └── CnsX509ClientCertificateAuthenticator.java
├── .gitignore
├── .github
└── workflows
│ └── maven.yml
├── README.md
├── pom.xml
└── LICENSE
/src/main/resources/META-INF/services/org.keycloak.authentication.AuthenticatorFactory:
--------------------------------------------------------------------------------
1 | org.keycloak.authentication.authenticators.x509.CnsX509ClientCertificateAuthenticatorFactory
--------------------------------------------------------------------------------
/src/main/resources/META-INF/jboss-deployment-structure.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled source #
2 | ###################
3 | *.com
4 | *.class
5 | *.dll
6 | *.exe
7 | *.o
8 | *.so
9 |
10 | # Build tool #
11 | ##############
12 | target
13 | .idea
14 | *.iml
15 | *.im
16 | *.ipr
17 | *.iws
18 | .settings
19 | .project
20 | .classpath
21 |
22 | # OS generated files #
23 | ######################
24 | *~
25 | .DS_Store
26 | .DS_Store?
27 | ._*
28 | .Spotlight-V100
29 | .Trashes
30 | Icon?
31 | ehthumbs.db
32 | Thumbs.db
33 |
34 | activemq-data
35 | *.epoch
36 | *.log
37 |
38 | # Extra #
39 | #########
40 |
--------------------------------------------------------------------------------
/.github/workflows/maven.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a Java project with Maven
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
3 |
4 | name: Build
5 |
6 | on:
7 | push:
8 | branches: [ main ]
9 | tags: '*'
10 | pull_request:
11 | branches: [ main ]
12 |
13 | jobs:
14 | build:
15 | name: Build
16 | runs-on: ubuntu-latest
17 |
18 | steps:
19 | - uses: actions/checkout@v2
20 |
21 | - name: Set up JDK 1.8
22 | uses: actions/setup-java@v1
23 | with:
24 | java-version: 1.8
25 |
26 | - name: Cache Maven packages
27 | uses: actions/cache@v2
28 | with:
29 | path: ~/.m2
30 | key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
31 | restore-keys: ${{ runner.os }}-m2
32 |
33 | - name: Build with Maven
34 | run: mvn --batch-mode --update-snapshots package
35 |
36 | - uses: actions/upload-artifact@v2
37 | with:
38 | name: cns-authenticator.jar
39 | path: target/cns-authenticator.jar
40 |
41 | - name: Release
42 | uses: softprops/action-gh-release@v1
43 | if: startsWith(github.ref, 'refs/tags/')
44 | with:
45 | files: target/cieid-provider.jar
46 | env:
47 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
48 |
--------------------------------------------------------------------------------
/src/main/java/org/keycloak/authentication/authenticators/x509/CnsX509ClientCertificateAuthenticatorFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Analytical Graphics, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | *
17 | */
18 |
19 | package org.keycloak.authentication.authenticators.x509;
20 |
21 | import org.keycloak.authentication.Authenticator;
22 | import org.keycloak.models.AuthenticationExecutionModel;
23 | import org.keycloak.models.KeycloakSession;
24 |
25 | public class CnsX509ClientCertificateAuthenticatorFactory extends X509ClientCertificateAuthenticatorFactory {
26 |
27 | public static final String PROVIDER_ID = "cns-auth-x509-client-username-form";
28 | public static final CnsX509ClientCertificateAuthenticator SINGLETON =
29 | new CnsX509ClientCertificateAuthenticator();
30 |
31 |
32 | @Override
33 | public String getHelpText() {
34 | return "Validates username and password from X509 client certificate (Italian CNS) received as a part of mutual SSL handshake.";
35 | }
36 |
37 | @Override
38 | public String getDisplayType() {
39 | return "CNS X509/Validate Username Form";
40 | }
41 |
42 | @Override
43 | public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
44 | return REQUIREMENT_CHOICES;
45 | }
46 |
47 |
48 | @Override
49 | public Authenticator create(KeycloakSession session) {
50 | return SINGLETON;
51 | }
52 |
53 | @Override
54 | public String getId() {
55 | return PROVIDER_ID;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://github.com/lscorcia/keycloak-cns-authenticator/actions?query=workflow%3ABuild)
2 | [](https://img.shields.io/github/v/release/lscorcia/keycloak-cns-authenticator?sort=semver)
3 | [](https://img.shields.io/github/downloads/lscorcia/keycloak-cns-authenticator/total)
4 | [](https://github.com/lscorcia/keycloak-cns-authenticator/issues)
5 |
6 | # keycloak-cns-authenticator
7 | Keycloak (https://www.keycloak.org/) custom authenticator for the Italian Carta Nazionale dei Servizi (CNS)
8 |
9 | ## Project details
10 | The Italian CNS is an X.509 based authentication mechanism that uses digital certificates on Smart Cards/USB
11 | Tokens to provide trusted authentication to Public Administrations. There is a bunch of accredited institutions
12 | (https://eidas.agid.gov.it/TL/TSL-IT.xml) that can issue cards and they are widespread because every company
13 | in Italy must have at least one.
14 |
15 | Keycloak natively supports X.509 authentication, however its use is really limited because it only allows
16 | the "corporate" use of certificates by requiring that all certificates are associated to existing users
17 | beforehand. This is obviously not the case for the Italian CNS.
18 |
19 | This project aims to create a new Authenticator that automatically creates users when a new certificate
20 | is presented to Keycloak.
21 |
22 | ## Status
23 | This project is under development, so for the moment I won't publish any release and you will have to build it yourself.
24 | It works and allows the creation of users from the data contained in the client certificate. The attribute
25 | mapping is hardcoded - if you want to change it, please see file `CnsX509ClientCertificateAuthenticator.java`.
26 |
27 | Until the project gets to a stable release, it will be targeting the most recent release of Keycloak as
28 | published on the website (see property `version.keycloak` in file pom.xml). Currently the main branch is
29 | targeting Keycloak 16.1.1. **Do not use this provider with previous versions of Keycloak, it won't work!**
30 |
31 | I am also wondering if it should become a fully-fledged Identity Provider instead of an authenticator,
32 | but this will take quite some time to study and implement.
33 |
34 | ## Build requirements
35 | * git
36 | * JDK8+
37 | * Maven
38 |
39 | ## Build
40 | Just run `mvn clean package` for a full rebuild. The output package will
41 | be generated under `target/cns-authenticator.jar`.
42 |
43 | ## Deployment
44 | This provider should be deployed as a module, i.e. copied under
45 | `{$KEYCLOAK_PATH}/standalone/deployments/`, with the right permissions.
46 | Keycloak will take care of loading the module, no restart needed.
47 |
48 | Use this command for reference:
49 | ```
50 | mvn clean package && \
51 | sudo install -C -o keycloak -g keycloak target/cns-authenticator.jar /opt/keycloak/standalone/deployments/
52 | ```
53 |
54 | If successful you will find a new Execution Flow type called `CNS X509/Validate Username Form` in the
55 | `Add Execution` drop down list in the Authentication configuration screen.
56 |
57 | ## Open issues and limitations
58 | Feel free to open issues on GitHub if you spot something not working correctly!
59 |
60 | ## Related projects
61 | If you are interested in Keycloak plugins for the various Italian national auth
62 | systems, you may be interested also in:
63 |
64 | * Keycloak SPID Provider - https://github.com/italia/spid-keycloak-provider/
65 | A Keycloak provider for the SPID federation
66 |
67 | * Keycloak CIE ID Provider - https://github.com/lscorcia/keycloak-cieid-provider/
68 | A Keycloak provider for the CIE ID federation
69 |
70 | * Keycloak CNS Authenticator - https://github.com/lscorcia/keycloak-cns-authenticator/
71 | A Keycloak authenticator to login using CNS tokens and smart cards
72 |
73 | ## License
74 | This project is released under the Apache License 2.0, same as the main Keycloak
75 | package.
76 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 | 4.0.0
9 | com.github.lscorcia
10 | keycloak-cns-authenticator
11 | 0.0.1-SNAPSHOT
12 | jar
13 |
14 | Keycloak CNS Authenticator
15 | A Keycloak Custom Authenticator for the Italian CNS System
16 | https://github.com/lscorcia/keycloak-cns-authenticator
17 |
18 |
19 | 1.8
20 | 1.8
21 | false
22 | UTF-8
23 |
24 | 16.1.1
25 | 1.7.30
26 | 4.13.2
27 | 1.68
28 |
29 |
30 |
31 | scm:git:https://github.com/lscorcia/keycloak-cns-authenticator.git
32 | HEAD
33 |
34 |
35 |
36 |
37 | org.bouncycastle
38 | bcprov-jdk15on
39 | ${bouncycastle.version}
40 |
41 |
42 | org.bouncycastle
43 | bcpkix-jdk15on
44 | ${bouncycastle.version}
45 |
46 |
47 | org.keycloak
48 | keycloak-core
49 | ${version.keycloak}
50 | provided
51 |
52 |
53 | org.keycloak
54 | keycloak-adapter-core
55 | ${version.keycloak}
56 | provided
57 |
58 |
59 | org.keycloak
60 | keycloak-server-spi
61 | ${version.keycloak}
62 | provided
63 |
64 |
65 | org.keycloak
66 | keycloak-server-spi-private
67 | ${version.keycloak}
68 | provided
69 |
70 |
71 | org.keycloak
72 | keycloak-services
73 | ${version.keycloak}
74 | provided
75 |
76 |
77 | org.slf4j
78 | slf4j-api
79 | ${slf4j-api.version}
80 |
81 |
82 |
83 | junit
84 | junit
85 | ${junit.version}
86 | test
87 |
88 |
89 |
90 |
91 |
92 | cns-authenticator
93 |
94 |
95 |
96 | org.apache.maven.plugins
97 | maven-release-plugin
98 | 3.0.0-M1
99 |
100 | true
101 | @{project.version}
102 | release
103 |
104 |
105 |
106 |
107 |
108 |
109 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/src/main/java/org/keycloak/authentication/authenticators/x509/CnsX509ClientCertificateAuthenticator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Analytical Graphics, Inc. and/or its affiliates
3 | * and other contributors as indicated by the @author tags.
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | *
17 | */
18 |
19 | package org.keycloak.authentication.authenticators.x509;
20 |
21 | import java.security.cert.CertificateEncodingException;
22 | import java.security.cert.X509Certificate;
23 | import java.util.Enumeration;
24 | import java.util.LinkedList;
25 | import java.util.List;
26 | import java.util.function.Function;
27 | import java.util.regex.Matcher;
28 | import java.util.regex.Pattern;
29 | import javax.ws.rs.core.MultivaluedHashMap;
30 |
31 | import javax.ws.rs.core.MultivaluedMap;
32 | import javax.ws.rs.core.Response;
33 |
34 | import org.bouncycastle.asn1.x500.X500Name;
35 | import org.bouncycastle.asn1.x500.style.BCStyle;
36 | import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
37 | import org.keycloak.authentication.AuthenticationFlowContext;
38 | import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;
39 | import org.keycloak.common.util.PemUtils;
40 | import org.keycloak.events.Details;
41 | import org.keycloak.events.Errors;
42 | import org.keycloak.forms.login.LoginFormsProvider;
43 | import org.keycloak.models.ModelDuplicateException;
44 | import org.keycloak.models.RealmModel;
45 | import org.keycloak.models.UserModel;
46 | import org.keycloak.models.utils.FormMessage;
47 |
48 | import static org.keycloak.authentication.authenticators.util.AuthenticatorUtils.getDisabledByBruteForceEventError;
49 |
50 | public class CnsX509ClientCertificateAuthenticator extends X509ClientCertificateAuthenticator {
51 |
52 | @Override
53 | public void close() {
54 | super.close();
55 | }
56 |
57 | @Override
58 | public void authenticate(AuthenticationFlowContext context) {
59 | try {
60 |
61 | dumpContainerAttributes(context);
62 |
63 | X509Certificate[] certs = getCertificateChain(context);
64 | if (certs == null || certs.length == 0) {
65 | // No x509 client cert, fall through and
66 | // continue processing the rest of the authentication flow
67 | logger.debug("[X509ClientCertificateAuthenticator:authenticate] x509 client certificate is not available for mutual SSL.");
68 | context.attempted();
69 | return;
70 | }
71 |
72 | saveX509CertificateAuditDataToAuthSession(context, certs[0]);
73 | recordX509CertificateAuditDataViaContextEvent(context);
74 |
75 | X509AuthenticatorConfigModel config = null;
76 | if (context.getAuthenticatorConfig() != null && context.getAuthenticatorConfig().getConfig() != null) {
77 | config = new X509AuthenticatorConfigModel(context.getAuthenticatorConfig());
78 | }
79 | if (config == null) {
80 | logger.warn("[X509ClientCertificateAuthenticator:authenticate] x509 Client Certificate Authentication configuration is not available.");
81 | context.challenge(createInfoResponse(context, "X509 client authentication has not been configured yet"));
82 | context.attempted();
83 | return;
84 | }
85 |
86 | // Validate X509 client certificate
87 | try {
88 | CertificateValidator.CertificateValidatorBuilder builder = certificateValidationParameters(context.getSession(), config);
89 | CertificateValidator validator = builder.build(certs);
90 | validator.checkRevocationStatus()
91 | .validateTrust()
92 | .validateKeyUsage()
93 | .validateExtendedKeyUsage()
94 | .validatePolicy()
95 | .validateTimestamps();
96 | } catch(Exception e) {
97 | logger.error(e.getMessage(), e);
98 | // TODO use specific locale to load error messages
99 | String errorMessage = "Certificate validation failed.";
100 | // TODO is calling form().setErrors enough to show errors on login screen?
101 | context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(),
102 | errorMessage, e.getMessage()));
103 | context.attempted();
104 | return;
105 | }
106 |
107 | Object userIdentity = getUserIdentityExtractor(config).extractUserIdentity(certs);
108 | if (userIdentity == null) {
109 | context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
110 | logger.warnf("[X509ClientCertificateAuthenticator:authenticate] Unable to extract user identity from certificate.");
111 | // TODO use specific locale to load error messages
112 | String errorMessage = "Unable to extract user identity from specified certificate";
113 | // TODO is calling form().setErrors enough to show errors on login screen?
114 | context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage));
115 | context.attempted();
116 | return;
117 | }
118 |
119 | UserModel user;
120 | try {
121 | context.getEvent().detail(Details.USERNAME, userIdentity.toString());
122 | context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, userIdentity.toString());
123 | user = getUserIdentityToModelMapper(config).find(context, userIdentity);
124 | }
125 | catch(ModelDuplicateException e) {
126 | logger.modelDuplicateException(e);
127 | String errorMessage = "X509 certificate authentication's failed.";
128 | // TODO is calling form().setErrors enough to show errors on login screen?
129 | context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(),
130 | errorMessage, e.getMessage()));
131 | context.attempted();
132 | return;
133 | }
134 |
135 | if (invalidUser(context, user)) {
136 | try
137 | {
138 | // Try to create the user
139 | logger.infof("[CnsX509ClientCertificateAuthenticator:authenticate] Existing user not found - now trying to create a new one...");
140 | user = importUserToKeycloak(context, certs, userIdentity.toString());
141 | }
142 | catch (Exception e)
143 | {
144 | logger.warn("[CnsX509ClientCertificateAuthenticator:authenticate] Error creating user identity.", e);
145 |
146 | // TODO use specific locale to load error messages
147 | String errorMessage = "X509 certificate authentication's failed.";
148 | // TODO is calling form().setErrors enough to show errors on login screen?
149 | context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(),
150 | errorMessage, "Invalid user"));
151 | context.attempted();
152 | return;
153 | }
154 | }
155 |
156 | String bruteForceError = getDisabledByBruteForceEventError(context.getProtector(), context.getSession(), context.getRealm(), user);
157 | if (bruteForceError != null) {
158 | context.getEvent().user(user);
159 | context.getEvent().error(bruteForceError);
160 | // TODO use specific locale to load error messages
161 | String errorMessage = "X509 certificate authentication's failed.";
162 | // TODO is calling form().setErrors enough to show errors on login screen?
163 | context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(),
164 | errorMessage, "Invalid user"));
165 | context.attempted();
166 | return;
167 | }
168 |
169 | if (!userEnabled(context, user)) {
170 | // TODO use specific locale to load error messages
171 | String errorMessage = "X509 certificate authentication's failed.";
172 | // TODO is calling form().setErrors enough to show errors on login screen?
173 | context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(),
174 | errorMessage, "User is disabled"));
175 | context.attempted();
176 | return;
177 | }
178 | context.setUser(user);
179 |
180 | // Check whether to display the identity confirmation
181 | if (!config.getConfirmationPageDisallowed()) {
182 | // FIXME calling forceChallenge was the only way to display
183 | // a form to let users either choose the user identity from certificate
184 | // or to ignore it and proceed to a normal login screen. Attempting
185 | // to call the method "challenge" results in a wrong/unexpected behavior.
186 | // The question is whether calling "forceChallenge" here is ok from
187 | // the design viewpoint?
188 | context.forceChallenge(createSuccessResponse(context, certs[0].getSubjectDN().getName()));
189 | // Do not set the flow status yet, we want to display a form to let users
190 | // choose whether to accept the identity from certificate or to specify username/password explicitly
191 | }
192 | else {
193 | // Bypass the confirmation page and log the user in
194 | context.success();
195 | }
196 | }
197 | catch(Exception e) {
198 | logger.errorf("[X509ClientCertificateAuthenticator:authenticate] Exception: %s", e.getMessage());
199 | context.attempted();
200 | }
201 | }
202 |
203 | protected UserModel importUserToKeycloak(AuthenticationFlowContext context, X509Certificate[] certs, String userIdentity)
204 | {
205 | Function subject = _certs -> {
206 | try {
207 | return new JcaX509CertificateHolder(_certs[0]).getSubject();
208 | } catch (CertificateEncodingException e) {
209 | logger.warn("Unable to get certificate Subject", e);
210 | }
211 | return null;
212 | };
213 |
214 | logger.debug("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - Extracting subject.cn...");
215 | UserIdentityExtractor cnExtractor = UserIdentityExtractor.getX500NameExtractor(BCStyle.CN, subject);
216 | Object subjectCn = cnExtractor.extractUserIdentity(certs);
217 | String subjectCnStr = subjectCn != null ? subjectCn.toString(): null;
218 | logger.debugf("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - subject.cn='%s'", subjectCnStr);
219 |
220 | logger.debug("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - Extracting subject.surname...");
221 | UserIdentityExtractor surnameExtractor = UserIdentityExtractor.getX500NameExtractor(BCStyle.SURNAME, subject);
222 | Object subjectLastName = surnameExtractor.extractUserIdentity(certs);
223 | String subjectLastNameStr = subjectLastName != null ? subjectLastName.toString(): null;
224 | logger.debugf("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - subject.surname='%s'", subjectLastNameStr);
225 |
226 | logger.debug("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - Extracting subject.givenname...");
227 | UserIdentityExtractor givenNameExtractor = UserIdentityExtractor.getX500NameExtractor(BCStyle.GIVENNAME, subject);
228 | Object subjectFirstName = givenNameExtractor.extractUserIdentity(certs);
229 | String subjectFirstNameStr = subjectFirstName != null ? subjectFirstName.toString(): null;
230 | logger.debugf("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - subject.givenname='%s'", subjectFirstNameStr);
231 |
232 | logger.debug("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - Extracting subject.email...");
233 | UserIdentityExtractor emailExtractor1 = UserIdentityExtractor.getX500NameExtractor(BCStyle.EmailAddress, subject);
234 | Object subjectEmail1 = emailExtractor1.extractUserIdentity(certs);
235 | String subjectEmail1Str = subjectEmail1 != null ? subjectEmail1.toString(): null;
236 |
237 | UserIdentityExtractor emailExtractor2 = UserIdentityExtractor.getX500NameExtractor(BCStyle.E, subject);
238 | Object subjectEmail2 = emailExtractor2.extractUserIdentity(certs);
239 | String subjectEmail2Str = subjectEmail2 != null ? subjectEmail2.toString(): null;
240 |
241 | String subjectEmailStr = subjectEmail1Str == null ? subjectEmail2Str: subjectEmail1Str;
242 | logger.debugf("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - subject.email='%s'", subjectEmailStr);
243 |
244 | logger.debug("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - Extracting fiscal number from cn...");
245 | String subjectFiscalNumberStr = extractFiscalNumber(subjectCnStr);
246 | logger.debugf("CnsX509ClientCertificateAuthenticator::importUserToKeycloak - fiscalNumber='%s'", subjectFiscalNumberStr);
247 |
248 | String pemCertificate = PemUtils.encodeCertificate(certs[0]);
249 |
250 | return createNewKeycloakUser(context, userIdentity, subjectEmailStr, subjectFirstNameStr, subjectLastNameStr, subjectFiscalNumberStr, pemCertificate);
251 | }
252 |
253 | protected UserModel createNewKeycloakUser(AuthenticationFlowContext context, String username, String email, String firstname, String lastname,
254 | String fiscalNumber, String pemCertificate) {
255 | logger.infof("Creating new user: %s, email: %s, first name: %s, last name: %s, fiscalNumber: %s to local Keycloak storage", username, email, firstname, lastname, fiscalNumber);
256 |
257 | RealmModel realm = context.getRealm();
258 | UserModel user = context.getSession().userLocalStorage().addUser(realm, username);
259 | user.setEnabled(true);
260 | user.setEmail(email);
261 | if (email != null && email.length() > 0)
262 | user.setEmailVerified(true);
263 |
264 | user.setFirstName(firstname);
265 | user.setLastName(lastname);
266 | user.setSingleAttribute("fiscalNumber", fiscalNumber);
267 | //user.setSingleAttribute(DEFAULT_ATTRIBUTE_NAME, userIdentity);
268 |
269 | return user;
270 | }
271 |
272 | protected String extractFiscalNumber(String subjectCn)
273 | {
274 | String _pattern = "^([-A-Z0-9]+)\\/";
275 | Pattern r = Pattern.compile(_pattern, Pattern.CASE_INSENSITIVE);
276 | Matcher m = r.matcher(subjectCn);
277 |
278 | if (!m.find()) {
279 | logger.debugf("[extractFiscalNumber] No matches were found for input \"%s\", pattern=\"%s\"", subjectCn, _pattern);
280 | return null;
281 | }
282 |
283 | if (m.groupCount() != 1) {
284 | logger.debugf("[extractFiscalNumber] Match produced more than a single group for input \"%s\", pattern=\"%s\"", subjectCn, _pattern);
285 | return null;
286 | }
287 |
288 | return m.group(1);
289 | }
290 |
291 | private Response createErrorResponse(AuthenticationFlowContext context,
292 | String subjectDN,
293 | String errorMessage,
294 | String ... errorParameters) {
295 |
296 | return createResponse(context, subjectDN, false, errorMessage, errorParameters);
297 | }
298 |
299 | private Response createSuccessResponse(AuthenticationFlowContext context,
300 | String subjectDN) {
301 | return createResponse(context, subjectDN, true, null, null);
302 | }
303 |
304 | private Response createResponse(AuthenticationFlowContext context,
305 | String subjectDN,
306 | boolean isUserEnabled,
307 | String errorMessage,
308 | Object[] errorParameters) {
309 |
310 | LoginFormsProvider form = context.form();
311 | if (errorMessage != null && errorMessage.trim().length() > 0) {
312 | List errors = new LinkedList<>();
313 |
314 | errors.add(new FormMessage(errorMessage));
315 | if (errorParameters != null) {
316 |
317 | for (Object errorParameter : errorParameters) {
318 | if (errorParameter == null) continue;
319 | for (String part : errorParameter.toString().split("\n")) {
320 | errors.add(new FormMessage(part));
321 | }
322 | }
323 | }
324 | form.setErrors(errors);
325 | }
326 |
327 | MultivaluedMap formData = new MultivaluedHashMap<>();
328 | formData.add("username", context.getUser() != null ? context.getUser().getUsername() : "unknown user");
329 | formData.add("subjectDN", subjectDN);
330 | formData.add("isUserEnabled", String.valueOf(isUserEnabled));
331 |
332 | form.setFormData(formData);
333 |
334 | return form.createX509ConfirmPage();
335 | }
336 |
337 | private void dumpContainerAttributes(AuthenticationFlowContext context) {
338 |
339 | Enumeration attributeNames = context.getHttpRequest().getAttributeNames();
340 | while(attributeNames.hasMoreElements()) {
341 | String a = attributeNames.nextElement();
342 | logger.tracef("[X509ClientCertificateAuthenticator:dumpContainerAttributes] \"%s\"", a);
343 | }
344 | }
345 |
346 | private boolean userEnabled(AuthenticationFlowContext context, UserModel user) {
347 | if (!user.isEnabled()) {
348 | context.getEvent().user(user);
349 | context.getEvent().error(Errors.USER_DISABLED);
350 | return false;
351 | }
352 | return true;
353 | }
354 |
355 | private boolean invalidUser(AuthenticationFlowContext context, UserModel user) {
356 | if (user == null) {
357 | context.getEvent().error(Errors.USER_NOT_FOUND);
358 | return true;
359 | }
360 | return false;
361 | }
362 |
363 | @Override
364 | public void action(AuthenticationFlowContext context) {
365 | super.action(context);
366 | }
367 | }
368 |
--------------------------------------------------------------------------------