All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.fabric8.kubernetes.client.internal.CertUtils Maven / Gradle / Ivy

There is a newer version: 7.1.0
Show newest version
/*
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.fabric8.kubernetes.client.internal;

import io.fabric8.kubernetes.client.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;

public class CertUtils {
  private CertUtils() {
  }

  private static final Logger LOG = LoggerFactory.getLogger(CertUtils.class);
  private static final String TRUST_STORE_SYSTEM_PROPERTY = "javax.net.ssl.trustStore";
  private static final String TRUST_STORE_PASSWORD_SYSTEM_PROPERTY = "javax.net.ssl.trustStorePassword";
  private static final String TRUST_STORE_TYPE_SYSTEM_PROPERTY = "javax.net.ssl.trustStoreType";
  private static final String KEY_STORE_SYSTEM_PROPERTY = "javax.net.ssl.keyStore";
  private static final String KEY_STORE_PASSWORD_SYSTEM_PROPERTY = "javax.net.ssl.keyStorePassword";
  private static final String KEY_STORE_DEFAULT_PASSWORD = "changeit";

  public static ByteArrayInputStream getInputStreamFromDataOrFile(String data, String file) throws IOException {
    if (data != null) {
      return createInputStreamFromBase64EncodedString(data);
    }
    return new ByteArrayInputStream(new String(Files.readAllBytes(Paths.get(file))).trim().getBytes());
  }

  public static KeyStore createTrustStore(String caCertData, String caCertFile, String trustStoreFile,
      String trustStorePassphrase) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    ByteArrayInputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile);

    KeyStore trustStore = loadTrustStore(trustStoreFile,
        getPassphrase(TRUST_STORE_PASSWORD_SYSTEM_PROPERTY, trustStorePassphrase));

    return mergePemCertsIntoTrustStore(pemInputStream, trustStore, true);
  }

  static KeyStore loadTrustStore(String trustStoreFile, char[] trustStorePassphrase)
      throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, FileNotFoundException {
    String trustStoreType = System.getProperty(TRUST_STORE_TYPE_SYSTEM_PROPERTY, KeyStore.getDefaultType());
    KeyStore trustStore = KeyStore.getInstance(trustStoreType);

    if (Utils.isNotNullOrEmpty(trustStoreFile)) {
      try (FileInputStream fis = new FileInputStream(trustStoreFile)) {
        trustStore.load(fis, trustStorePassphrase);
      }
    } else {
      loadDefaultTrustStoreFile(trustStore, trustStorePassphrase);
    }
    return trustStore;
  }

  static KeyStore mergePemCertsIntoTrustStore(ByteArrayInputStream pemInputStream, KeyStore trustStore, boolean first)
      throws CertificateException, KeyStoreException {
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    while (pemInputStream.available() > 0) {
      X509Certificate cert;
      try {
        cert = (X509Certificate) certFactory.generateCertificate(pemInputStream);
      } catch (CertificateException e) {
        if (pemInputStream.available() > 0) {
          // any remaining input means there is an actual problem with the key contents or file format
          throw e;
        }
        LOG.debug("The trailing entry generated a certificate exception.  More than likely the contents end with comments.", e);
        break;
      }
      try {
        String alias = cert.getSubjectX500Principal().getName() + "_" + cert.getSerialNumber().toString(16);
        trustStore.setCertificateEntry(alias, cert);
        first = false;
      } catch (KeyStoreException e) {
        if (first) {
          // could be that the store type is not writable, rather than some elaborate check for read-only
          // we'll simply try again with a well supported type
          pemInputStream.reset();
          KeyStore writableStore = KeyStore.getInstance("PKCS12");
          try {
            writableStore.load(null, null); // initialize the instance
          } catch (NoSuchAlgorithmException | CertificateException | IOException e1) {
            throw e; // not usable, just give up
          }
          for (String alias : Collections.list(trustStore.aliases())) {
            writableStore.setCertificateEntry(alias, trustStore.getCertificate(alias));
          }
          return mergePemCertsIntoTrustStore(pemInputStream, writableStore, false);
        }
        throw e;
      }
    }
    return trustStore;
  }

  public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream, String clientKeyAlgo,
      char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase)
      throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    Collection certificates = certFactory.generateCertificates(certInputStream);
    PrivateKey privateKey = loadKey(keyInputStream, clientKeyAlgo);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    if (Utils.isNotNullOrEmpty(keyStoreFile)) {
      try (FileInputStream fis = new FileInputStream(keyStoreFile)) {
        keyStore.load(fis, keyStorePassphrase);
      }
    } else {
      loadDefaultKeyStoreFile(keyStore, keyStorePassphrase);
    }

    String alias = certificates.stream().map(cert -> ((X509Certificate) cert).getIssuerX500Principal().getName())
        .collect(Collectors.joining("_"));
    keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, certificates.toArray(new Certificate[0]));

    return keyStore;
  }

  private static PrivateKey loadKey(InputStream keyInputStream, String clientKeyAlgo)
      throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
    if (clientKeyAlgo == null) {
      clientKeyAlgo = "RSA"; // by default let's assume it's RSA
    }
    byte[] keyBytes = decodePem(keyInputStream);
    if (clientKeyAlgo.equals("EC") || clientKeyAlgo.equals("RSA")) {
      try {
        return handleOtherKeys(keyBytes, clientKeyAlgo);
      } catch (IOException e) {
        // could be a version 1 key
        if (clientKeyAlgo.equals("EC")) {
          return handleECKey(keyBytes);
        } else {
          throw e;
        }
      }
    }

    throw new InvalidKeySpecException("Unknown type of PKCS8 Private Key, tried RSA and ECDSA");
  }

  private static PrivateKey handleECKey(byte[] keyBytes)
      throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
    return KeyFactory.getInstance("EC").generatePrivate(PKCS1Util.getECKeySpec(keyBytes));
  }

  private static PrivateKey handleOtherKeys(byte[] keyBytes, String clientKeyAlgo)
      throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    try {
      // First let's try PKCS8
      return KeyFactory.getInstance(clientKeyAlgo).generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
    } catch (InvalidKeySpecException e) {
      // Otherwise try PKCS8
      RSAPrivateCrtKeySpec keySpec = PKCS1Util.decodePKCS1(keyBytes);
      return KeyFactory.getInstance(clientKeyAlgo).generatePrivate(keySpec);
    }
  }

  private static void loadDefaultTrustStoreFile(KeyStore keyStore, char[] trustStorePassphrase)
      throws CertificateException, NoSuchAlgorithmException, IOException {

    File trustStoreFile = getDefaultTrustStoreFile();

    if (!loadDefaultStoreFile(keyStore, trustStoreFile, trustStorePassphrase)) {
      keyStore.load(null);
    }
  }

  private static File getDefaultTrustStoreFile() {
    String securityDirectory = System.getProperty("java.home") + File.separator + "lib" + File.separator + "security"
        + File.separator;

    String trustStorePath = System.getProperty(TRUST_STORE_SYSTEM_PROPERTY);
    if (Utils.isNotNullOrEmpty(trustStorePath)) {
      return new File(trustStorePath);
    }

    File jssecacertsFile = new File(securityDirectory + "jssecacerts");
    if (jssecacertsFile.exists() && jssecacertsFile.isFile()) {
      return jssecacertsFile;
    }

    return new File(securityDirectory + "cacerts");
  }

  private static void loadDefaultKeyStoreFile(KeyStore keyStore, char[] keyStorePassphrase)
      throws CertificateException, NoSuchAlgorithmException, IOException {

    String keyStorePath = System.getProperty(KEY_STORE_SYSTEM_PROPERTY);
    if (Utils.isNotNullOrEmpty(keyStorePath)) {
      File keyStoreFile = new File(keyStorePath);
      if (loadDefaultStoreFile(keyStore, keyStoreFile, keyStorePassphrase)) {
        return;
      }
    }

    keyStore.load(null);
  }

  @SuppressWarnings("java:S6437")
  private static boolean loadDefaultStoreFile(KeyStore keyStore, File fileToLoad, char[] passphrase) {
    if (!fileToLoad.exists() || !fileToLoad.isFile() || fileToLoad.length() == 0) {
      return false;
    }
    Exception ex = null;
    try (FileInputStream fis = new FileInputStream(fileToLoad)) {
      keyStore.load(fis, passphrase);
      return true;
    } catch (Exception e) {
      ex = e;
    }
    // last chance, try changeit
    if ((passphrase == null || passphrase.length == 0) && ex.getCause() instanceof UnrecoverableKeyException) {
      try (FileInputStream fis1 = new FileInputStream(fileToLoad)) {
        keyStore.load(fis1, KEY_STORE_DEFAULT_PASSWORD.toCharArray());
        return true;
      } catch (Exception e1) {
        // still no good
      }
    }
    LOG.info("There is a problem with reading default keystore/truststore file {} "
        + "- the file won't be loaded. The reason is: {}", fileToLoad, ex.getMessage());
    return false;
  }

  public static KeyStore createKeyStore(String clientCertData, String clientCertFile, String clientKeyData,
      String clientKeyFile, String clientKeyAlgo, String clientKeyPassphrase, String keyStoreFile,
      String keyStorePassphrase)
      throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {
    ByteArrayInputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile);
    ByteArrayInputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
    return createKeyStore(certInputStream, keyInputStream, clientKeyAlgo, clientKeyPassphrase.toCharArray(),
        keyStoreFile, getPassphrase(KEY_STORE_PASSWORD_SYSTEM_PROPERTY, keyStorePassphrase));
  }

  private static char[] getPassphrase(String property, String passphrase) {
    if (Utils.isNullOrEmpty(passphrase)) {
      passphrase = System.getProperty(property, passphrase);
    }
    if (passphrase != null) {
      return passphrase.toCharArray();
    }
    return null;
  }

  // This method is inspired and partly taken over from
  // http://oauth.googlecode.com/svn/code/java/
  // All credits to belong to them.
  private static byte[] decodePem(InputStream keyInputStream) throws IOException {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyInputStream))) {
      String line;
      while ((line = reader.readLine()) != null) {
        if (line.contains("-----BEGIN ")) {
          return readBytes(reader, line.trim().replace("BEGIN", "END"));
        }
      }
      throw new IOException("PEM is invalid: no begin marker");
    }
  }

  private static byte[] readBytes(BufferedReader reader, String endMarker) throws IOException {
    String line;
    StringBuffer buf = new StringBuffer();

    while ((line = reader.readLine()) != null) {
      if (line.indexOf(endMarker) != -1) {
        return Base64.getDecoder().decode(buf.toString());
      }
      buf.append(line.trim());
    }
    throw new IOException("PEM is invalid : No end marker");
  }

  private static ByteArrayInputStream createInputStreamFromBase64EncodedString(String data) {
    byte[] bytes;
    try {
      bytes = Base64.getDecoder().decode(data);
    } catch (IllegalArgumentException illegalArgumentException) {
      bytes = data.getBytes();
    }

    return new ByteArrayInputStream(bytes);
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy