diff --git a/tool/pom.xml b/tool/pom.xml index cb563968389..9c13a58c6eb 100644 --- a/tool/pom.xml +++ b/tool/pom.xml @@ -72,7 +72,7 @@ - + org.apache.maven.plugins maven-surefire-plugin diff --git a/tool/src/main/java/org/wildfly/security/tool/Command.java b/tool/src/main/java/org/wildfly/security/tool/Command.java index 7edf54a9925..81720e1b07b 100644 --- a/tool/src/main/java/org/wildfly/security/tool/Command.java +++ b/tool/src/main/java/org/wildfly/security/tool/Command.java @@ -22,21 +22,36 @@ import java.io.BufferedReader; import java.io.Console; +import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import java.util.function.Supplier; +import javax.crypto.SecretKey; + +import org.wildfly.security.credential.Credential; +import org.wildfly.security.credential.SecretKeyCredential; +import org.wildfly.security.credential.store.CredentialStore; +import org.wildfly.security.credential.store.CredentialStoreException; +import org.wildfly.security.credential.store.impl.PropertiesCredentialStore; +import org.wildfly.security.encryption.SecretKeyUtil; +import org.wildfly.security.password.WildFlyElytronPasswordProvider; + /** * Base command class * @author Peter Skopek @@ -48,8 +63,14 @@ public abstract class Command { */ public static final int GENERAL_CONFIGURATION_ERROR = 7; + public static final int GENERAL_CONFIGURATION_WARNING = 1; + public static final int INPUT_DATA_NOT_CONFIRMED = 3; + public static Supplier ELYTRON_PASSWORD_PROVIDERS = () -> new Provider[] { + WildFlyElytronPasswordProvider.getInstance() + }; + private int status = 255; private List redirectionValues; @@ -106,7 +127,7 @@ public static boolean isWindows() { * @param confirm confirm data after the first input * @param confirmPrompt confirmation text * @return data as user inputs it - * @throws Exception + * @throws Exception if a {@link BufferedReader} cannot be created */ protected String prompt(boolean echo, String prompt, boolean confirm, String confirmPrompt) throws Exception { Console console = System.console(); @@ -204,6 +225,27 @@ public void printDuplicatesWarning(CommandLine cmdLine, List duplicatesA } } + /** + * Print a warning message. + * + * @param warning The warning to be shown + */ + protected void warningHandler(String warning) { + System.out.print("WARNING: "); + System.out.println(warning); + } + + /** + * Set an {@value GENERAL_CONFIGURATION_ERROR} and raise the exception + * + * @param e The exception thrown during execution + * @throws Exception The exception to be handled by Elytron Tool + */ + protected void errorHandler(Exception e) throws Exception { + setStatus(GENERAL_CONFIGURATION_ERROR); + throw e; + } + /** * Get the command debug option */ @@ -270,4 +312,94 @@ protected Supplier getProvidersSupplier(final String providersList) } }; } + + /** + * Acquire a given secret key from a {@link CredentialStore}. + * + * @param alias the name for a secret key within the CredentialStore + * @return the requested {@link SecretKey}, or {@code null} if it could not be retrieved + * @throws CredentialStoreException when credential store initialization or an operation fails + * @throws NoSuchAlgorithmException if the credential store algorithm cannot be found + * @throws GeneralSecurityException when a secret key cannot be generated + * @throws Exception when an existing credential store does not contain the secret key + */ + SecretKey getSecretKey(Boolean createCredentialStore, String credentialStoreLocation, String alias, Boolean populate, + String inputRealmLocation) throws Exception { + CredentialStore credentialStore; + String csType = PropertiesCredentialStore.NAME; + try { + credentialStore = CredentialStore.getInstance(csType); + } catch (NoSuchAlgorithmException e) { + // fallback to load all possible providers + credentialStore = CredentialStore.getInstance(csType, getProvidersSupplier(null)); + } + Map implProps = new HashMap<>(); + implProps.put("create", String.valueOf(createCredentialStore)); + implProps.put("location", credentialStoreLocation); + implProps.put("modifiable", Boolean.TRUE.toString()); + credentialStore.initialize(implProps); + try { + credentialStore.retrieve(alias, SecretKeyCredential.class).getSecretKey(); + System.out.println(ElytronToolMessages.msg.existingCredentialStore()); + } catch (Exception e) { + if (!createCredentialStore) { + warningHandler(ElytronToolMessages.msg.skippingBlockMissingCredentialStore()); + return null; + } + if (populate) { + SecretKey key = SecretKeyUtil.generateSecretKey(256); + Credential keyCredential = new SecretKeyCredential(key); + credentialStore.store(alias, keyCredential); + credentialStore.flush(); + } else { + errorHandler(ElytronToolMessages.msg.cmdFileSystemPopulateUnspecified()); + } + } + SecretKey key; + try { + key = credentialStore.retrieve(alias, SecretKeyCredential.class).getSecretKey(); + } catch (NullPointerException e) { + System.out.println(ElytronToolMessages.msg.cmdFileSystemEncryptionNoSecretKey(credentialStoreLocation, inputRealmLocation)); + return null; + } + + return key; + } +} + +class Params { + static final String ALIAS_PARAM = "alias"; + static final String BULK_CONVERT_PARAM = "bulk-convert"; + static final String CREDENTIAL_STORE_LOCATION_PARAM = "credential-store"; + static final String CREATE_CREDENTIAL_STORE_PARAM = "create"; + static final String CREDENTIAL_STORE_TYPE_PARAM = "type"; + static final String CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM = "credential-store-provider"; + static final String ENCODED_PARAM = "encoded"; + static final String FILE_PARAM = "file"; + static final String DEBUG_PARAM = "debug"; + static final String DIRECTORY_PARAM = "directory"; + static final String HASH_ENCODING_PARAM = "hash-encoding"; + static final String HELP_PARAM = "help"; + static final String IMPLEMENTATION_PROPERTIES_PARAM = "properties"; + static final String INPUT_LOCATION_PARAM = "input-location"; + static final String ITERATION_PARAM = "iteration"; + static final String KEYSTORE_PARAM = "keystore"; + static final String LEVELS_PARAM = "levels"; + static final String NAME_PARAM = "name"; + static final String OTHER_PROVIDERS_PARAM = "other-providers"; + static final String OUTPUT_LOCATION_PARAM = "output-location"; + static final String PASSWORD_PARAM = "password"; + static final String REALM_NAME_PARAM = "realm-name"; + static final String SALT_PARAM = "salt"; + static final String SECRET_KEY_ALIAS_PARAM = "secret-key"; + static final String SILENT_PARAM = "silent"; + static final String STORE_LOCATION_PARAM = "location"; + static final String SUMMARY_PARAM = "summary"; + + // Other constants + static final Integer DEFAULT_LEVELS = 2; + static final String DEFAULT_SECRET_KEY_ALIAS = "key"; + static final String FILE_SEPARATOR = File.separator; + static final String LINE_SEPARATOR = System.lineSeparator(); + static final String SUMMARY_DIVIDER = "-".repeat(100); } diff --git a/tool/src/main/java/org/wildfly/security/tool/CredentialStoreCommand.java b/tool/src/main/java/org/wildfly/security/tool/CredentialStoreCommand.java index 8bc6577bc04..62b2637a773 100644 --- a/tool/src/main/java/org/wildfly/security/tool/CredentialStoreCommand.java +++ b/tool/src/main/java/org/wildfly/security/tool/CredentialStoreCommand.java @@ -70,6 +70,20 @@ import org.wildfly.security.pem.Pem; import org.wildfly.security.ssh.util.SshUtil; +import static org.wildfly.security.tool.Params.ALIAS_PARAM; +import static org.wildfly.security.tool.Params.CREATE_CREDENTIAL_STORE_PARAM; +import static org.wildfly.security.tool.Params.CREDENTIAL_STORE_TYPE_PARAM; +import static org.wildfly.security.tool.Params.CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM; +import static org.wildfly.security.tool.Params.DEBUG_PARAM; +import static org.wildfly.security.tool.Params.HELP_PARAM; +import static org.wildfly.security.tool.Params.IMPLEMENTATION_PROPERTIES_PARAM; +import static org.wildfly.security.tool.Params.ITERATION_PARAM; +import static org.wildfly.security.tool.Params.OTHER_PROVIDERS_PARAM; +import static org.wildfly.security.tool.Params.PASSWORD_PARAM; +import static org.wildfly.security.tool.Params.SALT_PARAM; +import static org.wildfly.security.tool.Params.STORE_LOCATION_PARAM; +import static org.wildfly.security.tool.Params.SUMMARY_PARAM; + /** * Credential Store Command * Performs credential store related operations. @@ -80,7 +94,6 @@ class CredentialStoreCommand extends Command { public static int ACTION_NOT_DEFINED = 5; public static int ALIAS_NOT_FOUND = 6; - public static int GENERAL_CONFIGURATION_ERROR = 7; public static final String RSA_ALGORITHM = "RSA"; public static final String DSA_ALGORITHM = "DSA"; @@ -88,26 +101,13 @@ class CredentialStoreCommand extends Command { public static final String CREDENTIAL_STORE_COMMAND = "credential-store"; - public static final String STORE_LOCATION_PARAM = "location"; - public static final String IMPLEMENTATION_PROPERTIES_PARAM = "properties"; - public static final String CREDENTIAL_STORE_PASSWORD_PARAM = "password"; - public static final String CREDENTIAL_STORE_TYPE_PARAM = "type"; - public static final String SALT_PARAM = "salt"; - public static final String ITERATION_PARAM = "iteration"; public static final String PASSWORD_CREDENTIAL_VALUE_PARAM = "secret"; public static final String ADD_ALIAS_PARAM = "add"; - public static final String ALIAS_ARGUMENT = "alias"; public static final String CHECK_ALIAS_PARAM = "exists"; public static final String ALIASES_PARAM = "aliases"; public static final String CREDENTIAL_TYPES = "credential-types"; public static final String REMOVE_ALIAS_PARAM = "remove"; - public static final String CREATE_CREDENTIAL_STORE_PARAM = "create"; - public static final String HELP_PARAM = "help"; - public static final String PRINT_SUMMARY_PARAM = "summary"; public static final String ENTRY_TYPE_PARAM = "entry-type"; - public static final String OTHER_PROVIDERS_PARAM = "other-providers"; - public static final String DEBUG_PARAM = "debug"; - public static final String CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM = "credential-store-provider"; public static final String SIZE_PARAM = "size"; public static final String GENERATE_KEY_PAIR_PARAM = "generate-key-pair"; @@ -142,7 +142,7 @@ class CredentialStoreCommand extends Command { options.addOption(opt); opt = new Option("u", IMPLEMENTATION_PROPERTIES_PARAM, true, ElytronToolMessages.msg.cmdLineImplementationPropertiesDesc()); options.addOption(opt); - opt = new Option("p", CREDENTIAL_STORE_PASSWORD_PARAM, true, ElytronToolMessages.msg.cmdLineCredentialStorePassword()); + opt = new Option("p", PASSWORD_PARAM, true, ElytronToolMessages.msg.cmdLineCredentialStorePassword()); opt.setArgName("pwd"); options.addOption(opt); options.addOption("s", SALT_PARAM, true, ElytronToolMessages.msg.cmdLineSaltDesc()); @@ -167,7 +167,7 @@ class CredentialStoreCommand extends Command { opt = new Option("t", CREDENTIAL_STORE_TYPE_PARAM, true, ElytronToolMessages.msg.cmdLineCredentialStoreTypeDesc()); opt.setArgName("type"); options.addOption(opt); - options.addOption("f", PRINT_SUMMARY_PARAM, false, ElytronToolMessages.msg.cmdLinePrintSummary()); + options.addOption("f", SUMMARY_PARAM, false, ElytronToolMessages.msg.cmdLinePrintSummary()); options.addOption("j", SIZE_PARAM, true, ElytronToolMessages.msg.cmdLineKeySizeDesc()); options.addOption("k", ALGORITHM_PARAM, true, ElytronToolMessages.msg.cmdLineKeyAlgorithmDesc()); @@ -210,7 +210,7 @@ class CredentialStoreCommand extends Command { options.addOption(Option.builder() .longOpt(ENTRY) .hasArg() - .argName(ALIAS_ARGUMENT) + .argName(ALIAS_PARAM) .desc(ElytronToolMessages.msg.cmdLineEntryDesc()) .build()); @@ -247,25 +247,25 @@ class CredentialStoreCommand extends Command { og.addOption(Option.builder() .longOpt(GENERATE_SECRET_KEY) .hasArg() - .argName(ALIAS_ARGUMENT) + .argName(ALIAS_PARAM) .desc(ElytronToolMessages.msg.generateSecretKey()) .build()); og.addOption(Option.builder() .longOpt(EXPORT_SECRET_KEY) .hasArg() - .argName(ALIAS_ARGUMENT) + .argName(ALIAS_PARAM) .desc(ElytronToolMessages.msg.exportSecretKey()) .build()); og.addOption(Option.builder() .longOpt(IMPORT_SECRET_KEY) .hasArg() - .argName(ALIAS_ARGUMENT) + .argName(ALIAS_PARAM) .desc(ElytronToolMessages.msg.importSecretKey()) .build()); og.addOption(Option.builder() .longOpt(ENCRYPT) .hasArg() - .argName(ALIAS_ARGUMENT) + .argName(ALIAS_PARAM) .desc(ElytronToolMessages.msg.encrypt()) .build()); @@ -352,7 +352,7 @@ public void execute(String[] args) throws Exception { setStatus(GENERAL_CONFIGURATION_ERROR); throw ElytronToolMessages.msg.storageFileDoesNotExist(location); } - String csPassword = cmdLine.getOptionValue(CREDENTIAL_STORE_PASSWORD_PARAM); + String csPassword = cmdLine.getOptionValue(PASSWORD_PARAM); String password = csPassword == null ? "" : csPassword; String salt = cmdLine.getOptionValue(SALT_PARAM); String csType = cmdLine.getOptionValue(CREDENTIAL_STORE_TYPE_PARAM, KeyStoreCredentialStore.KEY_STORE_CREDENTIAL_STORE); @@ -368,7 +368,7 @@ public void execute(String[] args) throws Exception { if (!createStorage && location != null && !Files.exists(Paths.get(location))) { throw ElytronToolMessages.msg.locationDoesNotExistCreationDisabled(location); } - boolean printSummary = cmdLine.hasOption(PRINT_SUMMARY_PARAM); + boolean printSummary = cmdLine.hasOption(SUMMARY_PARAM); String secret = cmdLine.getOptionValue(PASSWORD_CREDENTIAL_VALUE_PARAM); String key = cmdLine.getOptionValue(KEY_PARAM); @@ -404,7 +404,7 @@ public void execute(String[] args) throws Exception { csPassword = prompt(false, ElytronToolMessages.msg.credentialStorePasswordPrompt(), createStorage, ElytronToolMessages.msg.credentialStorePasswordPromptConfirm()); if (csPassword == null) { setStatus(GENERAL_CONFIGURATION_ERROR); - throw ElytronToolMessages.msg.optionNotSpecified(CREDENTIAL_STORE_PASSWORD_PARAM); + throw ElytronToolMessages.msg.optionNotSpecified(PASSWORD_PARAM); } } if (csPassword != null) { @@ -718,7 +718,7 @@ private void generateSecretKey(CredentialStore credentialStore, String entryType String alias = cmdLine.getOptionValue(GENERATE_SECRET_KEY); if (alias.length() == 0) { setStatus(GENERAL_CONFIGURATION_ERROR); - throw ElytronToolMessages.msg.optionNotSpecified(ALIAS_ARGUMENT); + throw ElytronToolMessages.msg.optionNotSpecified(ALIAS_PARAM); } final SecretKey secretKey; @@ -744,7 +744,7 @@ private void exportSecretKey(CredentialStore credentialStore) throws Exception { String alias = cmdLine.getOptionValue(EXPORT_SECRET_KEY); if (alias.length() == 0) { setStatus(GENERAL_CONFIGURATION_ERROR); - throw ElytronToolMessages.msg.optionNotSpecified(ALIAS_ARGUMENT); + throw ElytronToolMessages.msg.optionNotSpecified(ALIAS_PARAM); } if (credentialStore.exists(alias, SecretKeyCredential.class)) { @@ -762,7 +762,7 @@ private void importSecretKey(CredentialStore credentialStore, String entryType, String alias = cmdLine.getOptionValue(IMPORT_SECRET_KEY); if (alias.length() == 0) { setStatus(GENERAL_CONFIGURATION_ERROR); - throw ElytronToolMessages.msg.optionNotSpecified(ALIAS_ARGUMENT); + throw ElytronToolMessages.msg.optionNotSpecified(ALIAS_PARAM); } if (key == null) { @@ -797,7 +797,7 @@ private String encrypt(CredentialStore credentialStore) throws Exception { String alias = cmdLine.getOptionValue(ENCRYPT); if (alias.length() == 0) { setStatus(GENERAL_CONFIGURATION_ERROR); - throw ElytronToolMessages.msg.optionNotSpecified(ALIAS_ARGUMENT); + throw ElytronToolMessages.msg.optionNotSpecified(ALIAS_PARAM); } String cipherTextToken = null; diff --git a/tool/src/main/java/org/wildfly/security/tool/ElytronTool.java b/tool/src/main/java/org/wildfly/security/tool/ElytronTool.java index 5670562ebd9..10d51f47596 100644 --- a/tool/src/main/java/org/wildfly/security/tool/ElytronTool.java +++ b/tool/src/main/java/org/wildfly/security/tool/ElytronTool.java @@ -156,4 +156,4 @@ Command findCommand(String commandName) { return null; } -} +} \ No newline at end of file diff --git a/tool/src/main/java/org/wildfly/security/tool/FileSystemEncryptRealmCommand.java b/tool/src/main/java/org/wildfly/security/tool/FileSystemEncryptRealmCommand.java index 621efcc79b6..ccedd94c1fb 100644 --- a/tool/src/main/java/org/wildfly/security/tool/FileSystemEncryptRealmCommand.java +++ b/tool/src/main/java/org/wildfly/security/tool/FileSystemEncryptRealmCommand.java @@ -17,23 +17,39 @@ */ package org.wildfly.security.tool; +import static org.wildfly.security.tool.Params.BULK_CONVERT_PARAM; +import static org.wildfly.security.tool.Params.CREATE_CREDENTIAL_STORE_PARAM; +import static org.wildfly.security.tool.Params.CREDENTIAL_STORE_LOCATION_PARAM; +import static org.wildfly.security.tool.Params.DEBUG_PARAM; +import static org.wildfly.security.tool.Params.DEFAULT_LEVELS; +import static org.wildfly.security.tool.Params.DEFAULT_SECRET_KEY_ALIAS; +import static org.wildfly.security.tool.Params.DIRECTORY_PARAM; +import static org.wildfly.security.tool.Params.ENCODED_PARAM; +import static org.wildfly.security.tool.Params.FILE_PARAM; +import static org.wildfly.security.tool.Params.HASH_ENCODING_PARAM; +import static org.wildfly.security.tool.Params.HELP_PARAM; +import static org.wildfly.security.tool.Params.INPUT_LOCATION_PARAM; +import static org.wildfly.security.tool.Params.LEVELS_PARAM; +import static org.wildfly.security.tool.Params.LINE_SEPARATOR; +import static org.wildfly.security.tool.Params.NAME_PARAM; +import static org.wildfly.security.tool.Params.OUTPUT_LOCATION_PARAM; +import static org.wildfly.security.tool.Params.REALM_NAME_PARAM; +import static org.wildfly.security.tool.Params.SECRET_KEY_ALIAS_PARAM; +import static org.wildfly.security.tool.Params.SILENT_PARAM; +import static org.wildfly.security.tool.Params.SUMMARY_DIVIDER; +import static org.wildfly.security.tool.Params.SUMMARY_PARAM; + import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; import java.util.stream.Stream; import javax.crypto.SecretKey; import org.apache.commons.cli.CommandLine; @@ -44,12 +60,6 @@ import org.apache.commons.cli.Options; import org.wildfly.security.auth.realm.FileSystemRealmUtil; import org.wildfly.security.auth.realm.FileSystemSecurityRealm; -import org.wildfly.security.credential.Credential; -import org.wildfly.security.credential.SecretKeyCredential; -import org.wildfly.security.credential.store.CredentialStore; -import org.wildfly.security.credential.store.impl.PropertiesCredentialStore; -import org.wildfly.security.encryption.SecretKeyUtil; -import org.wildfly.security.password.WildFlyElytronPasswordProvider; import org.wildfly.security.password.spec.Encoding; /** @@ -60,35 +70,13 @@ */ class FileSystemEncryptRealmCommand extends Command { - static final int GENERAL_CONFIGURATION_WARNING = 1; static final String FILE_SYSTEM_ENCRYPT_COMMAND = "filesystem-realm-encrypt"; - static final int SUMMARY_WIDTH = 100; - - private static final String HELP_PARAM = "help"; - private static final String DEBUG_PARAM = "debug"; - private static final String SILENT_PARAM = "silent"; - private static final String SUMMARY_PARAM = "summary"; - private static final String INPUT_REALM_LOCATION_PARAM = "input-location"; - private static final String REALM_NAME_PARAM = "realm-name"; - private static final String OUTPUT_REALM_LOCATION_PARAM = "output-location"; - private static final String CREDENTIAL_STORE_LOCATION_PARAM = "credential-store"; - private static final String CREATE_CREDENTIAL_STORE_PARAM = "create"; - private static final String SECRET_KEY_ALIAS_PARAM = "secret-key"; - private static final String HASH_ENCODING_PARAM = "hash-encoding"; - private static final String ENCODED_PARAM = "encoded"; - private static final String LEVELS_PARAM = "levels"; + private static final String POPULATE_SECRET_KEY_PARAM = "populate"; - private static final String BULK_CONVERT_PARAM = "bulk-convert"; - private static final String FILE_ARG = "file"; - private static final String DIRECTORY_ARG = "directory"; - private static final String NAME_ARG = "name"; private static final String DEFAULT_FILESYSTEM_REALM_NAME = "encrypted-filesystem-realm"; - public static Supplier ELYTRON_PASSWORD_PROVIDERS = () -> new Provider[]{ - WildFlyElytronPasswordProvider.getInstance() - }; private final List descriptors = new ArrayList<>(); - private final List PARAMS_LIST = new ArrayList<>(Arrays.asList(INPUT_REALM_LOCATION_PARAM, OUTPUT_REALM_LOCATION_PARAM)); + private final List PARAMS_LIST = new ArrayList<>(Arrays.asList(INPUT_LOCATION_PARAM, OUTPUT_LOCATION_PARAM)); private final Options options; private final CommandLineParser parser = new DefaultParser(); @@ -102,48 +90,48 @@ class FileSystemEncryptRealmCommand extends Command { options = new Options(); Option option; - option = new Option("i", INPUT_REALM_LOCATION_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptInputLocationDesc()); - option.setArgName(DIRECTORY_ARG); + option = new Option("i", INPUT_LOCATION_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptInputLocationDesc()); + option.setArgName(DIRECTORY_PARAM); options.addOption(option); option = new Option("r", REALM_NAME_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptNewRealmDesc()); - option.setArgName(DIRECTORY_ARG); + option.setArgName(DIRECTORY_PARAM); options.addOption(option); - option = new Option("o", OUTPUT_REALM_LOCATION_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptOutputLocationDesc()); - option.setArgName(DIRECTORY_ARG); + option = new Option("o", OUTPUT_LOCATION_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptOutputLocationDesc()); + option.setArgName(DIRECTORY_PARAM); options.addOption(option); option = new Option("c", CREDENTIAL_STORE_LOCATION_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptCredentialStoreDesc()); - option.setArgName(FILE_ARG); + option.setArgName(FILE_PARAM); options.addOption(option); option = new Option("a", CREATE_CREDENTIAL_STORE_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptCreateCredentialStoreDesc()); - option.setArgName(NAME_ARG); + option.setArgName(NAME_PARAM); options.addOption(option); option = new Option("s", SECRET_KEY_ALIAS_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptSecretKeyDesc()); - option.setArgName(NAME_ARG); + option.setArgName(NAME_PARAM); options.addOption(option); option = new Option("e", HASH_ENCODING_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptHashEncodingDesc()); - option.setArgName(NAME_ARG); + option.setArgName(NAME_PARAM); options.addOption(option); option = new Option("f", ENCODED_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptEncodedDesc()); - option.setArgName(NAME_ARG); + option.setArgName(NAME_PARAM); options.addOption(option); option = new Option("l", LEVELS_PARAM, true, ElytronToolMessages.msg.cmdFileSystemEncryptLevelsDesc()); - option.setArgName(NAME_ARG); + option.setArgName(NAME_PARAM); options.addOption(option); option = new Option("p", POPULATE_SECRET_KEY_PARAM, true, ElytronToolMessages.msg.cmdFileSystemRealmEncryptPopulateDesc()); - option.setArgName(NAME_ARG); + option.setArgName(NAME_PARAM); options.addOption(option); option = new Option("b", BULK_CONVERT_PARAM, true, ElytronToolMessages.msg.cmdFileSystemRealmEncryptBulkConvertDesc()); - option.setArgName(FILE_ARG); + option.setArgName(FILE_PARAM); options.addOption(option); option = Option.builder().longOpt(HELP_PARAM).desc(ElytronToolMessages.msg.cmdLineHelp()).build(); @@ -296,12 +284,12 @@ public void execute(String[] args) throws Exception { if (cmdLine.hasOption(SUMMARY_PARAM)) { summaryMode = true; summaryString = new StringBuilder(); - summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-"))); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(SUMMARY_DIVIDER); + summaryString.append(LINE_SEPARATOR); summaryString.append("Summary for execution of Elytron-Tool command FileSystemRealmEncrypt"); - summaryString.append(System.getProperty("line.separator")); - summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-"))); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); + summaryString.append(SUMMARY_DIVIDER); + summaryString.append(LINE_SEPARATOR); } printDuplicatesWarning(cmdLine); @@ -358,7 +346,7 @@ public void execute(String[] args) throws Exception { } if (levelsOption == null) { - descriptor.setLevels(2); + descriptor.setLevels(DEFAULT_LEVELS); } else { try { descriptor.setLevels(Integer.parseInt(levelsOption)); @@ -390,7 +378,7 @@ public void execute(String[] args) throws Exception { if (secretKeyAliasOption != null) { descriptor.setSecretKeyAlias(secretKeyAliasOption); } else { - descriptor.setSecretKeyAlias("key"); + descriptor.setSecretKeyAlias(DEFAULT_SECRET_KEY_ALIAS); } descriptors.add(descriptor); checkDescriptorFields(descriptor); @@ -401,7 +389,7 @@ public void execute(String[] args) throws Exception { } else { if (summaryMode) { summaryString.append(String.format("Options were specified via descriptor file: %s, converting multiple old filesystem realm", bulkConvert)); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } parseDescriptorFile(bulkConvert); } @@ -410,11 +398,11 @@ public void execute(String[] args) throws Exception { createWildFlyScript(); if (summaryMode) { - summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-"))); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(SUMMARY_DIVIDER); + summaryString.append(LINE_SEPARATOR); summaryString.append("End of summary"); - summaryString.append(System.getProperty("line.separator")); - summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-"))); + summaryString.append(LINE_SEPARATOR); + summaryString.append(SUMMARY_DIVIDER); System.out.println(summaryString); } @@ -445,7 +433,8 @@ public void help() { * * @param warning The warning to be shown */ - private void warningHandler(String warning) { + @Override + protected void warningHandler(String warning) { warningOccurred = true; if (!silentMode) { System.out.print("WARNING: "); @@ -454,7 +443,7 @@ private void warningHandler(String warning) { if (summaryMode) { summaryString.append("WARNING: "); summaryString.append(warning); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } } @@ -464,13 +453,14 @@ private void warningHandler(String warning) { * @param e The exception thrown during execution * @throws Exception The exception to be handled by Elytron Tool */ - private void errorHandler(Exception e) throws Exception { + @Override + protected void errorHandler(Exception e) throws Exception { setStatus(GENERAL_CONFIGURATION_ERROR); if (summaryMode) { summaryString.append("Error was thrown during execution:"); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); summaryString.append(e.getMessage()); - System.out.println(System.getProperty("line.separator") + summaryString.toString()); + System.out.println(LINE_SEPARATOR + summaryString.toString()); } throw e; } @@ -481,26 +471,26 @@ private void errorHandler(Exception e) throws Exception { * @param count The amount of descriptor blocks in the file */ private void printDescriptorBlocks(int count) { - summaryString.append(System.getProperty("line.separator")); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); + summaryString.append(LINE_SEPARATOR); summaryString.append("Found following unencrypted filesystem-realm combinations, null indicates missing required component:"); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); for (int i = 0; i < count; i++) { StringBuilder summary = new StringBuilder(); summary.append("\tPrinting summary for block "); summary.append(i + 1); - summary.append(System.getProperty("line.separator")); + summary.append(LINE_SEPARATOR); Descriptor descriptor = descriptors.get(i); for (String param : PARAMS_LIST) { summary.append("\t\t"); summary.append(param); summary.append(" - "); summary.append(getDescriptorParam(param, descriptor)); - summary.append(System.getProperty("line.separator")); + summary.append(LINE_SEPARATOR); } summaryString.append(summary); } - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } /** @@ -512,9 +502,9 @@ private void printDescriptorBlocks(int count) { */ private String getDescriptorParam(String param, Descriptor descriptor) { switch (param) { - case INPUT_REALM_LOCATION_PARAM: + case INPUT_LOCATION_PARAM: return descriptor.getInputRealmLocation(); - case OUTPUT_REALM_LOCATION_PARAM: + case OUTPUT_LOCATION_PARAM: return descriptor.getOutputRealmLocation(); case REALM_NAME_PARAM: return descriptor.getFileSystemRealmName(); @@ -551,10 +541,10 @@ private void parseDescriptorFile(String file) throws Exception { String option = parts[0]; String arg = parts[1]; switch (option) { - case INPUT_REALM_LOCATION_PARAM: + case INPUT_LOCATION_PARAM: descriptor.setInputRealmLocation(arg); break; - case OUTPUT_REALM_LOCATION_PARAM: + case OUTPUT_LOCATION_PARAM: descriptor.setOutputRealmLocation(arg); break; case REALM_NAME_PARAM: @@ -633,7 +623,7 @@ private void findMissingRequiredValuesAndSetValues(int count, Descriptor descrip descriptor.setEncoded(true); } if(descriptor.getLevels() == null) { - descriptor.setLevels(2); + descriptor.setLevels(DEFAULT_LEVELS); } if(descriptor.getCredentialStore() == null) { warningHandler(ElytronToolMessages.msg.skippingDescriptorBlockCredentialStoreLocation(count)); @@ -648,7 +638,7 @@ private void findMissingRequiredValuesAndSetValues(int count, Descriptor descrip } if(descriptor.getSecretKeyAlias() == null) { - descriptor.setSecretKeyAlias("key"); + descriptor.setSecretKeyAlias(DEFAULT_SECRET_KEY_ALIAS); } if (missingRequiredValue) { @@ -667,46 +657,11 @@ private void createFileSystemRealm() throws Exception { System.out.println(ElytronToolMessages.msg.fileSystemRealmEncryptCreatingRealm(descriptor.getInputRealmLocation())); if (checkDescriptorFields(descriptor)) continue; - CredentialStore credentialStore; - // check if credential-store and secret-key-alias are both specified, or both null - String csType = PropertiesCredentialStore.NAME; - try { - credentialStore = CredentialStore.getInstance(csType); - } catch (NoSuchAlgorithmException e) { - // fallback to load all possible providers - credentialStore = CredentialStore.getInstance(csType, getProvidersSupplier(null)); - } - Map implProps = new HashMap<>(); - implProps.put("create", String.valueOf(descriptor.getCreateCredentialStore())); - implProps.put("location", descriptor.getCredentialStore()); - implProps.put("modifiable", Boolean.TRUE.toString()); - credentialStore.initialize(implProps); - try { - credentialStore.retrieve(descriptor.getSecretKeyAlias(), SecretKeyCredential.class).getSecretKey(); - System.out.println(ElytronToolMessages.msg.existingCredentialStore()); - } catch (Exception e) { - if (!descriptor.getCreateCredentialStore()) { - warningHandler(ElytronToolMessages.msg.skippingBlockMissingCredentialStore()); - descriptor.reset(); - continue; - } - if (descriptor.getPopulate()) { - SecretKey key = SecretKeyUtil.generateSecretKey(256); - Credential keyCredential = new SecretKeyCredential(key); - credentialStore.store(descriptor.getSecretKeyAlias(), keyCredential); - credentialStore.flush(); - } else { - errorHandler(ElytronToolMessages.msg.cmdFileSystemPopulateUnspecified()); - } - } - SecretKey key; - try { - key = credentialStore.retrieve(descriptor.getSecretKeyAlias(), SecretKeyCredential.class).getSecretKey(); - } catch (NullPointerException e) { - System.out.println(ElytronToolMessages.msg.cmdFileSystemEncryptionNoSecretKey(descriptor.getCredentialStore(), descriptor.getInputRealmLocation())); - descriptor.reset(); - continue; - } + + // Load secret key + SecretKey key = getSecretKey(descriptor.getCreateCredentialStore(), descriptor.getCredentialStore(), + descriptor.getSecretKeyAlias(), descriptor.getPopulate(), descriptor.getInputRealmLocation()); + if (key == null) continue; FileSystemSecurityRealm oldFileSystemRealm = FileSystemSecurityRealm.builder() .setRoot(Paths.get(descriptor.getInputRealmLocation())) @@ -742,7 +697,7 @@ private void createWildFlyScript() throws Exception { int levels = descriptor.getLevels(); if(secretKeyAlias == null) { - secretKeyAlias = "key"; + secretKeyAlias = DEFAULT_SECRET_KEY_ALIAS; } String createScriptCheck = ""; @@ -776,11 +731,11 @@ private void createWildFlyScript() throws Exception { if (summaryMode) { summaryString.append(String.format("Configured script for WildFly at %s", scriptPath)); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); summaryString.append("The script is using the following names:"); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); summaryString.append(String.format("Name of filesystem-realm: %s", fileSystemRealmName)); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } List scriptLines = Arrays.asList( @@ -809,4 +764,4 @@ private boolean checkDescriptorFields(Descriptor descriptor) { return false; } -} +} \ No newline at end of file diff --git a/tool/src/main/java/org/wildfly/security/tool/FileSystemRealmCommand.java b/tool/src/main/java/org/wildfly/security/tool/FileSystemRealmCommand.java index 6a442b5c52d..2bf21d4e484 100644 --- a/tool/src/main/java/org/wildfly/security/tool/FileSystemRealmCommand.java +++ b/tool/src/main/java/org/wildfly/security/tool/FileSystemRealmCommand.java @@ -17,6 +17,18 @@ */ package org.wildfly.security.tool; +import static org.wildfly.security.tool.Params.BULK_CONVERT_PARAM; +import static org.wildfly.security.tool.Params.DEBUG_PARAM; +import static org.wildfly.security.tool.Params.DIRECTORY_PARAM; +import static org.wildfly.security.tool.Params.FILE_PARAM; +import static org.wildfly.security.tool.Params.HELP_PARAM; +import static org.wildfly.security.tool.Params.LINE_SEPARATOR; +import static org.wildfly.security.tool.Params.NAME_PARAM; +import static org.wildfly.security.tool.Params.OUTPUT_LOCATION_PARAM; +import static org.wildfly.security.tool.Params.SILENT_PARAM; +import static org.wildfly.security.tool.Params.SUMMARY_DIVIDER; +import static org.wildfly.security.tool.Params.SUMMARY_PARAM; + import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -60,23 +72,12 @@ */ class FileSystemRealmCommand extends Command { - static final int GENERAL_CONFIGURATION_WARNING = 1; static final String FILE_SYSTEM_REALM_COMMAND = "filesystem-realm"; - static final int SUMMARY_WIDTH = 100; - private static final String HELP_PARAM = "help"; - private static final String DEBUG_PARAM = "debug"; - private static final String SILENT_PARAM = "silent"; - private static final String SUMMARY_PARAM = "summary"; private static final String USERS_FILE_PARAM = "users-file"; private static final String ROLES_FILE_PARAM = "roles-file"; - private static final String OUTPUT_LOCATION_PARAM = "output-location"; private static final String FILESYSTEM_REALM_NAME_PARAM = "filesystem-realm-name"; private static final String SECURITY_DOMAIN_NAME_PARAM = "security-domain-name"; - private static final String BULK_CONVERT_PARAM = "bulk-convert"; - private static final String FILE_ARG = "file"; - private static final String DIRECTORY_ARG = "directory"; - private static final String NAME_ARG = "name"; private static final String DEFAULT_FILESYSTEM_REALM_NAME = "converted-properties-filesystem-realm"; private static final String DEFAULT_SECURITY_DOMAIN_NAME = "converted-properties-security-domain"; @@ -96,27 +97,27 @@ class FileSystemRealmCommand extends Command { Option option; option = new Option("u", USERS_FILE_PARAM, true, ElytronToolMessages.msg.cmdFileSystemRealmUsersFileDesc()); - option.setArgName(FILE_ARG); + option.setArgName(FILE_PARAM); options.addOption(option); option = new Option("r", ROLES_FILE_PARAM, true, ElytronToolMessages.msg.cmdFileSystemRealmRolesFileDesc()); - option.setArgName(FILE_ARG); + option.setArgName(FILE_PARAM); options.addOption(option); option = new Option("o", OUTPUT_LOCATION_PARAM, true, ElytronToolMessages.msg.cmdFileSystemRealmOutputLocationDesc()); - option.setArgName(DIRECTORY_ARG); + option.setArgName(DIRECTORY_PARAM); options.addOption(option); option = new Option("b", BULK_CONVERT_PARAM, true, ElytronToolMessages.msg.cmdFileSystemRealmBulkConvertDesc()); - option.setArgName(NAME_ARG); + option.setArgName(NAME_PARAM); options.addOption(option); option = new Option("f", FILESYSTEM_REALM_NAME_PARAM, true, ElytronToolMessages.msg.cmdFileSystemRealmFileSystemRealmNameDesc()); - option.setArgName(NAME_ARG); + option.setArgName(NAME_PARAM); options.addOption(option); option = new Option("s", SECURITY_DOMAIN_NAME_PARAM, true, ElytronToolMessages.msg.cmdFileSystemRealmSecurityDomainNameDesc()); - option.setArgName(NAME_ARG); + option.setArgName(NAME_PARAM); options.addOption(option); option = Option.builder().longOpt(HELP_PARAM).desc(ElytronToolMessages.msg.cmdLineHelp()).build(); @@ -226,12 +227,12 @@ public void execute(String[] args) throws Exception { if (cmdLine.hasOption(SUMMARY_PARAM)) { summaryMode = true; summaryString = new StringBuilder(); - summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-"))); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(SUMMARY_DIVIDER); + summaryString.append(LINE_SEPARATOR); summaryString.append("Summary for execution of Elytron-Tool command FileSystemRealm"); - summaryString.append(System.getProperty("line.separator")); - summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-"))); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); + summaryString.append(SUMMARY_DIVIDER); + summaryString.append(LINE_SEPARATOR); } printDuplicatesWarning(cmdLine); @@ -243,7 +244,7 @@ public void execute(String[] args) throws Exception { if (bulkConvert == null) { if (summaryMode) { summaryString.append("Options were specified via CLI, converting single users-roles combination"); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } if (usersFileOption == null) { @@ -268,7 +269,7 @@ public void execute(String[] args) throws Exception { } else { if (summaryMode) { summaryString.append(String.format("Options were specified via descriptor file: %s, converting multiple users-roles combinations", bulkConvert)); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } parseDescriptorFile(bulkConvert); } @@ -277,11 +278,11 @@ public void execute(String[] args) throws Exception { createWildFlyScript(); if (summaryMode) { - summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-"))); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(SUMMARY_DIVIDER); + summaryString.append(LINE_SEPARATOR); summaryString.append("End of summary"); - summaryString.append(System.getProperty("line.separator")); - summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-"))); + summaryString.append(LINE_SEPARATOR); + summaryString.append(SUMMARY_DIVIDER); System.out.println(summaryString); } @@ -306,13 +307,8 @@ public void help() { true); } - /** - * Prints out a warning message if silentMode is not enabled and adds the warning to the summary - * if summaryMode is enabled - * - * @param warning The warning to be shown - */ - private void warningHandler(String warning) { + @Override + protected void warningHandler(String warning) { warningOccurred = true; if (! silentMode) { System.out.print("WARNING: "); @@ -321,23 +317,18 @@ private void warningHandler(String warning) { if (summaryMode) { summaryString.append("WARNING: "); summaryString.append(warning); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } } - /** - * Determines if a summary needs to be printed and prints summary after an error is thrown - * - * @param e The exception thrown during execution - * @throws Exception The exception to be handled by Elytron Tool - */ - private void errorHandler(Exception e) throws Exception { + @Override + protected void errorHandler(Exception e) throws Exception { setStatus(GENERAL_CONFIGURATION_ERROR); if (summaryMode) { summaryString.append("Error was thrown during execution:"); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); summaryString.append(e.getMessage()); - System.out.println(System.getProperty("line.separator") + summaryString.toString()); + System.out.println(LINE_SEPARATOR + summaryString.toString()); } throw e; } @@ -348,26 +339,26 @@ private void errorHandler(Exception e) throws Exception { * @param count The amount of descriptor blocks in the file */ private void printDescriptorBlocks(int count) { - summaryString.append(System.getProperty("line.separator")); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); + summaryString.append(LINE_SEPARATOR); summaryString.append("Found following users-roles combinations, null indicates missing required component:"); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); for (int i = 0; i < count; i++) { StringBuilder summary = new StringBuilder(); summary.append("\tPrinting summary for block "); summary.append(i + 1); - summary.append(System.getProperty("line.separator")); + summary.append(LINE_SEPARATOR); Descriptor descriptor = descriptors.get(i); for (String param : PARAMS_LIST) { summary.append("\t\t"); summary.append(param); summary.append(" - "); summary.append(getDescriptorParam(param, descriptor)); - summary.append(System.getProperty("line.separator")); + summary.append(LINE_SEPARATOR); } summaryString.append(summary); } - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } /** @@ -583,7 +574,7 @@ private void createFileSystemRealm() throws Exception { } if (summaryMode) { summaryString.append(String.format("Added roles: %s for user %s.", ArrayUtils.toString(roles), user)); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } } usersMap.forEach((key,value) -> { @@ -648,17 +639,17 @@ private void createWildFlyScript() throws Exception { if (summaryMode) { summaryString.append(String.format("Configured script for WildFly named %s.sh at %s.", fileSystemRealmName, fullOutputPath)); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); summaryString.append("The script is using the following names:"); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); summaryString.append(String.format("Name of filesystem-realm: %s", fileSystemRealmName)); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } if (securityDomainName != null && !securityDomainName.isEmpty()) { if (summaryMode) { summaryString.append(String.format("Name of security-domain: %s",securityDomainName)); - summaryString.append(System.getProperty("line.separator")); + summaryString.append(LINE_SEPARATOR); } } else { warningHandler(String.format("No name provided for security-domain, using default security-domain name for %s.", usersFile)); diff --git a/tool/src/main/java/org/wildfly/security/tool/MaskCommand.java b/tool/src/main/java/org/wildfly/security/tool/MaskCommand.java index fea010bfb23..bf029f0e6ee 100644 --- a/tool/src/main/java/org/wildfly/security/tool/MaskCommand.java +++ b/tool/src/main/java/org/wildfly/security/tool/MaskCommand.java @@ -28,6 +28,10 @@ import org.apache.commons.cli.Options; import org.wildfly.security.util.PasswordBasedEncryptionUtil; +import static org.wildfly.security.tool.Params.DEBUG_PARAM; +import static org.wildfly.security.tool.Params.HELP_PARAM; +import static org.wildfly.security.tool.Params.ITERATION_PARAM; +import static org.wildfly.security.tool.Params.SALT_PARAM; import static org.wildfly.security.util.PasswordUtil.generateSecureRandomString; /** @@ -42,12 +46,7 @@ class MaskCommand extends Command { * Command string */ public static final String MASK_COMMAND = "mask"; - - static final String SALT_PARAM = "salt"; - static final String ITERATION_PARAM = "iteration"; static final String SECRET_PARAM = "secret"; - static final String HELP_PARAM = "help"; - static final String DEBUG_PARAM = "debug"; private final int defaultIterationCount = 10000; diff --git a/tool/src/main/java/org/wildfly/security/tool/VaultCommand.java b/tool/src/main/java/org/wildfly/security/tool/VaultCommand.java index 41c2efdc035..3b3b2b2ee86 100644 --- a/tool/src/main/java/org/wildfly/security/tool/VaultCommand.java +++ b/tool/src/main/java/org/wildfly/security/tool/VaultCommand.java @@ -19,6 +19,20 @@ import static org.wildfly.security.credential.store.CredentialStore.CredentialSourceProtectionParameter; import static org.wildfly.security.credential.store.CredentialStore.getInstance; +import static org.wildfly.security.tool.Params.ALIAS_PARAM; +import static org.wildfly.security.tool.Params.BULK_CONVERT_PARAM; +import static org.wildfly.security.tool.Params.CREDENTIAL_STORE_TYPE_PARAM; +import static org.wildfly.security.tool.Params.CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM; +import static org.wildfly.security.tool.Params.DEBUG_PARAM; +import static org.wildfly.security.tool.Params.FILE_SEPARATOR; +import static org.wildfly.security.tool.Params.HELP_PARAM; +import static org.wildfly.security.tool.Params.IMPLEMENTATION_PROPERTIES_PARAM; +import static org.wildfly.security.tool.Params.ITERATION_PARAM; +import static org.wildfly.security.tool.Params.KEYSTORE_PARAM; +import static org.wildfly.security.tool.Params.OTHER_PROVIDERS_PARAM; +import static org.wildfly.security.tool.Params.SALT_PARAM; +import static org.wildfly.security.tool.Params.STORE_LOCATION_PARAM; +import static org.wildfly.security.tool.Params.SUMMARY_PARAM; import java.io.BufferedReader; import java.io.File; @@ -70,22 +84,11 @@ public class VaultCommand extends Command { public static final String VAULT_COMMAND = "vault"; - public static final String STORE_LOCATION_PARAM = "location"; - public static final String PRINT_SUMMARY_PARAM = "summary"; public static final String FAIL_IF_EXIST_PARAM = "fail-if-exist"; - // vault command actions - public static String BULK_CONVERT_PARAM = "bulk-convert"; - // convert options - public static final String KEYSTORE_PARAM = "keystore"; public static final String KEYSTORE_PASSWORD_PARAM = "keystore-password"; public static final String ENC_DIR_PARAM = "enc-dir"; - public static final String SALT_PARAM = "salt"; - public static final String ITERATION_PARAM = "iteration"; - public static final String ALIAS_PARAM = "alias"; - public static final String HELP_PARAM = "help"; - public static final String DEBUG_PARAM = "debug"; private static final class Descriptor { String keyStoreURL; @@ -126,22 +129,22 @@ public VaultCommand() { o = new Option("l", STORE_LOCATION_PARAM, true, ElytronToolMessages.msg.cmdLineVaultCSLocationDesc()); o.setArgName("loc"); options.addOption(o); - o = new Option("u", CredentialStoreCommand.IMPLEMENTATION_PROPERTIES_PARAM, true, ElytronToolMessages.msg.cmdLineVaultCSParametersDesc()); + o = new Option("u", IMPLEMENTATION_PROPERTIES_PARAM, true, ElytronToolMessages.msg.cmdLineVaultCSParametersDesc()); o.setValueSeparator(';'); o.setOptionalArg(true); options.addOption(o); - o = new Option("t", CredentialStoreCommand.CREDENTIAL_STORE_TYPE_PARAM, true, ElytronToolMessages.msg.cmdLineVaultCSTypeDesc()); + o = new Option("t", CREDENTIAL_STORE_TYPE_PARAM, true, ElytronToolMessages.msg.cmdLineVaultCSTypeDesc()); o.setArgName("type"); options.addOption(o); - o = new Option("o", CredentialStoreCommand.OTHER_PROVIDERS_PARAM, true, ElytronToolMessages.msg.cmdLineOtherProvidersDesc()); + o = new Option("o", OTHER_PROVIDERS_PARAM, true, ElytronToolMessages.msg.cmdLineOtherProvidersDesc()); o.setArgName("providers"); o.setOptionalArg(true); options.addOption(o); - o = new Option("q", CredentialStoreCommand.CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM, true, ElytronToolMessages.msg.cmdLineCustomCredentialStoreProviderDesc()); + o = new Option("q", CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM, true, ElytronToolMessages.msg.cmdLineCustomCredentialStoreProviderDesc()); o.setArgName("cs-provider"); o.setOptionalArg(true); options.addOption(o); - options.addOption("f", PRINT_SUMMARY_PARAM, false, ElytronToolMessages.msg.cmdLineVaultPrintSummary()); + options.addOption("f", SUMMARY_PARAM, false, ElytronToolMessages.msg.cmdLineVaultPrintSummary()); Option b = new Option("b", BULK_CONVERT_PARAM, true, ElytronToolMessages.msg.cliCommandBulkVaultCredentialStoreConversion()); b.setArgName("description file"); @@ -164,7 +167,7 @@ public void execute(String[] args) throws Exception { return; } - boolean printSummary = cmdLine.hasOption(PRINT_SUMMARY_PARAM); + boolean printSummary = cmdLine.hasOption(SUMMARY_PARAM); printDuplicatesWarning(cmdLine); @@ -204,10 +207,10 @@ public void execute(String[] args) throws Exception { String vaultSecretKeyAlias = cmdLine.getOptionValue(ALIAS_PARAM, "vault"); String location = cmdLine.getOptionValue(STORE_LOCATION_PARAM); - Map implProps = CredentialStoreCommand.parseCredentialStoreProperties(cmdLine.getOptionValue(CredentialStoreCommand.IMPLEMENTATION_PROPERTIES_PARAM)); - String csType = cmdLine.getOptionValue(CredentialStoreCommand.CREDENTIAL_STORE_TYPE_PARAM, KeyStoreCredentialStore.KEY_STORE_CREDENTIAL_STORE); - String csProvider = cmdLine.getOptionValue(CredentialStoreCommand.CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM); - String csOtherProviders = cmdLine.getOptionValue(CredentialStoreCommand.OTHER_PROVIDERS_PARAM); + Map implProps = CredentialStoreCommand.parseCredentialStoreProperties(cmdLine.getOptionValue(IMPLEMENTATION_PROPERTIES_PARAM)); + String csType = cmdLine.getOptionValue(CREDENTIAL_STORE_TYPE_PARAM, KeyStoreCredentialStore.KEY_STORE_CREDENTIAL_STORE); + String csProvider = cmdLine.getOptionValue(CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM); + String csOtherProviders = cmdLine.getOptionValue(OTHER_PROVIDERS_PARAM); if (location == null || location.isEmpty()) { location = convertedStoreName(encryptionDirectory, implProps); @@ -252,7 +255,7 @@ public void help() { private String convertedStoreName(String encryptionDirectory, Map implProps) { final String implPropsLocation = implProps.get("location"); - return (implPropsLocation != null && ! implPropsLocation.isEmpty()) ? implPropsLocation : encryptionDirectory + (encryptionDirectory.isEmpty() || encryptionDirectory.endsWith(File.separator) ? "" : File.separator) + "converted-vault.cr-store"; + return (implPropsLocation != null && ! implPropsLocation.isEmpty()) ? implPropsLocation : encryptionDirectory + (encryptionDirectory.isEmpty() || encryptionDirectory.endsWith(FILE_SEPARATOR) ? "" : FILE_SEPARATOR) + "converted-vault.cr-store"; } private HashMap convert(String keyStoreURL, String vaultPassword, String encryptionDirectory, @@ -368,13 +371,13 @@ private List parseDescriptorFile(String descriptorFileLocation) thro descriptor.secretKeyAlias = value; } else if (attribute.equals(STORE_LOCATION_PARAM)) { descriptor.outputFile = value; - } else if (attribute.equals(CredentialStoreCommand.IMPLEMENTATION_PROPERTIES_PARAM)) { + } else if (attribute.equals(IMPLEMENTATION_PROPERTIES_PARAM)) { descriptor.implProps = CredentialStoreCommand.parseCredentialStoreProperties(value); - } else if (attribute.equals(CredentialStoreCommand.CREDENTIAL_STORE_TYPE_PARAM)) { + } else if (attribute.equals(CREDENTIAL_STORE_TYPE_PARAM)) { descriptor.csType = value; - } else if (attribute.equals(CredentialStoreCommand.CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM)) { + } else if (attribute.equals(CUSTOM_CREDENTIAL_STORE_PROVIDER_PARAM)) { descriptor.csProvider = value; - } else if (attribute.equals(CredentialStoreCommand.OTHER_PROVIDERS_PARAM)) { + } else if (attribute.equals(OTHER_PROVIDERS_PARAM)) { descriptor.csOtherProviders = value; } else { throw ElytronToolMessages.msg.unrecognizedDescriptorAttribute(Integer.toString(lineNumber)); diff --git a/tool/src/test/java/org/wildfly/security/tool/FileSystemRealmCommandTest.java b/tool/src/test/java/org/wildfly/security/tool/FileSystemRealmCommandTest.java index 5d6c0ffc60d..d12788e9803 100644 --- a/tool/src/test/java/org/wildfly/security/tool/FileSystemRealmCommandTest.java +++ b/tool/src/test/java/org/wildfly/security/tool/FileSystemRealmCommandTest.java @@ -19,6 +19,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.wildfly.security.tool.Params.FILE_SEPARATOR; +import static org.wildfly.security.tool.Params.LINE_SEPARATOR; import java.io.File; import java.nio.file.Files; @@ -225,11 +227,11 @@ private void compareScriptOutput(String fileSystemRealmName, String securityDoma public static void getAbsolutePaths() throws Exception { ABSOLUTE_BASE_DIR = Paths.get(FileSystemRealmCommandTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()) .toAbsolutePath() - + System.getProperty("file.separator") + + FILE_SEPARATOR + "filesystem-realm" - + System.getProperty("file.separator"); - ABSOLUTE_BASE_DIR_USERS = ABSOLUTE_BASE_DIR + "users" + System.getProperty("file.separator"); - ABSOLUTE_BASE_DIR_ROLES = ABSOLUTE_BASE_DIR + "roles" + System.getProperty("file.separator"); + + FILE_SEPARATOR; + ABSOLUTE_BASE_DIR_USERS = ABSOLUTE_BASE_DIR + "users" + FILE_SEPARATOR; + ABSOLUTE_BASE_DIR_ROLES = ABSOLUTE_BASE_DIR + "roles" + FILE_SEPARATOR; OUTPUT_LOCATIONS_CLI[0] = RELATIVE_BASE_DIR + "output-1"; OUTPUT_LOCATIONS_CLI[1] = ABSOLUTE_BASE_DIR + "output-2"; OUTPUT_LOCATIONS_CLI[2] = RELATIVE_BASE_DIR + "output-3"; @@ -260,26 +262,26 @@ public static void getAbsolutePaths() throws Exception { public static void createAbsoluteDescriptorFile() throws Exception { String fileText = ""; fileText = fileText + "users-file:" + ABSOLUTE_BASE_DIR_USERS + "users-5.properties"; - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; fileText = fileText + "roles-file:" + ABSOLUTE_BASE_DIR_ROLES + "roles-5.properties"; - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; fileText += "output-location:" + ABSOLUTE_BASE_DIR + "output-5-bulk"; - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; fileText += "filesystem-realm-name:nameOfFileSystemRealm5"; - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; fileText += "security-domain-name:nameOfSecurityDomain5"; - fileText += System.getProperty("line.separator"); - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; + fileText += LINE_SEPARATOR; fileText = fileText + "users-file:" + ABSOLUTE_BASE_DIR_USERS + "users-6.properties"; - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; fileText = fileText + "roles-file:" + ABSOLUTE_BASE_DIR_ROLES + "roles-6.properties"; - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; fileText = fileText + "output-location:" + ABSOLUTE_BASE_DIR + "output-6-bulk"; - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; fileText += "filesystem-realm-name:nameOfFileSystemRealm6"; - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; fileText += "security-domain-name:nameOfSecurityDomain6"; - fileText += System.getProperty("line.separator"); + fileText += LINE_SEPARATOR; Files.write(Paths.get(RELATIVE_BASE_DIR + "descriptor-file-2"), fileText.getBytes(), StandardOpenOption.CREATE); } diff --git a/tool/src/test/java/org/wildfly/security/tool/MaskCommandTest.java b/tool/src/test/java/org/wildfly/security/tool/MaskCommandTest.java index af6414e3daf..3ce57f7b912 100644 --- a/tool/src/test/java/org/wildfly/security/tool/MaskCommandTest.java +++ b/tool/src/test/java/org/wildfly/security/tool/MaskCommandTest.java @@ -18,6 +18,7 @@ package org.wildfly.security.tool; import static org.junit.Assert.assertTrue; +import static org.wildfly.security.tool.Params.LINE_SEPARATOR; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; @@ -49,7 +50,7 @@ public void maskCompatibilityCheck() throws Exception { String[] args = {"--iteration", "123", "--salt", "ASDF1234", "--secret", secret}; String retVal = executeCommandAndCheckStatusAndGetOutput(args); - String retValNoNewLine = retVal.substring(0, retVal.indexOf(System.getProperty("line.separator"))); + String retValNoNewLine = retVal.substring(0, retVal.indexOf(LINE_SEPARATOR)); assertTrue("output has to be the as pre-generated one", ("MASK-" + pbGenerated + ";" + "ASDF1234" + ";" + 123).equals(retValNoNewLine)); } @@ -60,7 +61,7 @@ public void testMissingSaltAndIteration() { String[] args = { "--secret", "super_secret" }; String retVal = executeCommandAndCheckStatusAndGetOutput(args); - String[] retValLines = retVal.split(System.getProperty("line.separator")); + String[] retValLines = retVal.split(LINE_SEPARATOR); assertTrue("Message about invalid salt parameter must be present", retValLines[0].contains("Invalid \"salt\" parameter. Generated value")); assertTrue("Message about invalid iteration parameter must be present", ("Invalid \"iteration\" parameter. Default value \"" + defaultIteration + "\" will be used.").equals(retValLines[1])); @@ -77,7 +78,7 @@ public void testMissingIteration() { String[] args = { "--secret", secret, "--salt", salt }; String retVal = executeCommandAndCheckStatusAndGetOutput(args); - String[] retValLines = retVal.split(System.getProperty("line.separator")); + String[] retValLines = retVal.split(LINE_SEPARATOR); assertTrue("Message about invalid iteration parameter must be present", ("Invalid \"iteration\" parameter. Default value \"" + defaultIteration + "\" will be used.").equals(retValLines[0])); assertTrue("Output has to be the as pre-generated one", ("MASK-" + pregenerated + ";" + salt + ";" + defaultIteration).equals(retValLines[1])); @@ -89,7 +90,7 @@ public void testMissingSalt() { String[] args = { "--secret", "super_secret", "--iteration", "123" }; String retVal = executeCommandAndCheckStatusAndGetOutput(args); - String[] retValLines = retVal.split(System.getProperty("line.separator")); + String[] retValLines = retVal.split(LINE_SEPARATOR); assertTrue("Message about invalid salt parameter must be present", retValLines[0].contains("Invalid \"salt\" parameter. Generated value")); assertTrue("Message about invalid salt parameter must be present", retValLines[1].contains("MASK-")); @@ -124,7 +125,7 @@ public void testIterationAsStringValue() { String[] args = { "--secret", secret, "--salt", salt, "--iteration", "abcd" }; String retVal = executeCommandAndCheckStatusAndGetOutput(args); - String[] retValLines = retVal.split(System.getProperty("line.separator")); + String[] retValLines = retVal.split(LINE_SEPARATOR); assertTrue("IllegalArgumentException must be present", ("java.lang.IllegalArgumentException: ELYTOOL00007: Invalid \"iteration\" value. Must be an integer between 1 and 2147483647, inclusive").equals(retValLines[0])); assertTrue("Message about invalid iteration parameter must be present", ("Invalid \"iteration\" parameter. Default value \"" + defaultIteration + "\" will be used.").equals(retValLines[1])); @@ -141,7 +142,7 @@ public void testIterationAsLongMax() { String[] args = { "--secret", secret, "--salt", salt, "--iteration", String.valueOf(Long.MAX_VALUE) }; String retVal = executeCommandAndCheckStatusAndGetOutput(args); - String[] retValLines = retVal.split(System.getProperty("line.separator")); + String[] retValLines = retVal.split(LINE_SEPARATOR); assertTrue("IllegalArgumentException must be present", ("java.lang.IllegalArgumentException: ELYTOOL00007: Invalid \"iteration\" value. Must be an integer between 1 and 2147483647, inclusive").equals(retValLines[0])); assertTrue("Message about invalid iteration parameter must be present", ("Invalid \"iteration\" parameter. Default value \"" + defaultIteration + "\" will be used.").equals(retValLines[1])); @@ -158,7 +159,7 @@ public void testIterationAsNegativeValue() { String[] args = { "--secret", secret, "--salt", salt, "--iteration", "-123" }; String retVal = executeCommandAndCheckStatusAndGetOutput(args); - String[] retValLines = retVal.split(System.getProperty("line.separator")); + String[] retValLines = retVal.split(LINE_SEPARATOR); assertTrue("IllegalArgumentException must be present", ("java.lang.IllegalArgumentException: ELYTOOL00007: Invalid \"iteration\" value. Must be an integer between 1 and 2147483647, inclusive").equals(retValLines[0])); assertTrue("Message about invalid iteration parameter must be present", ("Invalid \"iteration\" parameter. Default value \"" + defaultIteration + "\" will be used.").equals(retValLines[1]));