/***********************************************************
Copyright (C) 2025 VeriSign, Inc.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

http://www.verisign.com/nds/naming/namestore/techdocs.html
***********************************************************/
package com.verisign.epp.transport;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.X509TrustManager;
import javax.security.auth.x500.X500Principal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Custom {@link X509TrustManager} for EPP that supports configuring the policy
 * for the client and server certificate EKU settings with the
 * {@link #setClientEKUs(List)} and {@link EPPTrustManager#setServerEKUs(List)},
 * respectively. Once initialized, the {@code EPPTrustManager} is thread-safe,
 * so it can be embedded into a Singleton.
 */
public class EPPTrustManager implements X509TrustManager {

	/**
	 * Used for logging
	 */
	private static Logger logger = LoggerFactory.getLogger(EPPTrustManager.class);

	/**
	 * List of trusted X.509 Extended Key Usage (EKU) values, where at least one
	 * of the values must exist in the client certificate. A {@code null} value
	 * means that the EKU values in the client certificate will be ignored.
	 */
	private List<String> clientEKUs = null;

	/**
	 * List of trusted X.509 Extended Key Usage (EKU) values, where at least one
	 * of the values must exist in the server certificate. A {@code null} value
	 * means that the EKU values in the server certificate will be ignored.
	 */
	private List<String> serverEKUs = null;

	/**
	 * Set of trusted X509Certificates.
	 */
	private Set<X509Certificate> trustedCerts = Collections.emptySet();

	/**
	 * Array of trusted X509Certificates created from trustedCerts
	 */
	private X509Certificate[] trustedCertsArray = null;

	/**
	 * Set of trust anchors
	 */
	private Set<TrustAnchor> trustAnchors = Collections.emptySet();

	/**
	 * PKIX settings template that is setup with the trust anchors, but is made
	 * available with the {@link #getPkixParamsTemplate()} and not directly used
	 * by the {@code EPPTrustManager}.Ï
	 */
	private PKIXBuilderParameters pkixParamsTemplate;

	/**
	 * Map of trusted principals with their list of public keys
	 */
	private Map<X500Principal, List<PublicKey>> trustedSubjects;

	/**
	 * Default constructor. Ensure to call one of the {@code init} methods.
	 */
	public EPPTrustManager() {
	}

	/**
	 * Creates the {@code EPPTrustManager} instance with a specific Trust Store.
	 * Passing a {@code null} Trust Store will load the default Trust Store for
	 * the JDK (${JAVA_HOME}/lib/security/cacerts).
	 *
	 * @param aKeyStore
	 *           Trust store to initialize the {@code EPPTrustManager} with. Set
	 *           to {@code null} to use the default JDK trust store
	 *           (${JAVA_HOME}/lib/security/cacerts).
	 * @throws Exception
	 *            Error initializing the {@code EPPTrustManager}
	 */
	public EPPTrustManager(KeyStore aKeyStore) throws Exception {
		this.init(aKeyStore);
	}

	/**
	 * Creates the {@code EPPTrustManager} instance with a specific
	 * {@link Collection} of trusted certificates.
	 *
	 * @param aTrustedCertificates
	 *           {@code Collection} of trusted certificates
	 *
	 * @throws EPPException
	 *            Error initializing the {@code EPPTrustManager}
	 */
	public EPPTrustManager(Set<X509Certificate> aTrustedCertificates) throws Exception {
		this.init(aTrustedCertificates);
	}

	/**
	 * Creates the {@code EPPTrustManager} instance with a specific Trust Store.
	 * Passing a {@code null} Trust Store will load the default Trust Store for
	 * the JDK (${JAVA_HOME}/lib/security/cacerts).
	 *
	 * @param aKeyStore
	 *           Trust store to initialize the {@code EPPTrustManager} with. Set
	 *           to {@code null} to use the default JDK trust store
	 *           (${JAVA_HOME}/lib/security/cacerts).
	 * @param aClientEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension for the client
	 *           certificate
	 * @param aServerEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension for the server
	 *           certificate
	 * @throws Exception
	 *            Error initializing the {@code EPPTrustManager}
	 */
	public EPPTrustManager(KeyStore aKeyStore, List<String> aClientEKUs, List<String> aServerEKUs) throws Exception {
		this.init(aKeyStore, aClientEKUs, aServerEKUs);
	}

	/**
	 * Creates the {@code EPPTrustManager} instance with a specific
	 * {@link Collection} of trusted certificates.
	 *
	 * @param aTrustedCertificates
	 *           {@code Collection} of trusted certificates
	 * @param aClientEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension for the client
	 *           certificate
	 * @param aServerEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension for the server
	 *           certificate
	 *
	 * @throws Exception
	 *            Error initializing the {@code EPPTrustManager}
	 */
	public EPPTrustManager(Set<X509Certificate> aTrustedCertificates, List<String> aClientEKUs, List<String> aServerEKUs)
	      throws Exception {
		this.init(aTrustedCertificates, aClientEKUs, aServerEKUs);
	}

	/**
	 * Initialize the {@code EPPTrustManager} instance with a specific Trust
	 * Store. Passing a {@code null} Trust Store will load the default Trust
	 * Store for the JDK (${JAVA_HOME}/lib/security/cacerts).
	 *
	 * @param aKeyStore
	 *           Trust store to initialize the {@code EPPTrustManager} with. Set
	 *           to {@code null} to use the default JDK trust store
	 *           (${JAVA_HOME}/lib/security/cacerts).
	 * @throws Exception
	 *            Error initializing the {@code EPPTrustManager}
	 */
	public void init(KeyStore aKeyStore) throws Exception {
		logger.debug("init(KeyStore): enter");

		KeyStore theTrustStore;

		try {

			if (aKeyStore == null) {
				logger.debug("init(KeyStore): Load default trust store (cacerts)");

				String theCacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
				FileInputStream theCacertsStream = new FileInputStream(theCacertsPath);
				theTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
				theTrustStore.load(theCacertsStream, null);
			}
			else {
				logger.debug("init(KeyStore): Load custom trust store");
				theTrustStore = aKeyStore;
			}

			//
			logger.debug("init(KeyStore): Loading " + theTrustStore.size() + " certificates");
			Enumeration<String> theAliases = aKeyStore.aliases();
			HashSet<X509Certificate> theTrustedCerts = new HashSet<>();
			while (theAliases.hasMoreElements()) {
				X509Certificate theCert = (X509Certificate) theTrustStore.getCertificate(theAliases.nextElement());
				if (theCert != null) {
					logger.debug("init(KeyStore): Loading certificate: " + theCert.getSubjectX500Principal().getName());
					theTrustedCerts.add(theCert);
				}
			}
			this.init(theTrustedCerts);

		}
		catch (Exception ex) {
			logger.error("init(KeyStore): Exception while initializing: " + ex);
			throw new Exception("Exception while initializing EPPTrustManager", ex);
		}

		logger.debug("init(KeyStore): exit");
	}

	/**
	 * Initialize the {@code EPPTrustManager} instance with a specific Trust
	 * Store. Passing a {@code null} Trust Store will load the default Trust
	 * Store for the JDK (${JAVA_HOME}/lib/security/cacerts).
	 *
	 * @param aKeyStore
	 *           Trust store to initialize the {@code EPPTrustManager} with. Set
	 *           to {@code null} to use the default JDK trust store
	 *           (${JAVA_HOME}/lib/security/cacerts).
	 * @param aClientEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension for the client
	 *           certificate
	 * @param aServerEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension for the server
	 *           certificate
	 * @throws Exception
	 *            Error initializing the {@code EPPTrustManager}
	 */
	public void init(KeyStore aKeyStore, List<String> aClientEKUs, List<String> aServerEKUs) throws Exception {
		logger.debug("init(KeyStore, List<String>, List<String>): enter");
		this.init(aKeyStore);
		this.clientEKUs = aClientEKUs;
		this.serverEKUs = aServerEKUs;
		logger.debug("init(KeyStore, List<String>, List<String>): exit");
	}

	/**
	 * Initialize the {@code EPPTrustManager} instance with a specific
	 * {@link Collection} of trusted certificates.
	 *
	 * @param aTrustedCertificates
	 *           {@code Collection} of trusted certificates
	 *
	 * @throws Exception
	 *            Error initializing the {@code EPPTrustManager}
	 */
	public void init(Set<X509Certificate> aTrustedCertificates) throws Exception {
		logger.debug("init(Set<X509Certificate>): enter");

		if (aTrustedCertificates == null) {
			logger.error("init(Collection<X509Certificate>): aTrustedCertificates is null");
			return;
		}

		Set<TrustAnchor> theTrustAnchors = new HashSet<>();
		Map<X500Principal, List<PublicKey>> theSubjectMap = new HashMap<>();

		for (X509Certificate theCert : aTrustedCertificates) {
			theTrustAnchors.add(new TrustAnchor(theCert, null));

			X500Principal theDn = theCert.getSubjectX500Principal();
			List<PublicKey> theKeys;
			if (theSubjectMap.containsKey(theDn)) {
				theKeys = theSubjectMap.get(theDn);
			}
			else {
				theKeys = new ArrayList<>();
				theSubjectMap.put(theDn, theKeys);
			}
			theKeys.add(theCert.getPublicKey());
		}

		try {
			this.pkixParamsTemplate = new PKIXBuilderParameters(theTrustAnchors, null);

			// TODO - Can make configurable
			this.pkixParamsTemplate.setRevocationEnabled(false);
		}
		catch (Exception ex) {
			logger.error("init(Set<X509Certificate>): Exception while initializing: " + ex);
			throw new Exception("Exception while initializing EPPTrustManager", ex);
		}

		this.trustedCerts = aTrustedCertificates;
		this.trustAnchors = theTrustAnchors;
		this.trustedSubjects = theSubjectMap;
		this.trustedCertsArray = new X509Certificate[this.trustedCerts.size()];
		this.trustedCerts.toArray(this.trustedCertsArray);

		logger.debug("init(Set<X509Certificate>): exit");
	}

	/**
	 * Initialize the {@code EPPTrustManager} instance with a specific
	 * {@link Collection} of trusted certificates.
	 *
	 * @param aTrustedCertificates
	 *           {@code Collection} of trusted certificates
	 * @param aClientEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension for the client
	 *           certificate
	 * @param aServerEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension for the server
	 *           certificate
	 *
	 * @throws Exception
	 *            Error initializing the {@code EPPTrustManager}
	 */
	public void init(Set<X509Certificate> aTrustedCertificates, List<String> aClientEKUs, List<String> aServerEKUs)
	      throws Exception {
		logger.debug("init(Set<X509Certificate>, List<String>, List<String>): enter");
		this.init(aTrustedCertificates);
		this.clientEKUs = aClientEKUs;
		this.serverEKUs = aServerEKUs;
		logger.debug("init(Set<X509Certificate>, List<String>, List<String>): exit");
	}

	/**
	 * Given the partial or complete certificate chain provided by the peer,
	 * build a certificate path to a trusted root and return if it can be
	 * validated and is trusted for client SSL authentication based on the
	 * authentication type. The authentication type is determined by the actual
	 * certificate used. For instance, if RSAPublicKey is used, the authType
	 * should be "RSA". Checking is case-sensitive. <br/>
	 * This implementation will only perform PKIX validation and will not
	 * validation the Extended Key Usage (EKU) settings.
	 *
	 * @param aChain
	 *           the peer certificate chain
	 * @param aAuthType
	 *           the authentication type based on the client certificate
	 *
	 * @exception CertificateException
	 *               if the certificate chain is not trusted by this
	 *               TrustManager.
	 */
	@Override
	public void checkClientTrusted(X509Certificate[] aChain, String aAuthType) throws CertificateException {
		logger.debug("checkClientTrusted(X509Certificate[], String): enter");

		if (aChain == null) {
			logger.info("checkClientTrusted(X509Certificate[], String): null certificate chain");
			throw new CertificateException("null certificate chain");
		}

		if (logger.isDebugEnabled()) {
			for (X509Certificate theCert : aChain) {
				logger.debug("checkClientTrusted(X509Certificate[], String): cert = "
				      + theCert.getSubjectX500Principal().getName());
			}
		}

		// Check the EKU settings of the client certificate?
		if (this.clientEKUs != null) {

			// Check the EKU settings of the leaf certificate
			X509Certificate theClientCert = aChain[0];
			List<String> theEkuValues = theClientCert.getExtendedKeyUsage();

			if (logger.isDebugEnabled() && theEkuValues != null) {
				for (String theEku : theEkuValues) {
					logger.debug("checkClientTrusted(X509Certificate[], String): EKU = " + theEku);
				}
			}

			boolean theEKUFound = false;
			for (String clientEKU : this.clientEKUs) {
				if (theEkuValues.contains(clientEKU)) {
					theEKUFound = true;
					break;
				}
			}

			if (!theEKUFound) {
				logger.info(
				      "checkClientTrusted(X509Certificate[], String): Client certificate does not have one of the trusted EKU settings");
				throw new CertificateException("Client certificate does not have one of the trusted EKU settings");
			}
		}
		else {
			logger.debug("checkClientTrusted(X509Certificate[], String): EKU setting ignored");
		}

		logger.debug("checkClientTrusted(X509Certificate[], String): exit");
	}

	/**
	 * Given the partial or complete certificate chain provided by the peer,
	 * build a certificate path to a trusted root and return if it can be
	 * validated and is trusted for server SSL authentication based on the
	 * authentication type. The authentication type is the key exchange algorithm
	 * portion of the cipher suites represented as a String, such as "RSA",
	 * "DHE_DSS". Note: for some exportable cipher suites, the key exchange
	 * algorithm is determined at run time during the handshake. For instance,
	 * for TLS_RSA_EXPORT_WITH_RC4_40_MD5, the authType should be RSA_EXPORT when
	 * an ephemeral RSA key is used for the key exchange, and RSA when the key
	 * from the server certificate is used. Checking is case-sensitive.
	 *
	 * @param aChain
	 *           the peer certificate chain
	 * @param aAuthType
	 *           the key exchange algorithm used
	 *
	 * @exception CertificateException
	 *               if the certificate chain is not trusted by this
	 *               TrustManager.
	 */
	@Override
	public void checkServerTrusted(X509Certificate[] aChain, String aAuthType) throws CertificateException {
		logger.debug("checkServerTrusted(X509Certificate[], String): enter");

		if (aChain == null) {
			logger.info("checkServerTrusted(X509Certificate[], String): null certificate chain");
			throw new CertificateException("null certificate chain");
		}

		if (logger.isDebugEnabled()) {
			for (X509Certificate theCert : aChain) {
				logger.debug("checkServerTrusted(X509Certificate[], String): cert = "
				      + theCert.getSubjectX500Principal().getName());
			}
		}

		// Check the EKU settings of the server certificate?
		if (this.serverEKUs != null) {

			// Check the EKU settings of the leaf certificate
			X509Certificate theServerCert = aChain[0];
			List<String> theEkuValues = theServerCert.getExtendedKeyUsage();

			if (logger.isDebugEnabled() && theEkuValues != null) {
				for (String theEku : theEkuValues) {
					logger.debug("checkServerTrusted(X509Certificate[], String): EKU = " + theEku);
				}
			}

			boolean theEKUFound = false;
			for (String serverEKU : this.serverEKUs) {
				if (theEkuValues.contains(serverEKU)) {
					theEKUFound = true;
					break;
				}
			}

			if (!theEKUFound) {
				logger.info(
				      "checkServerTrusted(X509Certificate[], String): Server certificate does not have one of the trusted EKU settings");
				throw new CertificateException("Server certificate does not have one of the trusted EKU settings");
			}
		}
		else {
			logger.debug("checkServerTrusted(X509Certificate[], String): EKU setting ignored");
		}

		logger.debug("checkServerTrusted(X509Certificate[], String): exit");
	}

	/**
	 * Return an array of certificate authority certificates which are trusted
	 * for authenticating peers.
	 *
	 * @return a non-null (possibly empty) array of acceptable CA issuer
	 *         certificates.
	 */
	@Override
	public X509Certificate[] getAcceptedIssuers() {
		return this.trustedCertsArray;
	}

	/**
	 * Gets the list of trusted certificates.
	 *
	 * @return the trusted certificates
	 */
	public Set<X509Certificate> getTrustedCerts() {
		return this.trustedCerts;
	}

	/**
	 * Gets the list of trust anchors, which should match the trusted
	 * certificates.
	 *
	 * @return the trust anchors
	 */
	public Set<TrustAnchor> getTrustAnchors() {
		return this.trustAnchors;
	}

	/**
	 * Gets the PKIX parameters template that can be cloned and customized, but
	 * it must be synchronized since its not thread safe.
	 *
	 * @return the PKIX parameters template
	 */
	public PKIXBuilderParameters getPkixParamsTemplate() {
		return this.pkixParamsTemplate;
	}

	/**
	 * Gets the map of trusted principals and their associated public keys.
	 *
	 * @return Map of the trusted principals and their associated public keys
	 */
	public Map<X500Principal, List<PublicKey>> getTrustedSubjects() {
		return this.trustedSubjects;
	}

	/**
	 * Gets the list of trusted X.509 Extended Key Usage (EKU) values, where at
	 * least one of the values must exist in the client certificate. A
	 * {@code null} value means that the EKU values in the client certificate
	 * will be ignored. These values are The values are integer values, as
	 * defined in the PKIX Extended Key Purpose registry.
	 *
	 *
	 * @return the trust client EKU values or {@code null} to ignore the EKU
	 *         settings
	 */
	public List<String> getClientEKUs() {
		return this.clientEKUs;
	}

	/**
	 * Sets the list of trusted X.509 Extended Key Usage (EKU) values, where at
	 * least one of the values must exist in the client certificate. A
	 * {@code null} value means that the EKU values in the client certificate
	 * will be ignored. These values are The values are integer values, as
	 * defined in the PKIX Extended Key Purpose registry.
	 *
	 * @param aClientEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension
	 */
	public void setClientEKUs(List<String> aClientEKUs) {
		this.clientEKUs = aClientEKUs;
	}

	/**
	 * Gets the list of trusted X.509 Extended Key Usage (EKU) values, where at
	 * least one of the values must exist in the server certificate. A
	 * {@code null} value means that the EKU values in the server certificate
	 * will be ignored. These values are The values are integer values, as
	 * defined in the PKIX Extended Key Purpose registry.
	 *
	 *
	 * @return the trust server EKU values or {@code null} to ignore the EKU
	 *         settings
	 */
	public List<String> getServerEKUs() {
		return this.serverEKUs;
	}

	/**
	 * Sets the list of trusted X.509 Extended Key Usage (EKU) values, where at
	 * least one of the values must exist in the server certificate. A
	 * {@code null} value means that the EKU values in the server certificate
	 * will be ignored. These values are The values are integer values, as
	 * defined in the PKIX Extended Key Purpose registry.
	 *
	 * @param aServerEKUs
	 *           Set to a list of EKU Object Identifier (OID) values or
	 *           {@code null} to ignore the EKU extension
	 */
	public void setServerEKUs(List<String> aServerEKUs) {
		this.serverEKUs = aServerEKUs;
	}

}
