Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FISH-5646: Client Certificate Validator API #5398

Merged
merged 2 commits into from
Sep 3, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) [2021] Payara Foundation and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://github.com/payara/Payara/blob/master/LICENSE.txt
* See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* The Payara Foundation designates this particular file as subject to the "Classpath"
* exception as provided by the Payara Foundation in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package fish.payara.security.client;

import javax.security.auth.Subject;
import javax.security.auth.x500.X500Principal;
import java.security.cert.X509Certificate;

/**
* The Client Certificate Validator API that can be used to perform additional checks on the presented
* Client certificate. When specified, this method is executed for each request so make sure the implementation
* considers some kind of caching for checks that take some considerable time.
*/
@FunctionalInterface
public interface ClientCertificateValidator {

/**
* @param subject The Subject object for the authentication request.
* @param principal The Principal object from the user certificate.
* @param certificate The user certificate that was presented in the request.
* @return true when the Client Certificate Validation was successful and request can continue.
* In the case of false, a {@code LoginException} will be thrown.
*/
boolean isValid(Subject subject, X500Principal principal, X509Certificate certificate);
}
7 changes: 6 additions & 1 deletion nucleus/security/core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
only if the new code is made subject to such option by the copyright
holder.

Portions Copyright [2019] [Payara Foundation and/or its affiliates]
Portions Copyright [2019-2021] [Payara Foundation and/or its affiliates]
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
Expand Down Expand Up @@ -207,6 +207,11 @@
<artifactId>glassfish-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>fish.payara.api</groupId>
<artifactId>payara-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <!-- for FindBugs -->
<groupId>fish.payara.server.internal.common</groupId>
<artifactId>simple-glassfish-api</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,34 +37,35 @@
* only if the new code is made subject to such option by the copyright
* holder.
*/
// Portions Copyright [2018-2019] [Payara Foundation and/or its affiliates]
// Portions Copyright [2018-2021] [Payara Foundation and/or its affiliates]
package com.sun.enterprise.security.auth.realm.certificate;

import java.security.Principal;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors;
import com.sun.enterprise.security.BaseRealm;
import com.sun.enterprise.security.SecurityContext;
import com.sun.enterprise.security.auth.login.DistinguishedPrincipalCredential;
import com.sun.enterprise.security.auth.login.common.LoginException;
import com.sun.enterprise.security.auth.realm.BadRealmException;
import com.sun.enterprise.security.auth.realm.NoSuchRealmException;
import com.sun.enterprise.util.Utility;
import fish.payara.security.client.ClientCertificateValidator;
import org.glassfish.security.common.Group;
import org.jvnet.hk2.annotations.Service;

import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.x500.X500Principal;

import org.glassfish.security.common.Group;
import org.jvnet.hk2.annotations.Service;

import com.sun.enterprise.security.BaseRealm;
import com.sun.enterprise.security.SecurityContext;
import com.sun.enterprise.security.auth.login.DistinguishedPrincipalCredential;
import com.sun.enterprise.security.auth.realm.BadRealmException;
import com.sun.enterprise.security.auth.realm.NoSuchRealmException;
import java.lang.ref.WeakReference;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
* Realm wrapper for supporting certificate authentication.
Expand Down Expand Up @@ -103,6 +104,12 @@ public final class CertificateRealm extends BaseRealm {
/** Descriptive string of the authentication type of this realm. */
public static final String AUTH_TYPE = "certificate";

private final Map<ClassLoader,
// ServiceLoader keeps a reference to ClassLoader, so it has
// to be explicitly weak as well
WeakReference<ServiceLoader<ClientCertificateValidator>>> clientCertificateValidatorMap
= Collections.synchronizedMap(new WeakHashMap<>());

@Override
protected void init(Properties props) throws BadRealmException, NoSuchRealmException {
super.init(props);
Expand Down Expand Up @@ -149,6 +156,8 @@ public Enumeration<String> getGroupNames(String username) {
* @return principal's name
*/
public String authenticate(Subject subject, X500Principal principal) {
validateSubjectViaAPI(subject, principal);

_logger.finest(() -> String.format("authenticate(subject=%s, principal=%s)", subject, principal));

final LdapName dn = getLdapName(principal);
Expand All @@ -175,6 +184,68 @@ public String authenticate(Subject subject, X500Principal principal) {
return principalName;
}

private void validateSubjectViaAPI(Subject subject, X500Principal principal) {
X509Certificate certificate = getCertificateFromSubject(subject, principal);
if (certificate == null) {
_logger.warning(() -> String.format("No X509Certificate found(subject=%s, principal=%s)", subject, principal));
return;
}

// Ask all the Client Certificate Validator.
List<ClientCertificateValidator> validators = Collections.emptyList();
try {
validators = loadValidatorClasses();
} catch (Throwable exc) {
_logger.log(Level.WARNING, "Exception while loading certificate validation class", exc);
clientCertificateValidatorMap.remove(Utility.getClassLoader());
}

boolean failed = false;
if (!validators.isEmpty()) {
for (ClientCertificateValidator validator : validators) {
if (!validator.isValid(subject, principal, certificate)) {
failed = true;
Copy link
Contributor

@svendiedrichsen svendiedrichsen Sep 1, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop could stop when first validation fails depending on how expensive validations are.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thx. There should only be 1 or max 2 validators but added the a break statement.

}
}
}
if (failed) {
throw new LoginException("Certificate Validation Failed via API");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add some information about which validation failed. Classname?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added logging statement on line 207 as this message could potentially be returned to clients which is not wanted (don't expose internal info around security to clients in case of failure)

}
}

private List<ClientCertificateValidator> loadValidatorClasses() {
AtomicReference<ServiceLoader<ClientCertificateValidator>> serviceLoader = new AtomicReference<>();
clientCertificateValidatorMap.compute(Utility.getClassLoader(), (cl, weak) -> {
serviceLoader.set(weak != null ? weak.get() : null);
if (serviceLoader.get() == null) {
serviceLoader.set(ServiceLoader.load(ClientCertificateValidator.class));
return new WeakReference<>(serviceLoader.get());
} else {
return weak;
}
});
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(serviceLoader.get().iterator(),
Spliterator.ORDERED), false).collect(Collectors.toList());
}

private X509Certificate getCertificateFromSubject(Subject subject, X500Principal principal) {
X509Certificate result = null;
Set<Object> publicCredentials = subject.getPublicCredentials();
for (Object publicCredential : publicCredentials) {
if (publicCredential instanceof List) {
List<Object> data = (List<Object>) publicCredential;
for (Object item : data) {
if (item instanceof X509Certificate) {
X509Certificate certificate = (X509Certificate) item;
if (principal.equals(certificate.getIssuerX500Principal())) {
result = (X509Certificate) item;
}
}
}
}
}
return result;
}

private LdapName getLdapName(final X500Principal principal) {
try {
Expand Down