|
| 1 | +package life.qbic.projectmanagement.infrastructure; |
| 2 | + |
| 3 | +import static life.qbic.logging.service.LoggerFactory.logger; |
| 4 | + |
| 5 | +import java.io.BufferedOutputStream; |
| 6 | +import java.io.FileOutputStream; |
| 7 | +import java.io.IOException; |
| 8 | +import java.nio.charset.StandardCharsets; |
| 9 | +import java.nio.file.Path; |
| 10 | +import java.nio.file.Paths; |
| 11 | +import java.security.KeyStore; |
| 12 | +import java.security.KeyStore.PasswordProtection; |
| 13 | +import java.security.KeyStore.SecretKeyEntry; |
| 14 | +import java.security.KeyStoreException; |
| 15 | +import java.security.NoSuchAlgorithmException; |
| 16 | +import java.security.UnrecoverableKeyException; |
| 17 | +import java.security.cert.CertificateException; |
| 18 | +import java.util.HashMap; |
| 19 | +import java.util.Map; |
| 20 | +import java.util.Optional; |
| 21 | +import javax.crypto.spec.SecretKeySpec; |
| 22 | +import life.qbic.logging.api.Logger; |
| 23 | +import org.springframework.beans.factory.DisposableBean; |
| 24 | +import org.springframework.beans.factory.annotation.Value; |
| 25 | +import org.springframework.stereotype.Component; |
| 26 | + |
| 27 | +/** |
| 28 | + * Container for a Java keystore to maintain secrets within the application. |
| 29 | + * |
| 30 | + * @since 1.8.0 |
| 31 | + */ |
| 32 | +@Component |
| 33 | +public class DataManagerVault implements DisposableBean { |
| 34 | + |
| 35 | + public static final String UNEXPECTED_VAULT_EXCEPTION = "Unexpected vault exception"; |
| 36 | + private static final Logger log = logger(DataManagerVault.class); |
| 37 | + private static final String KEY_GENERATOR_ALGORITHM = "AES"; |
| 38 | + private static final double MIN_ENTROPY = 100; // Shannon entropy * length of secret |
| 39 | + private final KeyStore keyStore; |
| 40 | + private final String envVarKeystorePassword; |
| 41 | + private final String envVarKeystoreEntryPassword; |
| 42 | + private final Path keystorePath; |
| 43 | + |
| 44 | + public DataManagerVault(@Value("${qbic.security.vault.key.env}") String vaultKeyEnvVar, |
| 45 | + @Value("${qbic.security.vault.path}") String vaultPathString, |
| 46 | + @Value("${qbic.security.vault.entry.password.env}") String vaultEntryPassword) |
| 47 | + throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException { |
| 48 | + if (System.getenv(vaultKeyEnvVar) == null) { |
| 49 | + throw new DataManagerVaultException( |
| 50 | + "Cannot find value for environment variable: %s".formatted(vaultKeyEnvVar)); |
| 51 | + } |
| 52 | + if (System.getenv(vaultEntryPassword) == null) { |
| 53 | + throw new DataManagerVaultException( |
| 54 | + "Cannot find value for environment variable: %s".formatted(vaultEntryPassword) |
| 55 | + ); |
| 56 | + } |
| 57 | + this.envVarKeystoreEntryPassword = vaultEntryPassword; |
| 58 | + this.envVarKeystorePassword = vaultKeyEnvVar; |
| 59 | + |
| 60 | + double entropy; |
| 61 | + if ((entropy = calculateEntropy(System.getenv(envVarKeystorePassword))) < MIN_ENTROPY) { |
| 62 | + throw new DataManagerVaultException( |
| 63 | + "Entry of password for keystore was to low: %f (min: %f)".formatted(entropy, |
| 64 | + MIN_ENTROPY)); |
| 65 | + } |
| 66 | + if ((entropy = calculateEntropy(System.getenv(envVarKeystoreEntryPassword))) < MIN_ENTROPY) { |
| 67 | + throw new DataManagerVaultException( |
| 68 | + "Entry of password for keystore entries was to low: %f (min: %f)".formatted(entropy, |
| 69 | + MIN_ENTROPY)); |
| 70 | + } |
| 71 | + |
| 72 | + this.keystorePath = fromString(vaultPathString); |
| 73 | + this.keyStore = createVault(vaultKeyEnvVar, keystorePath); |
| 74 | + } |
| 75 | + |
| 76 | + // Calculates the product of Shannon entropy and secret length |
| 77 | + // See https://en.wikipedia.org/wiki/Entropy_(information_theory) |
| 78 | + private static double calculateEntropy(String secret) { |
| 79 | + if (secret == null || secret.isEmpty()) { |
| 80 | + return 0.0; |
| 81 | + } |
| 82 | + |
| 83 | + Map<Character, Integer> frequencyMap = new HashMap<>(); |
| 84 | + int length = secret.length(); |
| 85 | + |
| 86 | + // Count character frequencies |
| 87 | + for (char c : secret.toCharArray()) { |
| 88 | + frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1); |
| 89 | + } |
| 90 | + |
| 91 | + // Compute entropy |
| 92 | + double entropy = 0.0; |
| 93 | + for (Integer count : frequencyMap.values()) { |
| 94 | + double probability = (double) count / length; |
| 95 | + entropy += probability * (Math.log(probability) / Math.log(2)); |
| 96 | + } |
| 97 | + |
| 98 | + return -entropy * secret.length(); // Negate since log probabilities are negative |
| 99 | + } |
| 100 | + |
| 101 | + private static Path fromString(String path) { |
| 102 | + Path p = Paths.get(path); |
| 103 | + if (p.isAbsolute()) { |
| 104 | + return p; |
| 105 | + } |
| 106 | + return Path.of(System.getProperty("user.dir")).resolve(path); |
| 107 | + } |
| 108 | + |
| 109 | + private static KeyStore createVault(String vaultKeyEnvVar, Path vaultPath) |
| 110 | + throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException { |
| 111 | + |
| 112 | + return KeyStore.getInstance(vaultPath.toFile(), |
| 113 | + System.getenv(vaultKeyEnvVar).toCharArray()); |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Adds a secret under a given alias to the vault and stores the vault content into the configured |
| 118 | + * file. |
| 119 | + * <p> |
| 120 | + * {@link DataManagerVault} applies an AES encryption on the provided secret. |
| 121 | + * |
| 122 | + * @param alias the reference the entry can be retrieved again with |
| 123 | + * {@link DataManagerVault#read(String)}. |
| 124 | + * @param secret the secret to store in the vault |
| 125 | + * @since 1.8.0 |
| 126 | + */ |
| 127 | + public void add(String alias, String secret) { |
| 128 | + try { |
| 129 | + this.keyStore.setEntry(alias, new SecretKeyEntry(new SecretKeySpec(secret.getBytes( |
| 130 | + StandardCharsets.UTF_8), KEY_GENERATOR_ALGORITHM)), |
| 131 | + new PasswordProtection(System.getenv(envVarKeystoreEntryPassword).toCharArray())); |
| 132 | + } catch (KeyStoreException e) { |
| 133 | + throw new DataManagerVaultException(UNEXPECTED_VAULT_EXCEPTION, e); |
| 134 | + } |
| 135 | + |
| 136 | + writeToFileSystem(); |
| 137 | + } |
| 138 | + |
| 139 | + private void writeToFileSystem() { |
| 140 | + try (var bos = new BufferedOutputStream(new FileOutputStream(keystorePath.toFile()))) { |
| 141 | + keyStore.store(bos, System.getenv(envVarKeystorePassword).toCharArray()); |
| 142 | + bos.flush(); |
| 143 | + } catch (IOException e) { |
| 144 | + throw new DataManagerVaultException("Unexpected vault exception when writing to the keystore", |
| 145 | + e); |
| 146 | + } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException e) { |
| 147 | + throw new DataManagerVaultException(UNEXPECTED_VAULT_EXCEPTION, e); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + /** |
| 152 | + * Read looks for a matching entry for the provided alias. |
| 153 | + * <p> |
| 154 | + * If no entry for the given alias is found, the vault returns an {@link Optional#empty()}. |
| 155 | + * <p> |
| 156 | + * If the decryption of the secret fails, an {@link DataManagerVaultException} is thrown. |
| 157 | + * |
| 158 | + * @param alias the reference for the entry to retrieve |
| 159 | + * @return an {@link Optional<String>} with the potential secret. |
| 160 | + * @throws DataManagerVaultException if the decryption fails. |
| 161 | + * @since 1.8.0 |
| 162 | + */ |
| 163 | + public Optional<String> read(String alias) throws DataManagerVaultException { |
| 164 | + try { |
| 165 | + return Optional.ofNullable( |
| 166 | + this.keyStore.getKey(alias, System.getenv(envVarKeystoreEntryPassword).toCharArray())) |
| 167 | + .map(k -> new String(k.getEncoded(), StandardCharsets.UTF_8)); |
| 168 | + } catch (KeyStoreException | NoSuchAlgorithmException e) { |
| 169 | + throw new DataManagerVaultException(UNEXPECTED_VAULT_EXCEPTION, e); |
| 170 | + } catch (UnrecoverableKeyException e) { |
| 171 | + throw new DataManagerVaultException("Recovering alias entry failed", e); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + @Override |
| 176 | + public void destroy() throws Exception { |
| 177 | + log.debug("Destroying vault keystore " + this); |
| 178 | + // Ensure current cached entries are written to the file system |
| 179 | + writeToFileSystem(); |
| 180 | + } |
| 181 | + |
| 182 | + /** |
| 183 | + * Used for exceptions occurring during interactions with the {@link DataManagerVault}. |
| 184 | + * |
| 185 | + * @since 1.8.0 |
| 186 | + */ |
| 187 | + public static class DataManagerVaultException extends RuntimeException { |
| 188 | + |
| 189 | + public DataManagerVaultException(String message) { |
| 190 | + super(message); |
| 191 | + } |
| 192 | + |
| 193 | + public DataManagerVaultException(String message, Throwable cause) { |
| 194 | + super(message, cause); |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | +} |
0 commit comments