From 9f4d899d664d14f3bb203ec3e7e0282b33413bb1 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 6 Nov 2023 16:27:49 -0500 Subject: [PATCH 01/27] Adds java tool for installing demo configuration Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 703 ++++++++++++++++++ 1 file changed, 703 insertions(+) create mode 100644 src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java new file mode 100644 index 0000000000..28056352b7 --- /dev/null +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -0,0 +1,703 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.tools; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.PosixFilePermission; +import java.util.HashSet; +import java.util.Scanner; +import java.util.Set; + +public class InstallDemoConfiguration { + static boolean assumeyes = false; + static boolean initsecurity = false; + static boolean cluster_mode = false; + static boolean skip_updates = true; + static String BASE_DIR; + static String OPENSEARCH_CONF_FILE; + static String OPENSEARCH_BIN_DIR; + static String OPENSEARCH_PLUGINS_DIR; + static String OPENSEARCH_MODULES_DIR; + static String OPENSEARCH_LIB_PATH; + static String OPENSEARCH_INSTALL_TYPE; + static String OPENSEARCH_CONF_DIR; + static String OPENSEARCH_VERSION; + static String SECURITY_VERSION; + static String OS; + + private static final String FILE_EXTENSION = System.getProperty("os.name").toLowerCase().contains("win") ? ".bat" : ".sh"; + + private static final String SYSTEM_INDICES = ".plugins-ml-config, .plugins-ml-connector, .plugins-ml-model-group, .plugins-ml-model, " + + ".plugins-ml-task, .plugins-ml-conversation-meta, .plugins-ml-conversation-interactions, .opendistro-alerting-config, .opendistro-alerting-alert*, " + + ".opendistro-anomaly-results*, .opendistro-anomaly-detector*, .opendistro-anomaly-checkpoints, .opendistro-anomaly-detection-state, " + + ".opendistro-reports-*, .opensearch-notifications-*, .opensearch-notebooks, .opensearch-observability, .ql-datasources, " + + ".opendistro-asynchronous-search-response*, .replication-metadata-store, .opensearch-knn-models, .geospatial-ip2geo-data*"; + + public static void main(String[] args) { + printScriptHeaders(); + readArguments(args); + gatherUserInputs(); + initializeVariables(); + printVariables(); + checkIfSecurityPluginIsAlreadyConfigured(); + createDemoCertificates(); + writeSecurityConfigToOpenSearchYML(); + runSecurityAdminCommands(); + setAdminPassword(); + } + + private static void printScriptHeaders() { + System.out.println("**************************************************************************"); + System.out.println("** This tool will be deprecated in the next major release of OpenSearch **"); + System.out.println("** https://github.com/opensearch-project/security/issues/1755 **"); + System.out.println("**************************************************************************"); + System.out.println("\n\n"); + System.out.println("OpenSearch Security Demo Installer"); + System.out.println("** Warning: Do not use on production or public reachable systems **"); + } + + private static void readArguments(String[] args) { + for (String arg : args) { + switch (arg) { + case "-y": + assumeyes = true; + break; + case "-i": + initsecurity = true; + break; + case "-c": + cluster_mode = true; + break; + case "-s": + skip_updates = false; + break; + case "-h": + case "-?": + showHelp(); + return; + default: + System.out.println("Invalid option: " + arg); + } + } + } + + private static void showHelp() { + System.out.println("install_demo_configuration.sh [-y] [-i] [-c]"); + System.out.println(" -h show help"); + System.out.println(" -y confirm all installation dialogues automatically"); + System.out.println(" -i initialize Security plugin with default configuration (default is to ask if -y is not given)"); + System.out.println(" -c enable cluster mode by binding to all network interfaces (default is to ask if -y is not given)"); + System.out.println(" -s skip updates if config is already applied to opensearch.yml"); + } + + private static void gatherUserInputs() { + try (Scanner scanner = new Scanner(System.in)) { + if (!assumeyes) { + if (!confirmAction(scanner, "Install demo certificates?")) { + System.exit(0); + } + + if (!initsecurity) { + initsecurity = confirmAction(scanner, "Initialize Security Modules?"); + } + + if (!cluster_mode) { + System.out.println("Cluster mode requires maybe additional setup of:"); + System.out.println(" - Virtual memory (vm.max_map_count)\n"); + cluster_mode = confirmAction(scanner, "Enable cluster mode?"); + } + } + } + } + + private static boolean confirmAction(Scanner scanner, String message) { + System.out.print(message + " [y/N] "); + String response = scanner.nextLine(); + return response.equalsIgnoreCase("yes") || response.equalsIgnoreCase("y"); + } + + private static void initializeVariables() { + setBaseDir(); + setOpenSearchVariables(); + setSecurityVariables(); + } + + private static void setBaseDir() { + String DIR = System.getProperty("user.dir"); + BASE_DIR = DIR + File.separator + ".." + File.separator + ".." + File.separator; + + if (new File(BASE_DIR).isDirectory()) { + String baseDir = System.getProperty("user.dir"); + System.setProperty("user.dir", BASE_DIR); + BASE_DIR = System.getProperty("user.dir"); + System.setProperty("user.dir", baseDir); + System.out.println("Basedir: " + BASE_DIR); + } else { + System.out.println("DEBUG: basedir does not exist"); + } + } + + private static void setOpenSearchVariables() { + OPENSEARCH_CONF_FILE = BASE_DIR + "config" + File.separator + "opensearch.yml"; + OPENSEARCH_BIN_DIR = BASE_DIR + "bin" + File.separator; + OPENSEARCH_PLUGINS_DIR = BASE_DIR + "plugins" + File.separator; + OPENSEARCH_MODULES_DIR = BASE_DIR + "modules" + File.separator; + OPENSEARCH_LIB_PATH = BASE_DIR + "lib" + File.separator; + OPENSEARCH_INSTALL_TYPE = determineInstallType(); + + if (!(new File(OPENSEARCH_CONF_FILE).exists())) { + System.out.println("Unable to determine OpenSearch config directory. Quit."); + System.exit(-1); + } + + if (!(new File(OPENSEARCH_BIN_DIR).exists())) { + System.out.println("Unable to determine OpenSearch bin directory. Quit."); + System.exit(-1); + } + + if (!(new File(OPENSEARCH_PLUGINS_DIR).exists())) { + System.out.println("Unable to determine OpenSearch plugins directory. Quit."); + System.exit(-1); + } + + if (!(new File(OPENSEARCH_MODULES_DIR).exists())) { + System.out.println("Unable to determine OpenSearch modules directory. Quit."); + // System.exit(-1); + } + + if (!(new File(OPENSEARCH_LIB_PATH).exists())) { + System.out.println("Unable to determine OpenSearch lib directory. Quit."); + System.exit(-1); + } + + OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_FILE).getParent(); + OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_DIR).getAbsolutePath() + File.separator; + } + + private static String determineInstallType() { + String os = System.getProperty("os.name").toLowerCase(); + // windows (.bat execution) + if (os.contains("win")) { + return ".zip"; + } + + // other OS (.sh execution) + if (new File("/usr/share/opensearch").equals(new File(BASE_DIR))) { + OPENSEARCH_CONF_FILE = "/usr/share/opensearch/config/opensearch.yml"; + if (!new File(OPENSEARCH_CONF_FILE).exists()) { + OPENSEARCH_CONF_FILE = "/etc/opensearch/opensearch.yml"; + } + return "rpm/deb"; + } + return ".tar.gz"; + } + + private static void setSecurityVariables() { + if (!(new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").exists())) { + System.out.println("OpenSearch Security plugin not installed. Quit."); + System.exit(-1); + } + + // Extract OpenSearch version and Security version + File[] opensearchLibFiles = new File(OPENSEARCH_LIB_PATH).listFiles( + pathname -> pathname.getName().startsWith("opensearch-") && pathname.getName().endsWith(".jar") + ); + + if (opensearchLibFiles != null && opensearchLibFiles.length > 0) { + OPENSEARCH_VERSION = opensearchLibFiles[0].getName().replaceAll("opensearch-(.*).jar", "$1"); + } + + File[] securityFiles = new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").listFiles( + pathname -> pathname.getName().startsWith("opensearch-security-") && pathname.getName().endsWith(".jar") + ); + + if (securityFiles != null && securityFiles.length > 0) { + SECURITY_VERSION = securityFiles[0].getName().replaceAll("opensearch-security-(.*).jar", "$1"); + } + + // Detect OS information + String osName = System.getProperty("os.name"); + String osVersion = System.getProperty("os.version"); + String osArch = System.getProperty("os.arch"); + OS = osName + " " + osVersion + " " + osArch; + } + + private static void printVariables() { + System.out.println("OpenSearch install type: " + OPENSEARCH_INSTALL_TYPE + " on " + OS); + System.out.println("OpenSearch config dir: " + OPENSEARCH_CONF_DIR); + System.out.println("OpenSearch config file: " + OPENSEARCH_CONF_FILE); + System.out.println("OpenSearch bin dir: " + OPENSEARCH_BIN_DIR); + System.out.println("OpenSearch plugins dir: " + OPENSEARCH_PLUGINS_DIR); + System.out.println("OpenSearch lib dir: " + OPENSEARCH_LIB_PATH); + System.out.println("Detected OpenSearch Version: " + OPENSEARCH_VERSION); + System.out.println("Detected OpenSearch Security Version: " + SECURITY_VERSION); + } + + private static void checkIfSecurityPluginIsAlreadyConfigured() { + // Check if the configuration file contains the 'plugins.security' string + if (OPENSEARCH_CONF_FILE != null && new File(OPENSEARCH_CONF_FILE).exists()) { + try (BufferedReader br = new BufferedReader(new FileReader(OPENSEARCH_CONF_FILE))) { + String line; + while ((line = br.readLine()) != null) { + if (line.toLowerCase().contains("plugins.security")) { + System.out.println(OPENSEARCH_CONF_FILE + " seems to be already configured for Security. Quit."); + System.exit(skip_updates ? 1 : 0); + } + } + } catch (IOException e) {} + } else { + System.out.println("OpenSearch configuration file does not exist. Quit."); + System.exit(-1); + } + // Reset the exit value + System.exit(0); + } + + public static void createDemoCertificates() { + for (DemoCertificate cert : DemoCertificate.values()) { + String filePath = OPENSEARCH_CONF_DIR + File.separator + cert.getFileName(); + try { + FileWriter fileWriter = new FileWriter(filePath); + fileWriter.write(cert.getContent()); + fileWriter.close(); + setFilePermissions(filePath); + } catch (IOException e) { + System.err.println("Error writing certificate to file: " + cert.getFileName()); + + } + } + } + + private static void setFilePermissions(String filePath) { + try { + File file = new File(filePath); + if (!file.setReadable(true, false) || !file.setWritable(false, false) || !file.setExecutable(false, false)) { + throw new IOException("Failed to set file permissions for: " + filePath); + } + } catch (IOException e) { + System.err.println("Error setting file permissions for: " + filePath); + + } + } + + private static void writeSecurityConfigToOpenSearchYML() { + String securityConfig = buildSecurityConfigString(); + + try (FileWriter writer = new FileWriter(OPENSEARCH_CONF_FILE, true)) { + writer.write(securityConfig); + } catch (IOException e) {} + } + + private static String buildSecurityConfigString() { + StringBuilder securityConfigLines = new StringBuilder(); + + securityConfigLines.append("\n") + .append("######## Start OpenSearch Security Demo Configuration ########\n") + .append("# WARNING: revise all the lines below before you go into production\n") + .append("plugins.security.ssl.transport.pemcert_filepath: esnode.pem\n") + .append("plugins.security.ssl.transport.pemkey_filepath: esnode-key.pem\n") + .append("plugins.security.ssl.transport.pemtrustedcas_filepath: root-ca.pem\n") + .append("plugins.security.ssl.transport.enforce_hostname_verification: false\n") + .append("plugins.security.ssl.http.enabled: true\n") + .append("plugins.security.ssl.http.pemcert_filepath: esnode.pem\n") + .append("plugins.security.ssl.http.pemkey_filepath: esnode-key.pem\n") + .append("plugins.security.ssl.http.pemtrustedcas_filepath: root-ca.pem\n") + .append("plugins.security.allow_unsafe_democertificates: true\n"); + + if (initsecurity) { + securityConfigLines.append("plugins.security.allow_default_init_securityindex: true\n"); + } + + securityConfigLines.append("plugins.security.authcz.admin_dn:\n - CN=kirk,OU=client,O=client,L=test, C=de\n\n"); + + securityConfigLines.append("plugins.security.system_indices.enabled: true\n" + "plugins.security.system_indices.indices: [") + .append(SYSTEM_INDICES) + .append("]\n"); + + if (!isNetworkHostAlreadyPresent(OPENSEARCH_CONF_FILE)) { + if (cluster_mode) { + securityConfigLines.append("network.host: 0.0.0.0\n"); + securityConfigLines.append("node.name: smoketestnode\n"); + securityConfigLines.append("cluster.initial_cluster_manager_nodes: smoketestnode\n"); + } + } + + if (!isNodeMaxLocalStorageNodesAlreadyPresent(OPENSEARCH_CONF_FILE)) { + securityConfigLines.append("node.max_local_storage_nodes: 3\n"); + } + + securityConfigLines.append("######## End OpenSearch Security Demo Configuration ########\n"); + + return securityConfigLines.toString(); + } + + private static boolean isNetworkHostAlreadyPresent(String filePath) { + try { + String searchString = "^network.host"; + return isStringAlreadyPresentInFile(filePath, searchString); + } catch (IOException e) { + return false; + } + } + + private static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) { + try { + String searchString = "^node.max_local_storage_nodes"; + return isStringAlreadyPresentInFile(filePath, searchString); + } catch (IOException e) { + return false; + } + } + + private static boolean isStringAlreadyPresentInFile(String filePath, String searchString) throws IOException { + try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + String line; + while ((line = reader.readLine()) != null) { + if (line.matches(searchString)) { + return true; + } + } + } + return false; + } + + private static void runSecurityAdminCommands() { + try { + String securityAdminScriptPath = OPENSEARCH_PLUGINS_DIR + + "opensearch-security" + + File.separator + + "tools" + + File.separator + + "securityadmin" + + FILE_EXTENSION; + String securityAdminDemoScriptPath = OPENSEARCH_CONF_DIR + "securityadmin_demo" + FILE_EXTENSION; + + createSecurityAdminDemoScript(securityAdminScriptPath, securityAdminDemoScriptPath); + + // Make securityadmin_demo script executable + Path file = Paths.get(securityAdminDemoScriptPath); + Set perms = new HashSet<>(); + // Add the execute permission for owner, group, and others + perms.add(PosixFilePermission.OWNER_EXECUTE); + perms.add(PosixFilePermission.GROUP_EXECUTE); + perms.add(PosixFilePermission.OTHERS_EXECUTE); + Files.setPosixFilePermissions(file, perms); + + // Read the last line of the security-admin script + String lastLine = ""; + try (BufferedReader reader = new BufferedReader(new FileReader(securityAdminDemoScriptPath))) { + String currentLine; + while ((currentLine = reader.readLine()) != null) { + lastLine = currentLine; + } + } + + if (!initsecurity) { + System.out.println("### After the whole cluster is up execute: "); + System.out.println(lastLine); + System.out.println("### or run ." + File.separator + "securityadmin_demo" + FILE_EXTENSION); + System.out.println("### After that you can also use the Security Plugin ConfigurationGUI"); + } else { + System.out.println("### OpenSearch Security will be automatically initialized."); + System.out.println("### If you like to change the runtime configuration "); + System.out.println( + "### change the files in .." + + File.separator + + ".." + + File.separator + + ".." + + File.separator + + "config" + + File.separator + + "opensearch-security and execute: " + ); + System.out.println(lastLine); + System.out.println("### or run ." + File.separator + "securityadmin_demo" + FILE_EXTENSION); + System.out.println("### To use the Security Plugin ConfigurationGUI"); + } + + System.out.println("### To access your secured cluster open https://: and log in with admin/admin."); + System.out.println("### (Ignore the SSL certificate warning because we installed self-signed demo certificates)"); + + } catch (IOException e) {} + } + + private static void createSecurityAdminDemoScript(String securityAdminScriptPath, String securityAdminDemoScriptPath) + throws IOException { + String[] securityAdminCommands; + + String securityAdminExecutionPath = securityAdminScriptPath + + "\" -cd \"" + + OPENSEARCH_CONF_DIR + + "opensearch-security\" -icl -key \"" + + OPENSEARCH_CONF_DIR + + DemoCertificate.ADMIN_CERT_KEY.getFileName() + + "\" -cert \"" + + OPENSEARCH_CONF_DIR + + DemoCertificate.ADMIN_CERT.getFileName() + + "\" -cacert \"" + + OPENSEARCH_CONF_DIR + + DemoCertificate.ROOT_CA.getFileName() + + "\" -nhnv"; + + if (System.getProperty("os.name").toLowerCase().contains("win")) { + securityAdminCommands = new String[] { "@echo off", "call \"" + securityAdminExecutionPath }; + } else { + securityAdminCommands = new String[] { "#!/bin/bash", "sudo" + " \"" + securityAdminExecutionPath }; + } + + // Write securityadmin_demo script + FileWriter writer = new FileWriter(securityAdminDemoScriptPath + FILE_EXTENSION); + for (String command : securityAdminCommands) { + writer.write(command + "\n"); + } + writer.close(); + } + + private static void setAdminPassword() { + String ADMIN_PASSWORD = ""; + String initialAdminPassword = System.getenv("initialAdminPassword"); + String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; + String INTERNAL_USERS_FILE_PATH = OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; + try { + if (initialAdminPassword != null && !initialAdminPassword.isEmpty()) { + ADMIN_PASSWORD = initialAdminPassword; + } else { + File adminPasswordFile = new File(ADMIN_PASSWORD_FILE_PATH); + if (adminPasswordFile.exists() && adminPasswordFile.length() > 0) { + try (BufferedReader br = new BufferedReader(new FileReader(ADMIN_PASSWORD_FILE_PATH))) { + ADMIN_PASSWORD = br.readLine(); + } + } else { + System.out.println( + "Unable to find the admin password for the cluster. Please set initialAdminPassword environment variable or create a file " + + ADMIN_PASSWORD_FILE_PATH + + " with a single line that contains the password." + ); + System.exit(1); + } + } + System.out.println(" ***************************************************"); + System.out.println(" *** ADMIN PASSWORD SET TO: " + ADMIN_PASSWORD + " ***"); + System.out.println(" ***************************************************"); + + String hashedAdminPassword = Hasher.hash(ADMIN_PASSWORD.toCharArray()); + + if (hashedAdminPassword.isEmpty()) { + System.out.println("Hash the admin password failure, see console for details"); + System.exit(1); + } + + File tempFile = new File(INTERNAL_USERS_FILE_PATH + ".tmp"); + BufferedReader reader = new BufferedReader(new FileReader(INTERNAL_USERS_FILE_PATH)); + FileWriter writer = new FileWriter(tempFile); + + String line; + while ((line = reader.readLine()) != null) { + if (line.matches(" *hash: *\"\\$2a\\$12\\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"")) { + line = line.replace( + "\"$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"", + "\"" + hashedAdminPassword + "\"" + ); + } + writer.write(line + System.lineSeparator()); + } + + reader.close(); + writer.close(); + + if (!tempFile.renameTo(new File(INTERNAL_USERS_FILE_PATH))) { + throw new IOException("Unable to update the internal users file with the hashed password."); + } + + } catch (IOException e) { + System.exit(1); + } + } +} + +enum DemoCertificate { + ADMIN_CERT( + "kirk.pem", + "-----BEGIN CERTIFICATE-----\n" + + "MIIEmDCCA4CgAwIBAgIUZjrlDPP8azRDPZchA/XEsx0X2iYwDQYJKoZIhvcNAQEL\n" + + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt\n" + + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl\n" + + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v\n" + + "dCBDQTAeFw0yMzA4MjkyMDA2MzdaFw0zMzA4MjYyMDA2MzdaME0xCzAJBgNVBAYT\n" + + "AmRlMQ0wCwYDVQQHDAR0Z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dDXzizx/JdmueT0nG9hOixLqzfoC9p\n" + + "fAhZxM62RgtyZoaczQN82k1/geMSwRpEndFe3OH7arkS/HSbIFxQhAIy229eWe5d\n" + + "1bUzP59iu7f3r567I4ob8Vy7PP+Ov35p7Vv4oDHHwgsdRzX6pvL6mmwVrQ3BfVec\n" + + "h9Dqprr+ukYmjho76g6k5cQuRaB6MxqldzUg+2E7IHQP8MCF+co51uZq2nl33mtp\n" + + "RGr6JbdHXc96zsLTL3saJQ8AWEfu1gbTVrwyRA==\n" + + "-----END CERTIFICATE-----" + ), + ADMIN_CERT_KEY( + "kirk-key.pem", + "-----BEGIN PRIVATE KEY-----\n" + + "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCVXDgEJQorgfXp\n" + + "gpY0TgF55bD2xuzxN5Dc9rDfgWxrsOvOloMpd7k6FR71bKWjJi1KptSmM/cDElky\n" + + "AWYKSfYWGiGxsQ+EQW+6kwCfEOHXQldn+0+JcWqP+osSPjtJfwRvRN5kRqP69MPo\n" + + "7U0N2kdqenqMWjmG1chDGLRSOEGU5HIBiDxsZtOcvMaJ8b1eaW0lvS+6gFQ80AvB\n" + + "GBkDDCOHHLtDXBylrZk2CQP8AzxNicIZ4B8G3CG3OHA8+nBtEtxZoIihrrkqlMt+\n" + + "b/5N8u8zB0Encew0kdrc4R/2wS//ahr6U+9Siq8T7WsUtGwKj3BJClg6OyDJRhlu\n" + + "y2gFnxoPAgMBAAECggEAP5TOycDkx+megAWVoHV2fmgvgZXkBrlzQwUG/VZQi7V4\n" + + "ZGzBMBVltdqI38wc5MtbK3TCgHANnnKgor9iq02Z4wXDwytPIiti/ycV9CDRKvv0\n" + + "TnD2hllQFjN/IUh5n4thHWbRTxmdM7cfcNgX3aZGkYbLBVVhOMtn4VwyYu/Mxy8j\n" + + "xClZT2xKOHkxqwmWPmdDTbAeZIbSv7RkIGfrKuQyUGUaWhrPslvYzFkYZ0umaDgQ\n" + + "OAthZew5Bz3OfUGOMPLH61SVPuJZh9zN1hTWOvT65WFWfsPd2yStI+WD/5PU1Doo\n" + + "1RyeHJO7s3ug8JPbtNJmaJwHe9nXBb/HXFdqb976yQKBgQDNYhpu+MYSYupaYqjs\n" + + "9YFmHQNKpNZqgZ4ceRFZ6cMJoqpI5dpEMqToFH7tpor72Lturct2U9nc2WR0HeEs\n" + + "/6tiptyMPTFEiMFb1opQlXF2ae7LeJllntDGN0Q6vxKnQV+7VMcXA0Y8F7tvGDy3\n" + + "qJu5lfvB1mNM2I6y/eMxjBuQhwKBgQC6K41DXMFro0UnoO879pOQYMydCErJRmjG\n" + + "/tZSy3Wj4KA/QJsDSViwGfvdPuHZRaG9WtxdL6kn0w1exM9Rb0bBKl36lvi7o7xv\n" + + "M+Lw9eyXMkww8/F5d7YYH77gIhGo+RITkKI3+5BxeBaUnrGvmHrpmpgRXWmINqr0\n" + + "0jsnN3u0OQKBgCf45vIgItSjQb8zonLz2SpZjTFy4XQ7I92gxnq8X0Q5z3B+o7tQ\n" + + "K/4rNwTju/sGFHyXAJlX+nfcK4vZ4OBUJjP+C8CTjEotX4yTNbo3S6zjMyGQqDI5\n" + + "9aIOUY4pb+TzeUFJX7If5gR+DfGyQubvvtcg1K3GHu9u2l8FwLj87sRzAoGAflQF\n" + + "RHuRiG+/AngTPnZAhc0Zq0kwLkpH2Rid6IrFZhGLy8AUL/O6aa0IGoaMDLpSWUJp\n" + + "nBY2S57MSM11/MVslrEgGmYNnI4r1K25xlaqV6K6ztEJv6n69327MS4NG8L/gCU5\n" + + "3pEm38hkUi8pVYU7in7rx4TCkrq94OkzWJYurAkCgYATQCL/rJLQAlJIGulp8s6h\n" + + "mQGwy8vIqMjAdHGLrCS35sVYBXG13knS52LJHvbVee39AbD5/LlWvjJGlQMzCLrw\n" + + "F7oILW5kXxhb8S73GWcuMbuQMFVHFONbZAZgn+C9FW4l7XyRdkrbR1MRZ2km8YMs\n" + + "/AHmo368d4PSNRMMzLHw8Q==\n" + + "-----END PRIVATE KEY-----" + ), + NODE_CERT( + "esnode.pem", + "-----BEGIN CERTIFICATE-----\n" + + "MIIEPDCCAySgAwIBAgIUZjrlDPP8azRDPZchA/XEsx0X2iIwDQYJKoZIhvcNAQEL\n" + + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt\n" + + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl\n" + + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v\n" + + "dCBDQTAeFw0yMzA4MjkwNDIzMTJaFw0zMzA4MjYwNDIzMTJaMFcxCzAJBgNVBAYT\n" + + "AmRlMQ0wCwYDVQQHDAR0ZXN0MQ0wCwYDVQQKDARub2RlMQ0wCwYDVQQLDARub2Rl\n" + + "MRswGQYDVQQDDBJub2RlLTAuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUA\n" + + "A4IBDwAwggEKAoIBAQCm93kXteDQHMAvbUPNPW5pyRHKDD42XGWSgq0k1D29C/Ud\n" + + "yL21HLzTJa49ZU2ldIkSKs9JqbkHdyK0o8MO6L8dotLoYbxDWbJFW8bp1w6tDTU0\n" + + "HGkn47XVu3EwbfrTENg3jFu+Oem6a/501SzITzJWtS0cn2dIFOBimTVpT/4Zv5qr\n" + + "XA6Cp4biOmoTYWhi/qQl8d0IaADiqoZ1MvZbZ6x76qTrRAbg+UWkpTEXoH1xTc8n\n" + + "dibR7+HP6OTqCKvo1NhE8uP4pY+fWd6b6l+KLo3IKpfTbAIJXIO+M67FLtWKtttD\n" + + "ao94B069skzKk6FPgW/OZh6PRCD0oxOavV+ld2SjAgMBAAGjgcYwgcMwRwYDVR0R\n" + + "BEAwPogFKgMEBQWCEm5vZGUtMC5leGFtcGxlLmNvbYIJbG9jYWxob3N0hxAAAAAA\n" + + "AAAAAAAAAAAAAAABhwR/AAABMAsGA1UdDwQEAwIF4DAdBgNVHSUEFjAUBggrBgEF\n" + + "BQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQU0/qDQaY10jIo\n" + + "wCjLUpz/HfQXyt8wHwYDVR0jBBgwFoAUF4ffoFrrZhKn1dD4uhJFPLcrAJwwDQYJ\n" + + "KoZIhvcNAQELBQADggEBAD2hkndVih6TWxoe/oOW0i2Bq7ScNO/n7/yHWL04HJmR\n" + + "MaHv/Xjc8zLFLgHuHaRvC02ikWIJyQf5xJt0Oqu2GVbqXH9PBGKuEP2kCsRRyU27\n" + + "zTclAzfQhqmKBTYQ/3lJ3GhRQvXIdYTe+t4aq78TCawp1nSN+vdH/1geG6QjMn5N\n" + + "1FU8tovDd4x8Ib/0dv8RJx+n9gytI8n/giIaDCEbfLLpe4EkV5e5UNpOnRgJjjuy\n" + + "vtZutc81TQnzBtkS9XuulovDE0qI+jQrKkKu8xgGLhgH0zxnPkKtUg2I3Aq6zl1L\n" + + "zYkEOUF8Y25J6WeY88Yfnc0iigI+Pnz5NK8R9GL7TYo=\n" + + "-----END CERTIFICATE-----" + ), + NODE_KEY( + "esnode-key.pem", + "-----BEGIN PRIVATE KEY-----\n" + + "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCm93kXteDQHMAv\n" + + "bUPNPW5pyRHKDD42XGWSgq0k1D29C/UdyL21HLzTJa49ZU2ldIkSKs9JqbkHdyK0\n" + + "o8MO6L8dotLoYbxDWbJFW8bp1w6tDTU0HGkn47XVu3EwbfrTENg3jFu+Oem6a/50\n" + + "1SzITzJWtS0cn2dIFOBimTVpT/4Zv5qrXA6Cp4biOmoTYWhi/qQl8d0IaADiqoZ1\n" + + "MvZbZ6x76qTrRAbg+UWkpTEXoH1xTc8ndibR7+HP6OTqCKvo1NhE8uP4pY+fWd6b\n" + + "6l+KLo3IKpfTbAIJXIO+M67FLtWKtttDao94B069skzKk6FPgW/OZh6PRCD0oxOa\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VO9U8hQPyiz9f7F+fu0LHZs6f7hyhYXlbe3XFxeop3f\n" + + "5dTKdWgXuTTRF2L9dABkA2deS9mutRKwezWBMQk5AoGBALPtX0FrT1zIosibmlud\n" + + "tu49A/0KZu4PBjrFMYTSEWGNJez3Fb2VsJwylVl6HivwbP61FhlYfyksCzQQFU71\n" + + "+x7Nmybp7PmpEBECr3deoZKQ/acNHn0iwb0It+YqV5+TquQebqgwK6WCLsMuiYKT\n" + + "bg/ch9Rhxbq22yrVgWHh6epp\n" + + "-----END PRIVATE KEY-----" + ), + ROOT_CA( + "root-ca.pem", + "-----BEGIN CERTIFICATE-----\n" + + "MIIExjCCA66gAwIBAgIUd+SvPvzan5P2TQbEZ4zj4Gt6FYowDQYJKoZIhvcNAQEL\n" + + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt\n" + + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl\n" + + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v\n" + + "dCBDQTAeFw0yMzA4MjkwNDIwMDNaFw0yMzA5MjgwNDIwMDNaMIGPMRMwEQYKCZIm\n" + + "iZPyLGQBGRYDY29tMRcwFQYKCZImiZPyLGQBGRYHZXhhbXBsZTEZMBcGA1UECgwQ\n" + + "RXhhbXBsZSBDb20gSW5jLjEhMB8GA1UECwwYRXhhbXBsZSBDb20gSW5jLiBSb290\n" + + "IENBMSEwHwYDVQQDDBhFeGFtcGxlIENvbSBJbmMuIFJvb3QgQ0EwggEiMA0GCSqG\n" + + "SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDEPyN7J9VGPyJcQmCBl5TGwfSzvVdWwoQU\n" + + "j9aEsdfFJ6pBCDQSsj8Lv4RqL0dZra7h7SpZLLX/YZcnjikrYC+rP5OwsI9xEE/4\n" + + "U98CsTBPhIMgq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+g/Y=\n" + + "-----END CERTIFICATE-----" + ); + + private final String fileName; + private final String content; + + DemoCertificate(String fileName, String content) { + this.fileName = fileName; + this.content = content; + } + + public String getFileName() { + return fileName; + } + + public String getContent() { + return content; + } +} From b89a43de4aba29c1dc254bd29a2a9514c7694e40 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 6 Nov 2023 16:27:56 -0500 Subject: [PATCH 02/27] Adds temp scripts to test the new java tool Signed-off-by: Darshit Chanpura --- ...tall_demo_configuration_with_java_tool.bat | 14 +++++++++ ...stall_demo_configuration_with_java_tool.sh | 30 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 tools/install_demo_configuration_with_java_tool.bat create mode 100755 tools/install_demo_configuration_with_java_tool.sh diff --git a/tools/install_demo_configuration_with_java_tool.bat b/tools/install_demo_configuration_with_java_tool.bat new file mode 100644 index 0000000000..b82cffcd4f --- /dev/null +++ b/tools/install_demo_configuration_with_java_tool.bat @@ -0,0 +1,14 @@ +@echo off +set DIR=%~dp0 + +if defined OPENSEARCH_JAVA_HOME ( + set BIN_PATH="%OPENSEARCH_JAVA_HOME%\bin\java.exe" +) else if defined JAVA_HOME ( + set BIN_PATH="%JAVA_HOME%\bin\java.exe" +) else ( + echo Unable to find java runtime + echo OPENSEARCH_JAVA_HOME or JAVA_HOME must be defined + exit /b 1 +) + +%BIN_PATH% -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.InstallDemoConfiguration %* 2> nul \ No newline at end of file diff --git a/tools/install_demo_configuration_with_java_tool.sh b/tools/install_demo_configuration_with_java_tool.sh new file mode 100755 index 0000000000..e8aa565eba --- /dev/null +++ b/tools/install_demo_configuration_with_java_tool.sh @@ -0,0 +1,30 @@ +#!/bin/bash +#install_demo_configuration.sh [-y] + +SCRIPT_PATH="${BASH_SOURCE[0]}" +if ! [ -x "$(command -v realpath)" ]; then + if [ -L "$SCRIPT_PATH" ]; then + + [ -x "$(command -v readlink)" ] || { echo "Not able to resolve symlink. Install realpath or readlink.";exit 1; } + + # try readlink (-f not needed because we know its a symlink) + DIR="$( cd "$( dirname $(readlink "$SCRIPT_PATH") )" && pwd -P)" + else + DIR="$( cd "$( dirname "$SCRIPT_PATH" )" && pwd -P)" + fi +else + DIR="$( cd "$( dirname "$(realpath "$SCRIPT_PATH")" )" && pwd -P)" +fi + +BIN_PATH="java" + +# now set the path to java: first OPENSEARCH_JAVA_HOME, then JAVA_HOME +if [ ! -z "$OPENSEARCH_JAVA_HOME" ]; then + BIN_PATH="$OPENSEARCH_JAVA_HOME/bin/java" +elif [ ! -z "$JAVA_HOME" ]; then + BIN_PATH="$JAVA_HOME/bin/java" +else + echo "WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use $(which $BIN_PATH)" +fi + +"$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.InstallDemoConfiguration "$@" 2>/dev/null From f38aeff07d0fd2ecee80c4ce0b8cccc68e145092 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 6 Nov 2023 17:55:01 -0500 Subject: [PATCH 03/27] Successful testing on local environment in MacOS Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 160 +++++++++--------- 1 file changed, 82 insertions(+), 78 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 28056352b7..c3f5874391 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -29,6 +29,7 @@ public class InstallDemoConfiguration { static boolean initsecurity = false; static boolean cluster_mode = false; static boolean skip_updates = true; + static String SCRIPT_DIR; static String BASE_DIR; static String OPENSEARCH_CONF_FILE; static String OPENSEARCH_BIN_DIR; @@ -56,10 +57,10 @@ public static void main(String[] args) { initializeVariables(); printVariables(); checkIfSecurityPluginIsAlreadyConfigured(); + setAdminPassword(); createDemoCertificates(); writeSecurityConfigToOpenSearchYML(); runSecurityAdminCommands(); - setAdminPassword(); } private static void printScriptHeaders() { @@ -67,12 +68,15 @@ private static void printScriptHeaders() { System.out.println("** This tool will be deprecated in the next major release of OpenSearch **"); System.out.println("** https://github.com/opensearch-project/security/issues/1755 **"); System.out.println("**************************************************************************"); - System.out.println("\n\n"); + System.out.println("\n"); System.out.println("OpenSearch Security Demo Installer"); System.out.println("** Warning: Do not use on production or public reachable systems **"); } private static void readArguments(String[] args) { + // set script execution dir + SCRIPT_DIR = args[0]; + for (String arg : args) { switch (arg) { case "-y": @@ -139,18 +143,15 @@ private static void initializeVariables() { } private static void setBaseDir() { - String DIR = System.getProperty("user.dir"); - BASE_DIR = DIR + File.separator + ".." + File.separator + ".." + File.separator; - - if (new File(BASE_DIR).isDirectory()) { - String baseDir = System.getProperty("user.dir"); - System.setProperty("user.dir", BASE_DIR); - BASE_DIR = System.getProperty("user.dir"); - System.setProperty("user.dir", baseDir); - System.out.println("Basedir: " + BASE_DIR); - } else { + File baseDirFile = new File(SCRIPT_DIR).getParentFile().getParentFile().getParentFile(); + BASE_DIR = baseDirFile != null ? baseDirFile.getAbsolutePath() : null; + + if (BASE_DIR == null || !new File(BASE_DIR).isDirectory()) { System.out.println("DEBUG: basedir does not exist"); + System.exit(-1); } + + BASE_DIR += File.separator; } private static void setOpenSearchVariables() { @@ -265,8 +266,67 @@ private static void checkIfSecurityPluginIsAlreadyConfigured() { System.out.println("OpenSearch configuration file does not exist. Quit."); System.exit(-1); } - // Reset the exit value - System.exit(0); + } + + private static void setAdminPassword() { + String ADMIN_PASSWORD = ""; + String initialAdminPassword = System.getenv("initialAdminPassword"); + String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; + String INTERNAL_USERS_FILE_PATH = OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; + try { + if (initialAdminPassword != null && !initialAdminPassword.isEmpty()) { + ADMIN_PASSWORD = initialAdminPassword; + } else { + File adminPasswordFile = new File(ADMIN_PASSWORD_FILE_PATH); + if (adminPasswordFile.exists() && adminPasswordFile.length() > 0) { + try (BufferedReader br = new BufferedReader(new FileReader(ADMIN_PASSWORD_FILE_PATH))) { + ADMIN_PASSWORD = br.readLine(); + } + } else { + System.out.println( + "Unable to find the admin password for the cluster. Please set initialAdminPassword environment variable or create a file " + + ADMIN_PASSWORD_FILE_PATH + + " with a single line that contains the password." + ); + System.exit(-1); + } + } + System.out.println(" ***************************************************"); + System.out.println(" *** ADMIN PASSWORD SET TO: " + ADMIN_PASSWORD + " ***"); + System.out.println(" ***************************************************"); + + String hashedAdminPassword = Hasher.hash(ADMIN_PASSWORD.toCharArray()); + + if (hashedAdminPassword.isEmpty()) { + System.out.println("Hash the admin password failure, see console for details"); + System.exit(-1); + } + + File tempFile = new File(INTERNAL_USERS_FILE_PATH + ".tmp"); + BufferedReader reader = new BufferedReader(new FileReader(INTERNAL_USERS_FILE_PATH)); + FileWriter writer = new FileWriter(tempFile); + + String line; + while ((line = reader.readLine()) != null) { + if (line.matches(" *hash: *\"\\$2a\\$12\\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"")) { + line = line.replace( + "\"$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"", + "\"" + hashedAdminPassword + "\"" + ); + } + writer.write(line + System.lineSeparator()); + } + + reader.close(); + writer.close(); + + if (!tempFile.renameTo(new File(INTERNAL_USERS_FILE_PATH))) { + throw new IOException("Unable to update the internal users file with the hashed password."); + } + + } catch (IOException e) { + System.exit(-1); + } } public static void createDemoCertificates() { @@ -279,7 +339,6 @@ public static void createDemoCertificates() { setFilePermissions(filePath); } catch (IOException e) { System.err.println("Error writing certificate to file: " + cert.getFileName()); - } } } @@ -378,6 +437,9 @@ private static boolean isStringAlreadyPresentInFile(String filePath, String sear } private static void runSecurityAdminCommands() { + System.out.println("### Success"); + System.out.println("### Execute this script now on all your nodes and then start all nodes"); + try { String securityAdminScriptPath = OPENSEARCH_PLUGINS_DIR + "opensearch-security" @@ -394,6 +456,7 @@ private static void runSecurityAdminCommands() { Path file = Paths.get(securityAdminDemoScriptPath); Set perms = new HashSet<>(); // Add the execute permission for owner, group, and others + perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_EXECUTE); perms.add(PosixFilePermission.GROUP_EXECUTE); perms.add(PosixFilePermission.OTHERS_EXECUTE); @@ -435,7 +498,9 @@ private static void runSecurityAdminCommands() { System.out.println("### To access your secured cluster open https://: and log in with admin/admin."); System.out.println("### (Ignore the SSL certificate warning because we installed self-signed demo certificates)"); - } catch (IOException e) {} + } catch (Exception e) { + System.out.println(e.getMessage()); + } } private static void createSecurityAdminDemoScript(String securityAdminScriptPath, String securityAdminDemoScriptPath) @@ -463,73 +528,12 @@ private static void createSecurityAdminDemoScript(String securityAdminScriptPath } // Write securityadmin_demo script - FileWriter writer = new FileWriter(securityAdminDemoScriptPath + FILE_EXTENSION); + FileWriter writer = new FileWriter(securityAdminDemoScriptPath); for (String command : securityAdminCommands) { writer.write(command + "\n"); } writer.close(); } - - private static void setAdminPassword() { - String ADMIN_PASSWORD = ""; - String initialAdminPassword = System.getenv("initialAdminPassword"); - String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; - String INTERNAL_USERS_FILE_PATH = OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; - try { - if (initialAdminPassword != null && !initialAdminPassword.isEmpty()) { - ADMIN_PASSWORD = initialAdminPassword; - } else { - File adminPasswordFile = new File(ADMIN_PASSWORD_FILE_PATH); - if (adminPasswordFile.exists() && adminPasswordFile.length() > 0) { - try (BufferedReader br = new BufferedReader(new FileReader(ADMIN_PASSWORD_FILE_PATH))) { - ADMIN_PASSWORD = br.readLine(); - } - } else { - System.out.println( - "Unable to find the admin password for the cluster. Please set initialAdminPassword environment variable or create a file " - + ADMIN_PASSWORD_FILE_PATH - + " with a single line that contains the password." - ); - System.exit(1); - } - } - System.out.println(" ***************************************************"); - System.out.println(" *** ADMIN PASSWORD SET TO: " + ADMIN_PASSWORD + " ***"); - System.out.println(" ***************************************************"); - - String hashedAdminPassword = Hasher.hash(ADMIN_PASSWORD.toCharArray()); - - if (hashedAdminPassword.isEmpty()) { - System.out.println("Hash the admin password failure, see console for details"); - System.exit(1); - } - - File tempFile = new File(INTERNAL_USERS_FILE_PATH + ".tmp"); - BufferedReader reader = new BufferedReader(new FileReader(INTERNAL_USERS_FILE_PATH)); - FileWriter writer = new FileWriter(tempFile); - - String line; - while ((line = reader.readLine()) != null) { - if (line.matches(" *hash: *\"\\$2a\\$12\\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"")) { - line = line.replace( - "\"$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"", - "\"" + hashedAdminPassword + "\"" - ); - } - writer.write(line + System.lineSeparator()); - } - - reader.close(); - writer.close(); - - if (!tempFile.renameTo(new File(INTERNAL_USERS_FILE_PATH))) { - throw new IOException("Unable to update the internal users file with the hashed password."); - } - - } catch (IOException e) { - System.exit(1); - } - } } enum DemoCertificate { From dfcf950d53403c4f53e20c8265d8ba8cdf0a2d13 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 6 Nov 2023 17:55:37 -0500 Subject: [PATCH 04/27] Modifies test scripts to pass script dir path as an argument Signed-off-by: Darshit Chanpura --- tools/install_demo_configuration_with_java_tool.bat | 2 +- tools/install_demo_configuration_with_java_tool.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/install_demo_configuration_with_java_tool.bat b/tools/install_demo_configuration_with_java_tool.bat index b82cffcd4f..04bf80e3e4 100644 --- a/tools/install_demo_configuration_with_java_tool.bat +++ b/tools/install_demo_configuration_with_java_tool.bat @@ -11,4 +11,4 @@ if defined OPENSEARCH_JAVA_HOME ( exit /b 1 ) -%BIN_PATH% -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.InstallDemoConfiguration %* 2> nul \ No newline at end of file +%BIN_PATH% -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.InstallDemoConfiguration %DIR% %* 2> nul \ No newline at end of file diff --git a/tools/install_demo_configuration_with_java_tool.sh b/tools/install_demo_configuration_with_java_tool.sh index e8aa565eba..ccd59fe34a 100755 --- a/tools/install_demo_configuration_with_java_tool.sh +++ b/tools/install_demo_configuration_with_java_tool.sh @@ -27,4 +27,4 @@ else echo "WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use $(which $BIN_PATH)" fi -"$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.InstallDemoConfiguration "$@" 2>/dev/null +"$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.InstallDemoConfiguration "$DIR" "$@" 2>/dev/null From cf15bae84468877c870011260a801973497afb32 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Tue, 7 Nov 2023 14:39:59 -0500 Subject: [PATCH 05/27] Adds password generation and validation capability Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 41 +++++++++++++++---- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index c3f5874391..0a089bbe7e 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -11,6 +11,10 @@ package org.opensearch.security.tools; +import org.opensearch.common.settings.Settings; +import org.opensearch.security.dlic.rest.validation.PasswordValidator; +import org.opensearch.security.dlic.rest.validation.RequestContentValidator; + import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -24,6 +28,10 @@ import java.util.Scanner; import java.util.Set; +import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_MIN_LENGTH; +import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX; +import static org.opensearch.security.user.UserService.generatePassword; + public class InstallDemoConfiguration { static boolean assumeyes = false; static boolean initsecurity = false; @@ -274,6 +282,14 @@ private static void setAdminPassword() { String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; String INTERNAL_USERS_FILE_PATH = OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; try { + final PasswordValidator passwordValidator = PasswordValidator.of( + Settings.builder() + .put(SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX, "(?=.*[A-Z])(?=.*[^a-zA-Z\\\\d])(?=.*[0-9])(?=.*[a-z]).{8,}") + .put(SECURITY_RESTAPI_PASSWORD_MIN_LENGTH, 8) + .build() + ); + + // Read custom password if (initialAdminPassword != null && !initialAdminPassword.isEmpty()) { ADMIN_PASSWORD = initialAdminPassword; } else { @@ -282,15 +298,26 @@ private static void setAdminPassword() { try (BufferedReader br = new BufferedReader(new FileReader(ADMIN_PASSWORD_FILE_PATH))) { ADMIN_PASSWORD = br.readLine(); } - } else { - System.out.println( - "Unable to find the admin password for the cluster. Please set initialAdminPassword environment variable or create a file " - + ADMIN_PASSWORD_FILE_PATH - + " with a single line that contains the password." - ); - System.exit(-1); } } + + // Validate custom password + if (!ADMIN_PASSWORD.isEmpty() + && passwordValidator.validate("admin", ADMIN_PASSWORD) != RequestContentValidator.ValidationError.NONE) { + System.out.println("Password " + ADMIN_PASSWORD + " is weak. Please re-try with a stronger password."); + System.exit(-1); + } + + // if ADMIN_PASSWORD is still an empty string, it implies no custom password was provided. We proceed with generating a new one. + if (ADMIN_PASSWORD.isEmpty()) { + System.out.println("No custom admin password found. Generating a new password now."); + // generate a new random password + while (passwordValidator.validate("admin", ADMIN_PASSWORD) != RequestContentValidator.ValidationError.NONE) { + ADMIN_PASSWORD = generatePassword(); + } + } + + // print the password to the logs System.out.println(" ***************************************************"); System.out.println(" *** ADMIN PASSWORD SET TO: " + ADMIN_PASSWORD + " ***"); System.out.println(" ***************************************************"); From bbacf0e23919a3a79f4630fb49301b00af80d3ed Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Tue, 7 Nov 2023 14:42:21 -0500 Subject: [PATCH 06/27] Updates existing scripts to reflect changes to install demo configuration and removes temp scripts Signed-off-by: Darshit Chanpura --- tools/install_demo_configuration.bat | 416 +--------------- tools/install_demo_configuration.sh | 461 +----------------- ...tall_demo_configuration_with_java_tool.bat | 14 - ...stall_demo_configuration_with_java_tool.sh | 30 -- 4 files changed, 16 insertions(+), 905 deletions(-) delete mode 100644 tools/install_demo_configuration_with_java_tool.bat delete mode 100755 tools/install_demo_configuration_with_java_tool.sh diff --git a/tools/install_demo_configuration.bat b/tools/install_demo_configuration.bat index d9d30fea2b..7296a05a2e 100755 --- a/tools/install_demo_configuration.bat +++ b/tools/install_demo_configuration.bat @@ -1,414 +1,14 @@ @echo off -setlocal enableDelayedExpansion -set "SCRIPT_DIR=%~dp0" +set DIR=%~dp0 -echo ************************************************************************** -echo ** This tool will be deprecated in the next major release of OpenSearch ** -echo ** https://github.com/opensearch-project/security/issues/1755 ** -echo ************************************************************************** - -echo. -echo OpenSearch Security Demo Installer -echo ** Warning: Do not use on production or public reachable systems ** - -echo. - -set "assumeyes=0" -set "initsecurity=0" -set "cluster_mode=0" -set "skip_updates=-1" - -goto :GETOPTS - -:show_help -echo install_demo_configuration.bat [-y] [-i] [-c] -echo -h show help -echo -y confirm all installation dialogues automatically -echo -i initialize Security plugin with default configuration (default is to ask if -y is not given) -echo -c enable cluster mode by binding to all network interfaces (default is to ask if -y is not given) -echo -s skip updates if config is already applied to opensearch.yml -EXIT /B 0 - -:GETOPTS -if /I "%1" == "-h" call :show_help & exit /b 0 -if /I "%1" == "-y" set "assumeyes=1" -if /I "%1" == "-i" set "initsecurity=1" -if /I "%1" == "-c" set "cluster_mode=1" -if /I "%1" == "-s" set "skip_updates=0" -shift -if not "%1" == "" goto :GETOPTS - -if "%1" == "--" shift - -if %assumeyes% == 0 ( - set /p "response=Install demo certificates? [y/N] " - if /I "!response!" neq "Y" exit /b 0 -) - -if %initsecurity% == 0 ( - if %assumeyes% == 0 ( - set /p "response=Initialize Security Modules? [y/N] " - if /I "!response!" == "Y" (set "initsecurity=1") ELSE (set "initsecurity=0") - ) -) - -if %cluster_mode% == 0 ( - if %assumeyes% == 0 ( - echo Cluster mode requires maybe additional setup of: - echo - Virtual memory [vm.max_map_count] - echo. - set /p "response=Enable cluster mode? [y/N] " - if /I "!response!" == "Y" (set "cluster_mode=1") ELSE (set "cluster_mode=0") - ) -) - -set BASE_DIR=%SCRIPT_DIR%\..\..\..\ -if not exist %BASE_DIR% ( - echo "basedir does not exist" - exit /b 1 -) - -set "CUR=%cd%" -cd %BASE_DIR% -set "BASE_DIR=%cd%\" -cd %CUR% -echo Basedir: %BASE_DIR% - -set "OPENSEARCH_CONF_FILE=%BASE_DIR%config\opensearch.yml" -set "INTERNAL_USERS_FILE"=%BASE_DIR%config\opensearch-security\internal_users.yml" -set "OPENSEARCH_CONF_DIR=%BASE_DIR%config\" -set "OPENSEARCH_BIN_DIR=%BASE_DIR%bin\" -set "OPENSEARCH_PLUGINS_DIR=%BASE_DIR%plugins\" -set "OPENSEARCH_MODULES_DIR=%BASE_DIR%modules\" -set "OPENSEARCH_LIB_PATH=%BASE_DIR%lib\" -set "OPENSEARCH_INSTALL_TYPE=.zip" - -if not exist %OPENSEARCH_CONF_FILE% ( - echo Unable to determine OpenSearch config file. Quit. - exit /b 1 -) - -if not exist %OPENSEARCH_BIN_DIR% ( - echo Unable to determine OpenSearch bin directory. Quit. - exit /b 1 -) - -if not exist %OPENSEARCH_PLUGINS_DIR% ( - echo Unable to determine OpenSearch plugins directory. Quit. - exit /b 1 -) - -if not exist %OPENSEARCH_MODULES_DIR% ( - echo Unable to determine OpenSearch modules directory. Quit. - exit /b 1 -) - -if not exist %OPENSEARCH_LIB_PATH% ( - echo Unable to determine OpenSearch lib directory. Quit. - exit /b 1 -) - -if not exist %OPENSEARCH_PLUGINS_DIR%\opensearch-security\ ( - echo OpenSearch Security plugin not installed. Quit. - exit /b 1 -) - -set "OPENSEARCH_VERSION=" -for %%F in ("%OPENSEARCH_LIB_PATH%opensearch-*.jar") do set "OPENSEARCH_VERSION=%%~nxF" & goto :opensearch_version -:opensearch_version -set "OPENSEARCH_JAR_VERSION=" -for /f "tokens=2 delims=[-]" %%a in ("%OPENSEARCH_VERSION%") do set "OPENSEARCH_JAR_VERSION=%%a" - -set "SECURITY_VERSION=" -for %%F in ("%OPENSEARCH_PLUGINS_DIR%\opensearch-security\opensearch-security-*.jar") do set "SECURITY_VERSION=%%~nxF" -set "SECURITY_JAR_VERSION=" -for /f "tokens=3 delims=[-]" %%a in ("%SECURITY_VERSION%") do set "SECURITY_JAR_VERSION=%%a" - -for /f "tokens=4-7 delims=[.] " %%i in ('ver') do (if %%i==Version (set "OS=%%j.%%k") else (set v="%%i.%%j")) -echo OpenSearch install type: %OPENSEARCH_INSTALL_TYPE% on %OS% -echo OpenSearch config dir: %OPENSEARCH_CONF_DIR% -echo OpenSearch config file: %OPENSEARCH_CONF_FILE% -echo OpenSearch bin dir: %OPENSEARCH_BIN_DIR% -echo OpenSearch plugins dir: %OPENSEARCH_PLUGINS_DIR% -echo OpenSearch lib dir: %OPENSEARCH_LIB_PATH% -echo Detected OpenSearch Version: %OPENSEARCH_JAR_VERSION% -echo Detected OpenSearch Security Version: %SECURITY_JAR_VERSION% - ->nul findstr /c:"plugins.security" "%OPENSEARCH_CONF_FILE%" && ( - echo %OPENSEARCH_CONF_FILE% seems to be already configured for Security. Quit. - exit /b %skip_updates% -) - -set LF=^ - - -:: two empty line required after LF -set ADMIN_CERT=-----BEGIN CERTIFICATE-----!LF!^ -MIIEmDCCA4CgAwIBAgIUZjrlDPP8azRDPZchA/XEsx0X2iYwDQYJKoZIhvcNAQEL!LF!^ -BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt!LF!^ -cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl!LF!^ -IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v!LF!^ -dCBDQTAeFw0yMzA4MjkyMDA2MzdaFw0zMzA4MjYyMDA2MzdaME0xCzAJBgNVBAYT!LF!^ -AmRlMQ0wCwYDVQQHDAR0ZXN0MQ8wDQYDVQQKDAZjbGllbnQxDzANBgNVBAsMBmNs!LF!^ -aWVudDENMAsGA1UEAwwEa2lyazCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC!LF!^ -ggEBAJVcOAQlCiuB9emCljROAXnlsPbG7PE3kNz2sN+BbGuw686Wgyl3uToVHvVs!LF!^ -paMmLUqm1KYz9wMSWTIBZgpJ9hYaIbGxD4RBb7qTAJ8Q4ddCV2f7T4lxao/6ixI+!LF!^ -O0l/BG9E3mRGo/r0w+jtTQ3aR2p6eoxaOYbVyEMYtFI4QZTkcgGIPGxm05y8xonx!LF!^ -vV5pbSW9L7qAVDzQC8EYGQMMI4ccu0NcHKWt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UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQU!LF!^ -F4ffoFrrZhKn1dD4uhJFPLcrAJwwgc8GA1UdIwSBxzCBxIAUF4ffoFrrZhKn1dD4!LF!^ -uhJFPLcrAJyhgZWkgZIwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJ!LF!^ -k/IsZAEZFgdleGFtcGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYD!LF!^ -VQQLDBhFeGFtcGxlIENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUg!LF!^ -Q29tIEluYy4gUm9vdCBDQYIUd+SvPvzan5P2TQbEZ4zj4Gt6FYowDQYJKoZIhvcN!LF!^ -AQELBQADggEBAIopqco/k9RSjouTeKP4z0EVUxdD4qnNh1GLSRqyAVe0aChyKF5f!LF!^ -qt1Bd1XCY8D16RgekkKGHDpJhGCpel+vtIoXPBxUaGQNYxmJCf5OzLMODlcrZk5i!LF!^ -jHIcv/FMeK02NBcz/WQ3mbWHVwXLhmwqa2zBsF4FmPCJAbFLchLhkAv1HJifHbnD!LF!^ -jQzlKyl5jxam/wtjWxSm0iyso0z2TgyzY+MESqjEqB1hZkCFzD1xtUOCxbXgtKae!LF!^ -dgfHVFuovr3fNLV3GvQk0s9okDwDUcqV7DSH61e5bUMfE84o3of8YA7+HUoPV5Du!LF!^ -8sTOKRf7ncGXdDRA8aofW268pTCuIu3+g/Y=!LF!^ ------END CERTIFICATE-----!LF! - - -echo !ADMIN_CERT! > "%OPENSEARCH_CONF_DIR%kirk.pem" -echo !NODE_CERT! > "%OPENSEARCH_CONF_DIR%esnode.pem" -echo !ROOT_CA! > "%OPENSEARCH_CONF_DIR%root-ca.pem" -echo !NODE_KEY! > "%OPENSEARCH_CONF_DIR%esnode-key.pem" -echo !ADMIN_CERT_KEY! > "%OPENSEARCH_CONF_DIR%kirk-key.pem" - -echo. >> "%OPENSEARCH_CONF_FILE%" -echo ######## Start OpenSearch Security Demo Configuration ######## >> "%OPENSEARCH_CONF_FILE%" -echo # WARNING: revise all the lines below before you go into production >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.ssl.transport.pemcert_filepath: esnode.pem >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.ssl.transport.pemkey_filepath: esnode-key.pem >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.ssl.transport.pemtrustedcas_filepath: root-ca.pem >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.ssl.transport.enforce_hostname_verification: false >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.ssl.http.enabled: true >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.ssl.http.pemcert_filepath: esnode.pem >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.ssl.http.pemkey_filepath: esnode-key.pem >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.ssl.http.pemtrustedcas_filepath: root-ca.pem >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.allow_unsafe_democertificates: true >> "%OPENSEARCH_CONF_FILE%" -if %initsecurity% == 1 ( - echo plugins.security.allow_default_init_securityindex: true >> "%OPENSEARCH_CONF_FILE%" -) -echo plugins.security.authcz.admin_dn: >> "%OPENSEARCH_CONF_FILE%" -echo - CN=kirk,OU=client,O=client,L=test, C=de >> "%OPENSEARCH_CONF_FILE%" -echo. >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.audit.type: internal_opensearch >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.enable_snapshot_restore_privilege: true >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.check_snapshot_restore_write_privileges: true >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.restapi.roles_enabled: ["all_access", "security_rest_api_access"] >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.system_indices.enabled: true >> "%OPENSEARCH_CONF_FILE%" -echo plugins.security.system_indices.indices: [".plugins-ml-config", ".plugins-ml-connector", ".plugins-ml-model-group", ".plugins-ml-model", ".plugins-ml-task", ".plugins-ml-conversation-meta", ".plugins-ml-conversation-interactions", ".opendistro-alerting-config", ".opendistro-alerting-alert*", ".opendistro-anomaly-results*", ".opendistro-anomaly-detector*", ".opendistro-anomaly-checkpoints", ".opendistro-anomaly-detection-state", ".opendistro-reports-*", ".opensearch-notifications-*", ".opensearch-notebooks", ".opensearch-observability", ".ql-datasources", ".opendistro-asynchronous-search-response*", ".replication-metadata-store", ".opensearch-knn-models", ".geospatial-ip2geo-data*"] >> "%OPENSEARCH_CONF_FILE%" - -setlocal enabledelayedexpansion - -set "ADMIN_PASSWORD_FILE=%OPENSEARCH_CONF_DIR%initialAdminPassword.txt" -set "INTERNAL_USERS_FILE=%OPENSEARCH_CONF_DIR%opensearch-security\internal_users.yml" - -echo "what is in the config directory" -dir %OPENSEARCH_CONF_DIR% - -echo "what is in the password file" -type "%ADMIN_PASSWORD_FILE%" - - -if "%initialAdminPassword%" NEQ "" ( - set "ADMIN_PASSWORD=!initialAdminPassword!" +if defined OPENSEARCH_JAVA_HOME ( + set BIN_PATH="%OPENSEARCH_JAVA_HOME%\bin\java.exe" +) else if defined JAVA_HOME ( + set BIN_PATH="%JAVA_HOME%\bin\java.exe" ) else ( - for /f %%a in ('type "%ADMIN_PASSWORD_FILE%"') do set "ADMIN_PASSWORD=%%a" -) - -if not defined ADMIN_PASSWORD ( - echo Unable to find the admin password for the cluster. Please set initialAdminPassword or create a file %ADMIN_PASSWORD_FILE% with a single line that contains the password. + echo Unable to find java runtime + echo OPENSEARCH_JAVA_HOME or JAVA_HOME must be defined exit /b 1 ) -echo " ***************************************************" -echo " *** ADMIN PASSWORD SET TO: %ADMIN_PASSWORD% ***" -echo " ***************************************************" - -set "HASH_SCRIPT=%OPENSEARCH_PLUGINS_DIR%\opensearch-security\tools\hash.bat" - -REM Run the command and capture its output -for /f %%a in ('%HASH_SCRIPT% -p !ADMIN_PASSWORD!') do ( - set "HASHED_ADMIN_PASSWORD=%%a" -) - -if errorlevel 1 ( - echo Failed to hash the admin password - exit /b 1 -) - -set "default_line= hash: "$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG"" -set "search=%default_line%" -set "replace= hash: "%HASHED_ADMIN_PASSWORD%"" - -setlocal enableextensions -for /f "delims=" %%i in ('type "%INTERNAL_USERS_FILE%" ^& break ^> "%INTERNAL_USERS_FILE%" ') do ( - set "line=%%i" - setlocal enabledelayedexpansion - >>"%INTERNAL_USERS_FILE%" echo(!line:%search%=%replace%! - endlocal -) - -:: network.host ->nul findstr /b /c:"network.host" "%OPENSEARCH_CONF_FILE%" && ( - echo network.host already present -) || ( - if %cluster_mode% == 1 ( - echo network.host: 0.0.0.0 >> "%OPENSEARCH_CONF_FILE%" - echo node.name: smoketestnode >> "%OPENSEARCH_CONF_FILE%" - echo cluster.initial_cluster_manager_nodes: smoketestnode >> "%OPENSEARCH_CONF_FILE%" - ) -) - ->nul findstr /b /c:"node.max_local_storage_nodes" "%OPENSEARCH_CONF_FILE%" && ( - echo node.max_local_storage_nodes already present -) || ( - echo node.max_local_storage_nodes: 3 >> "%OPENSEARCH_CONF_FILE%" -) - -echo ######## End OpenSearch Security Demo Configuration ######## >> "%OPENSEARCH_CONF_FILE%" - -echo ### Success -echo ### Execute this script now on all your nodes and then start all nodes -:: Generate securityadmin_demo.bat -echo. > securityadmin_demo.bat -echo %OPENSEARCH_PLUGINS_DIR%opensearch-security\tools\securityadmin.bat -cd %OPENSEARCH_CONF_DIR%opensearch-security -icl -key %OPENSEARCH_CONF_DIR%kirk-key.pem -cert %OPENSEARCH_CONF_DIR%kirk.pem -cacert %OPENSEARCH_CONF_DIR%root-ca.pem -nhnv >> securityadmin_demo.bat - -if %initsecurity% == 0 ( - echo ### After the whole cluster is up execute: - type securityadmin_demo.bat - echo ### or run ./securityadmin_demo.bat - echo ### After that you can also use the Security Plugin ConfigurationGUI -) else ( - echo ### OpenSearch Security will be automatically initialized. - echo ### If you like to change the runtime configuration - echo ### change the files in ../../../config/opensearch-security and execute: - type securityadmin_demo.bat - echo ### or run ./securityadmin_demo.bat - echo ### To use the Security Plugin ConfigurationGUI -) - -echo ### To access your secured cluster open https://: and log in with admin/admin. -echo ### [Ignore the SSL certificate warning because we installed self-signed demo certificates] +%BIN_PATH% -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.InstallDemoConfiguration %DIR% %* 2> nul \ No newline at end of file diff --git a/tools/install_demo_configuration.sh b/tools/install_demo_configuration.sh index 01bc1bfed1..ccd59fe34a 100755 --- a/tools/install_demo_configuration.sh +++ b/tools/install_demo_configuration.sh @@ -1,11 +1,6 @@ #!/bin/bash #install_demo_configuration.sh [-y] -echo "**************************************************************************" -echo "** This tool will be deprecated in the next major release of OpenSearch **" -echo "** https://github.com/opensearch-project/security/issues/1755 **" -echo "**************************************************************************" - SCRIPT_PATH="${BASH_SOURCE[0]}" if ! [ -x "$(command -v realpath)" ]; then if [ -L "$SCRIPT_PATH" ]; then @@ -21,455 +16,15 @@ else DIR="$( cd "$( dirname "$(realpath "$SCRIPT_PATH")" )" && pwd -P)" fi -echo "OpenSearch Security Demo Installer" -echo " ** Warning: Do not use on production or public reachable systems **" - -OPTIND=1 -assumeyes=0 -initsecurity=0 -cluster_mode=0 -skip_updates=-1 - -function show_help() { - echo "install_demo_configuration.sh [-y] [-i] [-c]" - echo " -h show help" - echo " -y confirm all installation dialogues automatically" - echo " -i initialize Security plugin with default configuration (default is to ask if -y is not given)" - echo " -c enable cluster mode by binding to all network interfaces (default is to ask if -y is not given)" - echo " -s skip updates if config is already applied to opensearch.yml" -} - -while getopts "h?yics" opt; do - case "$opt" in - h|\?) - show_help - exit 0 - ;; - y) assumeyes=1 - ;; - i) initsecurity=1 - ;; - c) cluster_mode=1 - ;; - s) skip_updates=0 - esac -done - -shift $((OPTIND-1)) - -[ "$1" = "--" ] && shift - -if [ "$assumeyes" == 0 ]; then - read -r -p "Install demo certificates? [y/N] " response - case "$response" in - [yY][eE][sS]|[yY]) - ;; - *) - exit 0 - ;; - esac -fi - -if [ "$initsecurity" == 0 ] && [ "$assumeyes" == 0 ]; then - read -r -p "Initialize Security Modules? [y/N] " response - case "$response" in - [yY][eE][sS]|[yY]) - initsecurity=1 - ;; - *) - initsecurity=0 - ;; - esac -fi - -if [ "$cluster_mode" == 0 ] && [ "$assumeyes" == 0 ]; then - echo "Cluster mode requires maybe additional setup of:" - echo " - Virtual memory (vm.max_map_count)" - echo "" - read -r -p "Enable cluster mode? [y/N] " response - case "$response" in - [yY][eE][sS]|[yY]) - cluster_mode=1 - ;; - *) - cluster_mode=0 - ;; - esac -fi - -set -e -BASE_DIR="$DIR/../../.." -if [ -d "$BASE_DIR" ]; then - CUR="$(pwd)" - cd "$BASE_DIR" - BASE_DIR="$(pwd)" - cd "$CUR" - echo "Basedir: $BASE_DIR" -else - echo "DEBUG: basedir does not exist" -fi - -OPENSEARCH_CONF_FILE="$BASE_DIR/config/opensearch.yml" -OPENSEARCH_BIN_DIR="$BASE_DIR/bin" -OPENSEARCH_PLUGINS_DIR="$BASE_DIR/plugins" -OPENSEARCH_MODULES_DIR="$BASE_DIR/modules" -OPENSEARCH_LIB_PATH="$BASE_DIR/lib" -SUDO_CMD="" -OPENSEARCH_INSTALL_TYPE=".tar.gz" - -#Check if its a rpm/deb install -if [ "/usr/share/opensearch" -ef "$BASE_DIR" ]; then - OPENSEARCH_CONF_FILE="/usr/share/opensearch/config/opensearch.yml" - - if [ ! -f "$OPENSEARCH_CONF_FILE" ]; then - OPENSEARCH_CONF_FILE="/etc/opensearch/opensearch.yml" - fi - - if [ -x "$(command -v sudo)" ]; then - SUDO_CMD="sudo" - echo "This script maybe require your root password for 'sudo' privileges" - fi - - OPENSEARCH_INSTALL_TYPE="rpm/deb" -fi - -if [ $SUDO_CMD ]; then - if ! [ -x "$(command -v $SUDO_CMD)" ]; then - echo "Unable to locate 'sudo' command. Quit." - exit 1 - fi -fi - -if $SUDO_CMD test -f "$OPENSEARCH_CONF_FILE"; then - : -else - echo "Unable to determine OpenSearch config directory. Quit." - exit -1 -fi - -if [ ! -d "$OPENSEARCH_BIN_DIR" ]; then - echo "Unable to determine OpenSearch bin directory. Quit." - exit -1 -fi - -if [ ! -d "$OPENSEARCH_PLUGINS_DIR" ]; then - echo "Unable to determine OpenSearch plugins directory. Quit." - exit -1 -fi - -if [ ! -d "$OPENSEARCH_MODULES_DIR" ]; then - echo "Unable to determine OpenSearch modules directory. Quit." - #exit -1 -fi - -if [ ! -d "$OPENSEARCH_LIB_PATH" ]; then - echo "Unable to determine OpenSearch lib directory. Quit." - exit -1 -fi - -OPENSEARCH_CONF_DIR=$(dirname "${OPENSEARCH_CONF_FILE}") -OPENSEARCH_CONF_DIR=`cd "$OPENSEARCH_CONF_DIR" ; pwd` - -if [ ! -d "$OPENSEARCH_PLUGINS_DIR/opensearch-security" ]; then - echo "OpenSearch Security plugin not installed. Quit." - exit -1 -fi - -OPENSEARCH_VERSION=("$OPENSEARCH_LIB_PATH/opensearch-*.jar") -OPENSEARCH_VERSION=$(echo $OPENSEARCH_VERSION | sed 's/.*opensearch-\(.*\)\.jar/\1/') - -SECURITY_VERSION=("$OPENSEARCH_PLUGINS_DIR/opensearch-security/opensearch-security-*.jar") -SECURITY_VERSION=$(echo $SECURITY_VERSION | sed 's/.*opensearch-security-\(.*\)\.jar/\1/') - -OS=$(sb_release -ds 2>/dev/null || cat /etc/*release 2>/dev/null | head -n1 || uname -om) -echo "OpenSearch install type: $OPENSEARCH_INSTALL_TYPE on $OS" -echo "OpenSearch config dir: $OPENSEARCH_CONF_DIR" -echo "OpenSearch config file: $OPENSEARCH_CONF_FILE" -echo "OpenSearch bin dir: $OPENSEARCH_BIN_DIR" -echo "OpenSearch plugins dir: $OPENSEARCH_PLUGINS_DIR" -echo "OpenSearch lib dir: $OPENSEARCH_LIB_PATH" -echo "Detected OpenSearch Version: $OPENSEARCH_VERSION" -echo "Detected OpenSearch Security Version: $SECURITY_VERSION" - -if $SUDO_CMD grep --quiet -i plugins.security "$OPENSEARCH_CONF_FILE"; then - echo "$OPENSEARCH_CONF_FILE seems to be already configured for Security. Quit." - exit $skip_updates -fi - -set +e - -read -r -d '' ADMIN_CERT << EOM ------BEGIN CERTIFICATE----- -MIIEmDCCA4CgAwIBAgIUZjrlDPP8azRDPZchA/XEsx0X2iYwDQYJKoZIhvcNAQEL -BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt -cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl -IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v -dCBDQTAeFw0yMzA4MjkyMDA2MzdaFw0zMzA4MjYyMDA2MzdaME0xCzAJBgNVBAYT -AmRlMQ0wCwYDVQQHDAR0ZXN0MQ8wDQYDVQQKDAZjbGllbnQxDzANBgNVBAsMBmNs -aWVudDENMAsGA1UEAwwEa2lyazCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBAJVcOAQlCiuB9emCljROAXnlsPbG7PE3kNz2sN+BbGuw686Wgyl3uToVHvVs -paMmLUqm1KYz9wMSWTIBZgpJ9hYaIbGxD4RBb7qTAJ8Q4ddCV2f7T4lxao/6ixI+ -O0l/BG9E3mRGo/r0w+jtTQ3aR2p6eoxaOYbVyEMYtFI4QZTkcgGIPGxm05y8xonx -vV5pbSW9L7qAVDzQC8EYGQMMI4ccu0NcHKWtmTYJA/wDPE2JwhngHwbcIbc4cDz6 -cG0S3FmgiKGuuSqUy35v/k3y7zMHQSdx7DSR2tzhH/bBL/9qGvpT71KKrxPtaxS0 -bAqPcEkKWDo7IMlGGW7LaAWfGg8CAwEAAaOCASswggEnMAwGA1UdEwEB/wQCMAAw -DgYDVR0PAQH/BAQDAgXgMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMCMIHPBgNVHSME -gccwgcSAFBeH36Ba62YSp9XQ+LoSRTy3KwCcoYGVpIGSMIGPMRMwEQYKCZImiZPy -LGQBGRYDY29tMRcwFQYKCZImiZPyLGQBGRYHZXhhbXBsZTEZMBcGA1UECgwQRXhh -bXBsZSBDb20gSW5jLjEhMB8GA1UECwwYRXhhbXBsZSBDb20gSW5jLiBSb290IENB -MSEwHwYDVQQDDBhFeGFtcGxlIENvbSBJbmMuIFJvb3QgQ0GCFHfkrz782p+T9k0G -xGeM4+BrehWKMB0GA1UdDgQWBBSjMS8tgguX/V7KSGLoGg7K6XMzIDANBgkqhkiG -9w0BAQsFAAOCAQEANMwD1JYlwAh82yG1gU3WSdh/tb6gqaSzZK7R6I0L7slaXN9m -y2ErUljpTyaHrdiBFmPhU/2Kj2r+fIUXtXdDXzizx/JdmueT0nG9hOixLqzfoC9p -fAhZxM62RgtyZoaczQN82k1/geMSwRpEndFe3OH7arkS/HSbIFxQhAIy229eWe5d -1bUzP59iu7f3r567I4ob8Vy7PP+Ov35p7Vv4oDHHwgsdRzX6pvL6mmwVrQ3BfVec -h9Dqprr+ukYmjho76g6k5cQuRaB6MxqldzUg+2E7IHQP8MCF+co51uZq2nl33mtp -RGr6JbdHXc96zsLTL3saJQ8AWEfu1gbTVrwyRA== ------END CERTIFICATE----- -EOM - -read -r -d '' ADMIN_CERT_KEY << EOM ------BEGIN PRIVATE KEY----- -MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCVXDgEJQorgfXp -gpY0TgF55bD2xuzxN5Dc9rDfgWxrsOvOloMpd7k6FR71bKWjJi1KptSmM/cDElky -AWYKSfYWGiGxsQ+EQW+6kwCfEOHXQldn+0+JcWqP+osSPjtJfwRvRN5kRqP69MPo -7U0N2kdqenqMWjmG1chDGLRSOEGU5HIBiDxsZtOcvMaJ8b1eaW0lvS+6gFQ80AvB -GBkDDCOHHLtDXBylrZk2CQP8AzxNicIZ4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DLpSWUJp -nBY2S57MSM11/MVslrEgGmYNnI4r1K25xlaqV6K6ztEJv6n69327MS4NG8L/gCU5 -3pEm38hkUi8pVYU7in7rx4TCkrq94OkzWJYurAkCgYATQCL/rJLQAlJIGulp8s6h -mQGwy8vIqMjAdHGLrCS35sVYBXG13knS52LJHvbVee39AbD5/LlWvjJGlQMzCLrw -F7oILW5kXxhb8S73GWcuMbuQMFVHFONbZAZgn+C9FW4l7XyRdkrbR1MRZ2km8YMs -/AHmo368d4PSNRMMzLHw8Q== ------END PRIVATE KEY----- -EOM - -read -r -d '' NODE_CERT << EOM ------BEGIN CERTIFICATE----- -MIIEPDCCAySgAwIBAgIUZjrlDPP8azRDPZchA/XEsx0X2iIwDQYJKoZIhvcNAQEL -BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt -cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl -IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v -dCBDQTAeFw0yMzA4MjkwNDIzMTJaFw0zMzA4MjYwNDIzMTJaMFcxCzAJBgNVBAYT -AmRlMQ0wCwYDVQQHDAR0ZXN0MQ0wCwYDVQQKDARub2RlMQ0wCwYDVQQLDARub2Rl -MRswGQYDVQQDDBJub2RlLTAuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUA -A4IBDwAwggEKAoIBAQCm93kXteDQHMAvbUPNPW5pyRHKDD42XGWSgq0k1D29C/Ud -yL21HLzTJa49ZU2ldIkSKs9JqbkHdyK0o8MO6L8dotLoYbxDWbJFW8bp1w6tDTU0 -HGkn47XVu3EwbfrTENg3jFu+Oem6a/501SzITzJWtS0cn2dIFOBimTVpT/4Zv5qr -XA6Cp4biOmoTYWhi/qQl8d0IaADiqoZ1MvZbZ6x76qTrRAbg+UWkpTEXoH1xTc8n -dibR7+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T" | $SUDO_CMD tee "$OPENSEARCH_CONF_DIR/esnode.pem" > /dev/null -echo "$ROOT_CA" | $SUDO_CMD tee "$OPENSEARCH_CONF_DIR/root-ca.pem" > /dev/null -echo "$NODE_KEY" | $SUDO_CMD tee "$OPENSEARCH_CONF_DIR/esnode-key.pem" > /dev/null -echo "$ADMIN_CERT_KEY" | $SUDO_CMD tee "$OPENSEARCH_CONF_DIR/kirk-key.pem" > /dev/null - -chmod 0600 "$OPENSEARCH_CONF_DIR/kirk.pem" -chmod 0600 "$OPENSEARCH_CONF_DIR/esnode.pem" -chmod 0600 "$OPENSEARCH_CONF_DIR/root-ca.pem" -chmod 0600 "$OPENSEARCH_CONF_DIR/esnode-key.pem" -chmod 0600 "$OPENSEARCH_CONF_DIR/kirk-key.pem" - -echo "" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" -echo "######## Start OpenSearch Security Demo Configuration ########" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "# WARNING: revise all the lines below before you go into production" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.ssl.transport.pemcert_filepath: esnode.pem" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.ssl.transport.pemkey_filepath: esnode-key.pem" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.ssl.transport.pemtrustedcas_filepath: root-ca.pem" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.ssl.transport.enforce_hostname_verification: false" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.ssl.http.enabled: true" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.ssl.http.pemcert_filepath: esnode.pem" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.ssl.http.pemkey_filepath: esnode-key.pem" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.ssl.http.pemtrustedcas_filepath: root-ca.pem" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.allow_unsafe_democertificates: true" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -if [ "$initsecurity" == 1 ]; then - echo "plugins.security.allow_default_init_securityindex: true" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -fi -echo "plugins.security.authcz.admin_dn:" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo " - CN=kirk,OU=client,O=client,L=test, C=de" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.audit.type: internal_opensearch" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.enable_snapshot_restore_privilege: true" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo "plugins.security.check_snapshot_restore_write_privileges: true" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo 'plugins.security.restapi.roles_enabled: ["all_access", "security_rest_api_access"]' | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo 'plugins.security.system_indices.enabled: true' | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -echo 'plugins.security.system_indices.indices: [".plugins-ml-config", ".plugins-ml-connector", ".plugins-ml-model-group", ".plugins-ml-model", ".plugins-ml-task", ".plugins-ml-conversation-meta", ".plugins-ml-conversation-interactions", ".opendistro-alerting-config", ".opendistro-alerting-alert*", ".opendistro-anomaly-results*", ".opendistro-anomaly-detector*", ".opendistro-anomaly-checkpoints", ".opendistro-anomaly-detection-state", ".opendistro-reports-*", ".opensearch-notifications-*", ".opensearch-notebooks", ".opensearch-observability", ".ql-datasources", ".opendistro-asynchronous-search-response*", ".replication-metadata-store", ".opensearch-knn-models", ".geospatial-ip2geo-data*"]' | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null - -## Read the admin password from the file or use the initialAdminPassword if set -ADMIN_PASSWORD_FILE="$OPENSEARCH_CONF_DIR/initialAdminPassword.txt" -INTERNAL_USERS_FILE="$OPENSEARCH_CONF_DIR/opensearch-security/internal_users.yml" - -if [[ -n "$initialAdminPassword" ]]; then - ADMIN_PASSWORD="$initialAdminPassword" -elif [[ -f "$ADMIN_PASSWORD_FILE" && -s "$ADMIN_PASSWORD_FILE" ]]; then - ADMIN_PASSWORD=$(head -n 1 "$ADMIN_PASSWORD_FILE") -else - echo "Unable to find the admin password for the cluster. Please run 'export initialAdminPassword=' or create a file $ADMIN_PASSWORD_FILE with a single line that contains the password." - exit 1 -fi - -echo " ***************************************************" -echo " *** ADMIN PASSWORD SET TO: $ADMIN_PASSWORD ***" -echo " ***************************************************" - -$SUDO_CMD chmod +x "$OPENSEARCH_PLUGINS_DIR/opensearch-security/tools/hash.sh" - -# Use the Hasher script to hash the admin password -HASHED_ADMIN_PASSWORD=$($OPENSEARCH_PLUGINS_DIR/opensearch-security/tools/hash.sh -p "$ADMIN_PASSWORD" | tail -n 1) - -if [ $? -ne 0 ]; then - echo "Hash the admin password failure, see console for details" - exit 1 -fi - -# Find the line number containing 'admin:' in the internal_users.yml file -ADMIN_HASH_LINE=$(grep -n 'admin:' "$INTERNAL_USERS_FILE" | cut -f1 -d:) - -awk -v hashed_admin_password="$HASHED_ADMIN_PASSWORD" ' - /^ *hash: *"\$2a\$12\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR\/YFJcgHp0UGns5JDymv..TOG"/ { - sub(/"\$2a\$12\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR\/YFJcgHp0UGns5JDymv..TOG"/, "\"" hashed_admin_password "\""); - } - { print } -' "$INTERNAL_USERS_FILE" > temp_file && mv temp_file "$INTERNAL_USERS_FILE" - -#network.host -if $SUDO_CMD grep --quiet -i "^network.host" "$OPENSEARCH_CONF_FILE"; then - : #already present -else - if [ "$cluster_mode" == 1 ]; then - echo "network.host: 0.0.0.0" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null - echo "node.name: smoketestnode" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null - echo "cluster.initial_cluster_manager_nodes: smoketestnode" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null - fi -fi - -if $SUDO_CMD grep --quiet -i "^node.max_local_storage_nodes" "$OPENSEARCH_CONF_FILE"; then - : #already present -else - echo 'node.max_local_storage_nodes: 3' | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null -fi - - - -echo "######## End OpenSearch Security Demo Configuration ########" | $SUDO_CMD tee -a "$OPENSEARCH_CONF_FILE" > /dev/null - -$SUDO_CMD chmod +x "$OPENSEARCH_PLUGINS_DIR/opensearch-security/tools/securityadmin.sh" - -OPENSEARCH_PLUGINS_DIR=`cd "$OPENSEARCH_PLUGINS_DIR" ; pwd` - -echo "### Success" -echo "### Execute this script now on all your nodes and then start all nodes" -#Generate securityadmin_demo.sh -echo "#!/bin/bash" | $SUDO_CMD tee securityadmin_demo.sh > /dev/null -echo $SUDO_CMD \""$OPENSEARCH_PLUGINS_DIR/opensearch-security/tools/securityadmin.sh"\" -cd \""$OPENSEARCH_CONF_DIR/opensearch-security"\" -icl -key \""$OPENSEARCH_CONF_DIR/kirk-key.pem"\" -cert \""$OPENSEARCH_CONF_DIR/kirk.pem"\" -cacert \""$OPENSEARCH_CONF_DIR/root-ca.pem"\" -nhnv | $SUDO_CMD tee -a securityadmin_demo.sh > /dev/null -$SUDO_CMD chmod +x securityadmin_demo.sh +BIN_PATH="java" -if [ "$initsecurity" == 0 ]; then - echo "### After the whole cluster is up execute: " - $SUDO_CMD cat securityadmin_demo.sh | tail -1 - echo "### or run ./securityadmin_demo.sh" - echo "### After that you can also use the Security Plugin ConfigurationGUI" +# now set the path to java: first OPENSEARCH_JAVA_HOME, then JAVA_HOME +if [ ! -z "$OPENSEARCH_JAVA_HOME" ]; then + BIN_PATH="$OPENSEARCH_JAVA_HOME/bin/java" +elif [ ! -z "$JAVA_HOME" ]; then + BIN_PATH="$JAVA_HOME/bin/java" else - echo "### OpenSearch Security will be automatically initialized." - echo "### If you like to change the runtime configuration " - echo "### change the files in ../../../config/opensearch-security and execute: " - $SUDO_CMD cat securityadmin_demo.sh | tail -1 - echo "### or run ./securityadmin_demo.sh" - echo "### To use the Security Plugin ConfigurationGUI" + echo "WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use $(which $BIN_PATH)" fi -echo "### To access your secured cluster open https://: and log in with admin/admin." -echo "### (Ignore the SSL certificate warning because we installed self-signed demo certificates)" +"$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.InstallDemoConfiguration "$DIR" "$@" 2>/dev/null diff --git a/tools/install_demo_configuration_with_java_tool.bat b/tools/install_demo_configuration_with_java_tool.bat deleted file mode 100644 index 04bf80e3e4..0000000000 --- a/tools/install_demo_configuration_with_java_tool.bat +++ /dev/null @@ -1,14 +0,0 @@ -@echo off -set DIR=%~dp0 - -if defined OPENSEARCH_JAVA_HOME ( - set BIN_PATH="%OPENSEARCH_JAVA_HOME%\bin\java.exe" -) else if defined JAVA_HOME ( - set BIN_PATH="%JAVA_HOME%\bin\java.exe" -) else ( - echo Unable to find java runtime - echo OPENSEARCH_JAVA_HOME or JAVA_HOME must be defined - exit /b 1 -) - -%BIN_PATH% -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.InstallDemoConfiguration %DIR% %* 2> nul \ No newline at end of file diff --git a/tools/install_demo_configuration_with_java_tool.sh b/tools/install_demo_configuration_with_java_tool.sh deleted file mode 100755 index ccd59fe34a..0000000000 --- a/tools/install_demo_configuration_with_java_tool.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash -#install_demo_configuration.sh [-y] - -SCRIPT_PATH="${BASH_SOURCE[0]}" -if ! [ -x "$(command -v realpath)" ]; then - if [ -L "$SCRIPT_PATH" ]; then - - [ -x "$(command -v readlink)" ] || { echo "Not able to resolve symlink. Install realpath or readlink.";exit 1; } - - # try readlink (-f not needed because we know its a symlink) - DIR="$( cd "$( dirname $(readlink "$SCRIPT_PATH") )" && pwd -P)" - else - DIR="$( cd "$( dirname "$SCRIPT_PATH" )" && pwd -P)" - fi -else - DIR="$( cd "$( dirname "$(realpath "$SCRIPT_PATH")" )" && pwd -P)" -fi - -BIN_PATH="java" - -# now set the path to java: first OPENSEARCH_JAVA_HOME, then JAVA_HOME -if [ ! -z "$OPENSEARCH_JAVA_HOME" ]; then - BIN_PATH="$OPENSEARCH_JAVA_HOME/bin/java" -elif [ ! -z "$JAVA_HOME" ]; then - BIN_PATH="$JAVA_HOME/bin/java" -else - echo "WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use $(which $BIN_PATH)" -fi - -"$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.InstallDemoConfiguration "$DIR" "$@" 2>/dev/null From 9e9b50fdd07e8b5e92d837346556b4c9ee7f80ea Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Tue, 7 Nov 2023 15:07:11 -0500 Subject: [PATCH 07/27] Updates options reading workflow to skip first argument as that is the directory path Signed-off-by: Darshit Chanpura --- .../security/tools/InstallDemoConfiguration.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 0a089bbe7e..7650fa512e 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -32,7 +32,7 @@ import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX; import static org.opensearch.security.user.UserService.generatePassword; -public class InstallDemoConfiguration { +public final class InstallDemoConfiguration { static boolean assumeyes = false; static boolean initsecurity = false; static boolean cluster_mode = false; @@ -85,8 +85,8 @@ private static void readArguments(String[] args) { // set script execution dir SCRIPT_DIR = args[0]; - for (String arg : args) { - switch (arg) { + for (int i=1; i< args.length; i++) { + switch (args[i]) { case "-y": assumeyes = true; break; @@ -104,7 +104,7 @@ private static void readArguments(String[] args) { showHelp(); return; default: - System.out.println("Invalid option: " + arg); + System.out.println("Invalid option: " + args[i]); } } } From ddebaad831e334117c87aaf24e4e2fb8acaaadc7 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Tue, 7 Nov 2023 15:35:03 -0500 Subject: [PATCH 08/27] Adds a new option to accept the execution environment Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 7650fa512e..16fb132726 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -37,6 +37,8 @@ public final class InstallDemoConfiguration { static boolean initsecurity = false; static boolean cluster_mode = false; static boolean skip_updates = true; + + static ExecutionEnvironment environment = ExecutionEnvironment.production; static String SCRIPT_DIR; static String BASE_DIR; static String OPENSEARCH_CONF_FILE; @@ -85,7 +87,7 @@ private static void readArguments(String[] args) { // set script execution dir SCRIPT_DIR = args[0]; - for (int i=1; i< args.length; i++) { + for (int i = 1; i < args.length; i++) { switch (args[i]) { case "-y": assumeyes = true; @@ -99,6 +101,22 @@ private static void readArguments(String[] args) { case "-s": skip_updates = false; break; + case "-e": + i++; + try { + environment = ExecutionEnvironment.valueOf(args[i]); + } catch (IllegalArgumentException e) { + System.out.println( + "Invalid argument value for execution environment. " + + "Please provide one of `" + + ExecutionEnvironment.production + + "` OR `" + + ExecutionEnvironment.test + + "`" + ); + System.exit(-1); + } + break; case "-h": case "-?": showHelp(); @@ -732,3 +750,8 @@ public String getContent() { return content; } } + +enum ExecutionEnvironment { + production, + test; +} From d0e0fec48d7f336d2fc21b56f5ded1e52dbf2b1e Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Wed, 8 Nov 2023 11:24:10 -0500 Subject: [PATCH 09/27] Skips password validation if the new option `-t` is passed to set test as execution environment Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 27 +++++++------------ 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 16fb132726..c859405720 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -101,21 +101,8 @@ private static void readArguments(String[] args) { case "-s": skip_updates = false; break; - case "-e": - i++; - try { - environment = ExecutionEnvironment.valueOf(args[i]); - } catch (IllegalArgumentException e) { - System.out.println( - "Invalid argument value for execution environment. " - + "Please provide one of `" - + ExecutionEnvironment.production - + "` OR `" - + ExecutionEnvironment.test - + "`" - ); - System.exit(-1); - } + case "-t": + environment = ExecutionEnvironment.test; break; case "-h": case "-?": @@ -134,6 +121,9 @@ private static void showHelp() { System.out.println(" -i initialize Security plugin with default configuration (default is to ask if -y is not given)"); System.out.println(" -c enable cluster mode by binding to all network interfaces (default is to ask if -y is not given)"); System.out.println(" -s skip updates if config is already applied to opensearch.yml"); + System.out.println( + " -t set the execution environment to `test` to skip password validation. Should be used only for testing. (default is set to `production`)" + ); } private static void gatherUserInputs() { @@ -299,6 +289,7 @@ private static void setAdminPassword() { String initialAdminPassword = System.getenv("initialAdminPassword"); String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; String INTERNAL_USERS_FILE_PATH = OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; + boolean shouldValidatePassword = environment.equals(ExecutionEnvironment.production); try { final PasswordValidator passwordValidator = PasswordValidator.of( Settings.builder() @@ -319,8 +310,9 @@ private static void setAdminPassword() { } } - // Validate custom password - if (!ADMIN_PASSWORD.isEmpty() + // If script execution environment is set to production, validate custom password, else if set to test, skip validation + if (shouldValidatePassword + && !ADMIN_PASSWORD.isEmpty() && passwordValidator.validate("admin", ADMIN_PASSWORD) != RequestContentValidator.ValidationError.NONE) { System.out.println("Password " + ADMIN_PASSWORD + " is weak. Please re-try with a stronger password."); System.exit(-1); @@ -330,6 +322,7 @@ private static void setAdminPassword() { if (ADMIN_PASSWORD.isEmpty()) { System.out.println("No custom admin password found. Generating a new password now."); // generate a new random password + // We always validate a generated password while (passwordValidator.validate("admin", ADMIN_PASSWORD) != RequestContentValidator.ValidationError.NONE) { ADMIN_PASSWORD = generatePassword(); } From 88bb1e2994073f54ad33679309c70ff40dd2cd0a Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Wed, 8 Nov 2023 11:31:53 -0500 Subject: [PATCH 10/27] Adds some formatting change around printing password Signed-off-by: Darshit Chanpura --- .../opensearch/security/tools/InstallDemoConfiguration.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index c859405720..7dea2b91cc 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -329,9 +329,9 @@ private static void setAdminPassword() { } // print the password to the logs - System.out.println(" ***************************************************"); - System.out.println(" *** ADMIN PASSWORD SET TO: " + ADMIN_PASSWORD + " ***"); - System.out.println(" ***************************************************"); + System.out.println("\t***************************************************"); + System.out.println("\t\tADMIN PASSWORD SET TO: " + ADMIN_PASSWORD); + System.out.println("\t***************************************************"); String hashedAdminPassword = Hasher.hash(ADMIN_PASSWORD.toCharArray()); From 69d8ec0aa015d311b4665dc0f86a2daa4d7caa96 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Wed, 8 Nov 2023 12:01:11 -0500 Subject: [PATCH 11/27] Updates plugin install workflows to pass option `-t` to skip password-validation Signed-off-by: Darshit Chanpura --- .github/workflows/plugin_install.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/plugin_install.yml b/.github/workflows/plugin_install.yml index ae570a9df8..92d923bb0d 100644 --- a/.github/workflows/plugin_install.yml +++ b/.github/workflows/plugin_install.yml @@ -44,14 +44,14 @@ jobs: run: | cat > setup.sh <<'EOF' chmod +x ./opensearch-${{ env.OPENSEARCH_VERSION }}-SNAPSHOT/plugins/${{ env.PLUGIN_NAME }}/tools/install_demo_configuration.sh - /bin/bash -c "yes | ./opensearch-${{ env.OPENSEARCH_VERSION }}-SNAPSHOT/plugins/${{ env.PLUGIN_NAME }}/tools/install_demo_configuration.sh" + /bin/bash -c "yes | ./opensearch-${{ env.OPENSEARCH_VERSION }}-SNAPSHOT/plugins/${{ env.PLUGIN_NAME }}/tools/install_demo_configuration.sh -t" EOF - name: Create Setup Script if: ${{ runner.os == 'Windows' }} run: | New-Item .\setup.bat -type file - Set-Content .\setup.bat -Value "powershell.exe .\opensearch-${{ env.OPENSEARCH_VERSION }}-SNAPSHOT\plugins\${{ env.PLUGIN_NAME }}\tools\install_demo_configuration.bat -i -c -y" + Set-Content .\setup.bat -Value "powershell.exe .\opensearch-${{ env.OPENSEARCH_VERSION }}-SNAPSHOT\plugins\${{ env.PLUGIN_NAME }}\tools\install_demo_configuration.bat -i -c -y -t" Get-Content .\setup.bat - name: Run Opensearch with A Single Plugin From 729a65dbb9aee7e5d6f2d0d68effe66e8c1e05a5 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Wed, 8 Nov 2023 15:10:06 -0500 Subject: [PATCH 12/27] Fixes the tool to address issue when running on Windows Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 62 +++++++++++-------- 1 file changed, 35 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 7dea2b91cc..40a9f6aaa0 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -11,11 +11,8 @@ package org.opensearch.security.tools; -import org.opensearch.common.settings.Settings; -import org.opensearch.security.dlic.rest.validation.PasswordValidator; -import org.opensearch.security.dlic.rest.validation.RequestContentValidator; - import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; @@ -28,6 +25,10 @@ import java.util.Scanner; import java.util.Set; +import org.opensearch.common.settings.Settings; +import org.opensearch.security.dlic.rest.validation.PasswordValidator; +import org.opensearch.security.dlic.rest.validation.RequestContentValidator; + import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_MIN_LENGTH; import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX; import static org.opensearch.security.user.UserService.generatePassword; @@ -340,29 +341,33 @@ private static void setAdminPassword() { System.exit(-1); } - File tempFile = new File(INTERNAL_USERS_FILE_PATH + ".tmp"); - BufferedReader reader = new BufferedReader(new FileReader(INTERNAL_USERS_FILE_PATH)); - FileWriter writer = new FileWriter(tempFile); + Path tempFilePath = Paths.get(INTERNAL_USERS_FILE_PATH + ".tmp"); + Path internalUsersPath = Paths.get(INTERNAL_USERS_FILE_PATH); - String line; - while ((line = reader.readLine()) != null) { - if (line.matches(" *hash: *\"\\$2a\\$12\\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"")) { - line = line.replace( - "\"$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"", - "\"" + hashedAdminPassword + "\"" - ); + try ( + BufferedReader reader = new BufferedReader(new FileReader(INTERNAL_USERS_FILE_PATH)); + BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath.toFile())) + ) { + String line; + while ((line = reader.readLine()) != null) { + if (line.matches(" *hash: *\"\\$2a\\$12\\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"")) { + line = line.replace( + "\"$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"", + "\"" + hashedAdminPassword + "\"" + ); + } + writer.write(line + System.lineSeparator()); } - writer.write(line + System.lineSeparator()); } - reader.close(); - writer.close(); - - if (!tempFile.renameTo(new File(INTERNAL_USERS_FILE_PATH))) { + try { + Files.move(tempFilePath, internalUsersPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { throw new IOException("Unable to update the internal users file with the hashed password."); } } catch (IOException e) { + System.out.println("Exception: " + e.getMessage()); System.exit(-1); } } @@ -491,14 +496,17 @@ private static void runSecurityAdminCommands() { createSecurityAdminDemoScript(securityAdminScriptPath, securityAdminDemoScriptPath); // Make securityadmin_demo script executable - Path file = Paths.get(securityAdminDemoScriptPath); - Set perms = new HashSet<>(); - // Add the execute permission for owner, group, and others - perms.add(PosixFilePermission.OWNER_READ); - perms.add(PosixFilePermission.OWNER_EXECUTE); - perms.add(PosixFilePermission.GROUP_EXECUTE); - perms.add(PosixFilePermission.OTHERS_EXECUTE); - Files.setPosixFilePermissions(file, perms); + // not needed for windows + if (!System.getProperty("os.name").toLowerCase().contains("win")) { + Path file = Paths.get(securityAdminDemoScriptPath); + Set perms = new HashSet<>(); + // Add the execute permission for owner, group, and others + perms.add(PosixFilePermission.OWNER_READ); + perms.add(PosixFilePermission.OWNER_EXECUTE); + perms.add(PosixFilePermission.GROUP_EXECUTE); + perms.add(PosixFilePermission.OTHERS_EXECUTE); + Files.setPosixFilePermissions(file, perms); + } // Read the last line of the security-admin script String lastLine = ""; From 7771f162c2a45063c86bfbc0b94109f751153ee3 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Wed, 8 Nov 2023 15:23:20 -0500 Subject: [PATCH 13/27] Makes minor modifications around os name usage Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 57 +++++++++---------- 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 40a9f6aaa0..3d27b25e7f 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -34,26 +34,31 @@ import static org.opensearch.security.user.UserService.generatePassword; public final class InstallDemoConfiguration { - static boolean assumeyes = false; - static boolean initsecurity = false; - static boolean cluster_mode = false; - static boolean skip_updates = true; - - static ExecutionEnvironment environment = ExecutionEnvironment.production; - static String SCRIPT_DIR; - static String BASE_DIR; - static String OPENSEARCH_CONF_FILE; - static String OPENSEARCH_BIN_DIR; - static String OPENSEARCH_PLUGINS_DIR; - static String OPENSEARCH_MODULES_DIR; - static String OPENSEARCH_LIB_PATH; - static String OPENSEARCH_INSTALL_TYPE; - static String OPENSEARCH_CONF_DIR; - static String OPENSEARCH_VERSION; - static String SECURITY_VERSION; - static String OS; - - private static final String FILE_EXTENSION = System.getProperty("os.name").toLowerCase().contains("win") ? ".bat" : ".sh"; + private static boolean assumeyes = false; + private static boolean initsecurity = false; + private static boolean cluster_mode = false; + private static boolean skip_updates = true; + private static String SCRIPT_DIR; + private static String BASE_DIR; + private static String OPENSEARCH_CONF_FILE; + private static String OPENSEARCH_BIN_DIR; + private static String OPENSEARCH_PLUGINS_DIR; + private static String OPENSEARCH_MODULES_DIR; + private static String OPENSEARCH_LIB_PATH; + private static String OPENSEARCH_INSTALL_TYPE; + private static String OPENSEARCH_CONF_DIR; + private static String OPENSEARCH_VERSION; + private static String SECURITY_VERSION; + + private static ExecutionEnvironment environment = ExecutionEnvironment.production; + + private static final String OS = System.getProperty("os.name") + + " " + + System.getProperty("os.version") + + " " + + System.getProperty("os.arch"); + + private static final String FILE_EXTENSION = OS.toLowerCase().contains("win") ? ".bat" : ".sh"; private static final String SYSTEM_INDICES = ".plugins-ml-config, .plugins-ml-connector, .plugins-ml-model-group, .plugins-ml-model, " + ".plugins-ml-task, .plugins-ml-conversation-meta, .plugins-ml-conversation-interactions, .opendistro-alerting-config, .opendistro-alerting-alert*, " @@ -209,9 +214,8 @@ private static void setOpenSearchVariables() { } private static String determineInstallType() { - String os = System.getProperty("os.name").toLowerCase(); // windows (.bat execution) - if (os.contains("win")) { + if (OS.toLowerCase().contains("win")) { return ".zip"; } @@ -249,11 +253,6 @@ private static void setSecurityVariables() { SECURITY_VERSION = securityFiles[0].getName().replaceAll("opensearch-security-(.*).jar", "$1"); } - // Detect OS information - String osName = System.getProperty("os.name"); - String osVersion = System.getProperty("os.version"); - String osArch = System.getProperty("os.arch"); - OS = osName + " " + osVersion + " " + osArch; } private static void printVariables() { @@ -497,7 +496,7 @@ private static void runSecurityAdminCommands() { // Make securityadmin_demo script executable // not needed for windows - if (!System.getProperty("os.name").toLowerCase().contains("win")) { + if (!OS.toLowerCase().contains("win")) { Path file = Paths.get(securityAdminDemoScriptPath); Set perms = new HashSet<>(); // Add the execute permission for owner, group, and others @@ -567,7 +566,7 @@ private static void createSecurityAdminDemoScript(String securityAdminScriptPath + DemoCertificate.ROOT_CA.getFileName() + "\" -nhnv"; - if (System.getProperty("os.name").toLowerCase().contains("win")) { + if (OS.toLowerCase().contains("win")) { securityAdminCommands = new String[] { "@echo off", "call \"" + securityAdminExecutionPath }; } else { securityAdminCommands = new String[] { "#!/bin/bash", "sudo" + " \"" + securityAdminExecutionPath }; From d0e645901ecd222768257f4045c510a826526143 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Wed, 8 Nov 2023 20:53:28 -0500 Subject: [PATCH 14/27] Adds javadoc and change execution environment value keyword from production to demo Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 138 +++++++++++++++--- 1 file changed, 118 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 3d27b25e7f..d9f380ff12 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -33,6 +33,9 @@ import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX; import static org.opensearch.security.user.UserService.generatePassword; +/** + * This standalone class installs demo security configuration + */ public final class InstallDemoConfiguration { private static boolean assumeyes = false; private static boolean initsecurity = false; @@ -43,14 +46,13 @@ public final class InstallDemoConfiguration { private static String OPENSEARCH_CONF_FILE; private static String OPENSEARCH_BIN_DIR; private static String OPENSEARCH_PLUGINS_DIR; - private static String OPENSEARCH_MODULES_DIR; private static String OPENSEARCH_LIB_PATH; private static String OPENSEARCH_INSTALL_TYPE; private static String OPENSEARCH_CONF_DIR; private static String OPENSEARCH_VERSION; private static String SECURITY_VERSION; - private static ExecutionEnvironment environment = ExecutionEnvironment.production; + private static ExecutionEnvironment environment = ExecutionEnvironment.demo; private static final String OS = System.getProperty("os.name") + " " @@ -66,9 +68,14 @@ public final class InstallDemoConfiguration { + ".opendistro-reports-*, .opensearch-notifications-*, .opensearch-notebooks, .opensearch-observability, .ql-datasources, " + ".opendistro-asynchronous-search-response*, .replication-metadata-store, .opensearch-knn-models, .geospatial-ip2geo-data*"; - public static void main(String[] args) { + /** + * Main method that coordinates the execution of various security-related tasks. + * + * @param options the options passed to the script + */ + public static void main(String[] options) { printScriptHeaders(); - readArguments(args); + readOptions(options); gatherUserInputs(); initializeVariables(); printVariables(); @@ -76,9 +83,12 @@ public static void main(String[] args) { setAdminPassword(); createDemoCertificates(); writeSecurityConfigToOpenSearchYML(); - runSecurityAdminCommands(); + finishScriptExecution(); } + /** + * Prints deprecation warning and other headers for the scrip + */ private static void printScriptHeaders() { System.out.println("**************************************************************************"); System.out.println("** This tool will be deprecated in the next major release of OpenSearch **"); @@ -89,12 +99,16 @@ private static void printScriptHeaders() { System.out.println("** Warning: Do not use on production or public reachable systems **"); } - private static void readArguments(String[] args) { + /** + * Reads the options passed to the script + * @param options an array of strings containing options passed to the script + */ + private static void readOptions(String[] options) { // set script execution dir - SCRIPT_DIR = args[0]; + SCRIPT_DIR = options[0]; - for (int i = 1; i < args.length; i++) { - switch (args[i]) { + for (int i = 1; i < options.length; i++) { + switch (options[i]) { case "-y": assumeyes = true; break; @@ -115,11 +129,14 @@ private static void readArguments(String[] args) { showHelp(); return; default: - System.out.println("Invalid option: " + args[i]); + System.out.println("Invalid option: " + options[i]); } } } + /** + * Prints the help menu when -h option is passed + */ private static void showHelp() { System.out.println("install_demo_configuration.sh [-y] [-i] [-c]"); System.out.println(" -h show help"); @@ -128,13 +145,18 @@ private static void showHelp() { System.out.println(" -c enable cluster mode by binding to all network interfaces (default is to ask if -y is not given)"); System.out.println(" -s skip updates if config is already applied to opensearch.yml"); System.out.println( - " -t set the execution environment to `test` to skip password validation. Should be used only for testing. (default is set to `production`)" + " -t set the execution environment to `test` to skip password validation. Should be used only for testing. (default is set to `demo`)" ); } + /** + * Prompt the user and collect user inputs + * Input collection will be skipped if -y option was passed + */ private static void gatherUserInputs() { - try (Scanner scanner = new Scanner(System.in)) { - if (!assumeyes) { + if (!assumeyes) { + try (Scanner scanner = new Scanner(System.in)) { + if (!confirmAction(scanner, "Install demo certificates?")) { System.exit(0); } @@ -152,18 +174,30 @@ private static void gatherUserInputs() { } } + /** + * Helper method to scan user inputs. + * @param scanner object to be used for scanning user input + * @param message prompt question + * @return true or false based on user input + */ private static boolean confirmAction(Scanner scanner, String message) { System.out.print(message + " [y/N] "); String response = scanner.nextLine(); return response.equalsIgnoreCase("yes") || response.equalsIgnoreCase("y"); } + /** + * Initialize all class level variables required + */ private static void initializeVariables() { setBaseDir(); setOpenSearchVariables(); setSecurityVariables(); } + /** + * Sets the base directory to be used by the script + */ private static void setBaseDir() { File baseDirFile = new File(SCRIPT_DIR).getParentFile().getParentFile().getParentFile(); BASE_DIR = baseDirFile != null ? baseDirFile.getAbsolutePath() : null; @@ -176,11 +210,14 @@ private static void setBaseDir() { BASE_DIR += File.separator; } + /** + * Sets the variables for items at OpenSearch level + */ private static void setOpenSearchVariables() { OPENSEARCH_CONF_FILE = BASE_DIR + "config" + File.separator + "opensearch.yml"; OPENSEARCH_BIN_DIR = BASE_DIR + "bin" + File.separator; OPENSEARCH_PLUGINS_DIR = BASE_DIR + "plugins" + File.separator; - OPENSEARCH_MODULES_DIR = BASE_DIR + "modules" + File.separator; + String OPENSEARCH_MODULES_DIR = BASE_DIR + "modules" + File.separator; OPENSEARCH_LIB_PATH = BASE_DIR + "lib" + File.separator; OPENSEARCH_INSTALL_TYPE = determineInstallType(); @@ -213,6 +250,10 @@ private static void setOpenSearchVariables() { OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_DIR).getAbsolutePath() + File.separator; } + /** + * Returns the installation type based on the underlying operating system + * @return will be one of `.zip`, `.tar.gz` or `rpm/deb` + */ private static String determineInstallType() { // windows (.bat execution) if (OS.toLowerCase().contains("win")) { @@ -230,6 +271,9 @@ private static String determineInstallType() { return ".tar.gz"; } + /** + * Sets the path variables for items at OpenSearch security plugin level + */ private static void setSecurityVariables() { if (!(new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").exists())) { System.out.println("OpenSearch Security plugin not installed. Quit."); @@ -255,6 +299,9 @@ private static void setSecurityVariables() { } + /** + * Prints the initialized variables + */ private static void printVariables() { System.out.println("OpenSearch install type: " + OPENSEARCH_INSTALL_TYPE + " on " + OS); System.out.println("OpenSearch config dir: " + OPENSEARCH_CONF_DIR); @@ -266,6 +313,9 @@ private static void printVariables() { System.out.println("Detected OpenSearch Security Version: " + SECURITY_VERSION); } + /** + * Checks if security plugin is already configured. If so, the script execution will not continue. + */ private static void checkIfSecurityPluginIsAlreadyConfigured() { // Check if the configuration file contains the 'plugins.security' string if (OPENSEARCH_CONF_FILE != null && new File(OPENSEARCH_CONF_FILE).exists()) { @@ -284,12 +334,15 @@ private static void checkIfSecurityPluginIsAlreadyConfigured() { } } + /** + * Replaces the admin password in internal_users.yml with the custom or generated password + */ private static void setAdminPassword() { String ADMIN_PASSWORD = ""; String initialAdminPassword = System.getenv("initialAdminPassword"); String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; String INTERNAL_USERS_FILE_PATH = OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; - boolean shouldValidatePassword = environment.equals(ExecutionEnvironment.production); + boolean shouldValidatePassword = environment.equals(ExecutionEnvironment.demo); try { final PasswordValidator passwordValidator = PasswordValidator.of( Settings.builder() @@ -310,7 +363,7 @@ private static void setAdminPassword() { } } - // If script execution environment is set to production, validate custom password, else if set to test, skip validation + // If script execution environment is set to demo, validate custom password, else if set to test, skip validation if (shouldValidatePassword && !ADMIN_PASSWORD.isEmpty() && passwordValidator.validate("admin", ADMIN_PASSWORD) != RequestContentValidator.ValidationError.NONE) { @@ -371,6 +424,9 @@ private static void setAdminPassword() { } } + /** + * Creates demo super-admin, node and root certificates + */ public static void createDemoCertificates() { for (DemoCertificate cert : DemoCertificate.values()) { String filePath = OPENSEARCH_CONF_DIR + File.separator + cert.getFileName(); @@ -385,6 +441,10 @@ public static void createDemoCertificates() { } } + /** + * Set permission to given file + * @param filePath the path to the file whose permissions need to be set + */ private static void setFilePermissions(String filePath) { try { File file = new File(filePath); @@ -393,10 +453,12 @@ private static void setFilePermissions(String filePath) { } } catch (IOException e) { System.err.println("Error setting file permissions for: " + filePath); - } } + /** + * Update opensearch.yml with security configuration information + */ private static void writeSecurityConfigToOpenSearchYML() { String securityConfig = buildSecurityConfigString(); @@ -405,6 +467,10 @@ private static void writeSecurityConfigToOpenSearchYML() { } catch (IOException e) {} } + /** + * Helper method to build security configuration to append to opensearch.yml + * @return the configuration string to be written to opensearch.yml + */ private static String buildSecurityConfigString() { StringBuilder securityConfigLines = new StringBuilder(); @@ -448,6 +514,11 @@ private static String buildSecurityConfigString() { return securityConfigLines.toString(); } + /** + * Helper method to check if network.host config is present + * @param filePath path to opensearch.yml + * @return true is present, false otherwise + */ private static boolean isNetworkHostAlreadyPresent(String filePath) { try { String searchString = "^network.host"; @@ -457,6 +528,11 @@ private static boolean isNetworkHostAlreadyPresent(String filePath) { } } + /** + * Helper method to check if node.max_local_storage_nodes config is present + * @param filePath path to opensearch.yml + * @return true if present, false otherwise + */ private static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) { try { String searchString = "^node.max_local_storage_nodes"; @@ -466,6 +542,13 @@ private static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) } } + /** + * Checks if given string is already present in the file + * @param filePath path to file in which given string should be searched + * @param searchString the string to be searched for + * @return true if string is present, false otherwise + * @throws IOException if there was exception reading the file + */ private static boolean isStringAlreadyPresentInFile(String filePath, String searchString) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; @@ -478,7 +561,10 @@ private static boolean isStringAlreadyPresentInFile(String filePath, String sear return false; } - private static void runSecurityAdminCommands() { + /** + * Prints end of script execution message and creates security admin demo file. + */ + private static void finishScriptExecution() { System.out.println("### Success"); System.out.println("### Execute this script now on all your nodes and then start all nodes"); @@ -548,6 +634,12 @@ private static void runSecurityAdminCommands() { } } + /** + * Helper method to create security_admin_demo.(sh|bat) + * @param securityAdminScriptPath path to original script + * @param securityAdminDemoScriptPath path to security admin demo script + * @throws IOException if there was error reading/writing the file + */ private static void createSecurityAdminDemoScript(String securityAdminScriptPath, String securityAdminDemoScriptPath) throws IOException { String[] securityAdminCommands; @@ -581,6 +673,9 @@ private static void createSecurityAdminDemoScript(String securityAdminScriptPath } } +/** + * Enum for demo certificates + */ enum DemoCertificate { ADMIN_CERT( "kirk.pem", @@ -751,7 +846,10 @@ public String getContent() { } } +/** + * The environment in which the script is being executed + */ enum ExecutionEnvironment { - production, - test; + demo, // default value + test; // to be used only for tests } From af7585cab198bcd528e9434662843e6e964cec50 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Thu, 9 Nov 2023 01:30:50 -0500 Subject: [PATCH 15/27] Breaks admin password setter into two methods Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 98 +++++++++---------- 1 file changed, 48 insertions(+), 50 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index d9f380ff12..5a0f167337 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -327,9 +327,12 @@ private static void checkIfSecurityPluginIsAlreadyConfigured() { System.exit(skip_updates ? 1 : 0); } } - } catch (IOException e) {} + } catch (IOException e) { + System.err.println("Error reading configuration file."); + System.exit(-1); + } } else { - System.out.println("OpenSearch configuration file does not exist. Quit."); + System.err.println("OpenSearch configuration file does not exist. Quit."); System.exit(-1); } } @@ -386,41 +389,48 @@ private static void setAdminPassword() { System.out.println("\t\tADMIN PASSWORD SET TO: " + ADMIN_PASSWORD); System.out.println("\t***************************************************"); - String hashedAdminPassword = Hasher.hash(ADMIN_PASSWORD.toCharArray()); + writePasswordToInternalUsersFile(ADMIN_PASSWORD, INTERNAL_USERS_FILE_PATH); - if (hashedAdminPassword.isEmpty()) { - System.out.println("Hash the admin password failure, see console for details"); - System.exit(-1); - } + } catch (IOException e) { + System.out.println("Exception: " + e.getMessage()); + System.exit(-1); + } + } - Path tempFilePath = Paths.get(INTERNAL_USERS_FILE_PATH + ".tmp"); - Path internalUsersPath = Paths.get(INTERNAL_USERS_FILE_PATH); + /** + * Generate password hash and update it in the internal_users.yml file + * @param adminPassword the password to be hashed and updated + * @param internalUsersFile the file path string to internal_users.yml file + * @throws IOException while reading, writing to files + */ + private static void writePasswordToInternalUsersFile(String adminPassword, String internalUsersFile) throws IOException { + String hashedAdminPassword = Hasher.hash(adminPassword.toCharArray()); - try ( - BufferedReader reader = new BufferedReader(new FileReader(INTERNAL_USERS_FILE_PATH)); - BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath.toFile())) - ) { - String line; - while ((line = reader.readLine()) != null) { - if (line.matches(" *hash: *\"\\$2a\\$12\\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"")) { - line = line.replace( - "\"$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"", - "\"" + hashedAdminPassword + "\"" - ); - } - writer.write(line + System.lineSeparator()); - } - } + if (hashedAdminPassword.isEmpty()) { + System.out.println("Hash the admin password failure, see console for details"); + System.exit(-1); + } - try { - Files.move(tempFilePath, internalUsersPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - throw new IOException("Unable to update the internal users file with the hashed password."); - } + Path tempFilePath = Paths.get(internalUsersFile + ".tmp"); + Path internalUsersPath = Paths.get(internalUsersFile); + try ( + BufferedReader reader = new BufferedReader(new FileReader(internalUsersFile)); + BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath.toFile())) + ) { + String line; + while ((line = reader.readLine()) != null) { + if (line.matches(" *hash: *\"\\$2a\\$12\\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"")) { + line = line.replace( + "\"$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"", + "\"" + hashedAdminPassword + "\"" + ); + } + writer.write(line + System.lineSeparator()); + } + Files.move(tempFilePath, internalUsersPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { - System.out.println("Exception: " + e.getMessage()); - System.exit(-1); + throw new IOException("Unable to update the internal users file with the hashed password."); } } @@ -434,25 +444,10 @@ public static void createDemoCertificates() { FileWriter fileWriter = new FileWriter(filePath); fileWriter.write(cert.getContent()); fileWriter.close(); - setFilePermissions(filePath); } catch (IOException e) { - System.err.println("Error writing certificate to file: " + cert.getFileName()); - } - } - } - - /** - * Set permission to given file - * @param filePath the path to the file whose permissions need to be set - */ - private static void setFilePermissions(String filePath) { - try { - File file = new File(filePath); - if (!file.setReadable(true, false) || !file.setWritable(false, false) || !file.setExecutable(false, false)) { - throw new IOException("Failed to set file permissions for: " + filePath); + System.err.println("Error writing certificate file: " + cert.getFileName()); + System.exit(-1); } - } catch (IOException e) { - System.err.println("Error setting file permissions for: " + filePath); } } @@ -464,7 +459,10 @@ private static void writeSecurityConfigToOpenSearchYML() { try (FileWriter writer = new FileWriter(OPENSEARCH_CONF_FILE, true)) { writer.write(securityConfig); - } catch (IOException e) {} + } catch (IOException e) { + System.err.println("Exception writing security configuration to opensearch.yml."); + System.exit(-1); + } } /** @@ -851,5 +849,5 @@ public String getContent() { */ enum ExecutionEnvironment { demo, // default value - test; // to be used only for tests + test // to be used only for tests } From 5829e6800bd1d44218445e07ebf0325ddef1fb7d Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Thu, 9 Nov 2023 01:47:11 -0500 Subject: [PATCH 16/27] Fixes failures for windows Signed-off-by: Darshit Chanpura --- .../org/opensearch/security/tools/InstallDemoConfiguration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 5a0f167337..1d779cfeef 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -428,10 +428,10 @@ private static void writePasswordToInternalUsersFile(String adminPassword, Strin } writer.write(line + System.lineSeparator()); } - Files.move(tempFilePath, internalUsersPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new IOException("Unable to update the internal users file with the hashed password."); } + Files.move(tempFilePath, internalUsersPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING); } /** From 11f0218699e7f8f64f1fbc1f3fd4928d51568e28 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Thu, 9 Nov 2023 13:29:08 -0500 Subject: [PATCH 17/27] Fixes help method to exit when done displaying help Signed-off-by: Darshit Chanpura --- .../security/tools/InstallDemoConfiguration.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 1d779cfeef..e901c46934 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -40,7 +40,7 @@ public final class InstallDemoConfiguration { private static boolean assumeyes = false; private static boolean initsecurity = false; private static boolean cluster_mode = false; - private static boolean skip_updates = true; + private static int skip_updates = -1; private static String SCRIPT_DIR; private static String BASE_DIR; private static String OPENSEARCH_CONF_FILE; @@ -119,7 +119,7 @@ private static void readOptions(String[] options) { cluster_mode = true; break; case "-s": - skip_updates = false; + skip_updates = 0; break; case "-t": environment = ExecutionEnvironment.test; @@ -147,6 +147,7 @@ private static void showHelp() { System.out.println( " -t set the execution environment to `test` to skip password validation. Should be used only for testing. (default is set to `demo`)" ); + System.exit(0); } /** @@ -296,7 +297,6 @@ private static void setSecurityVariables() { if (securityFiles != null && securityFiles.length > 0) { SECURITY_VERSION = securityFiles[0].getName().replaceAll("opensearch-security-(.*).jar", "$1"); } - } /** @@ -324,7 +324,7 @@ private static void checkIfSecurityPluginIsAlreadyConfigured() { while ((line = br.readLine()) != null) { if (line.toLowerCase().contains("plugins.security")) { System.out.println(OPENSEARCH_CONF_FILE + " seems to be already configured for Security. Quit."); - System.exit(skip_updates ? 1 : 0); + System.exit(skip_updates); } } } catch (IOException e) { From 2f75836b7f06918110659dae46e0200886845977 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Fri, 10 Nov 2023 00:14:39 -0500 Subject: [PATCH 18/27] Fixes spotbugs errors Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index e901c46934..dcb488421d 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -17,6 +17,7 @@ import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -156,7 +157,7 @@ private static void showHelp() { */ private static void gatherUserInputs() { if (!assumeyes) { - try (Scanner scanner = new Scanner(System.in)) { + try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) { if (!confirmAction(scanner, "Install demo certificates?")) { System.exit(0); @@ -319,7 +320,7 @@ private static void printVariables() { private static void checkIfSecurityPluginIsAlreadyConfigured() { // Check if the configuration file contains the 'plugins.security' string if (OPENSEARCH_CONF_FILE != null && new File(OPENSEARCH_CONF_FILE).exists()) { - try (BufferedReader br = new BufferedReader(new FileReader(OPENSEARCH_CONF_FILE))) { + try (BufferedReader br = new BufferedReader(new FileReader(OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8))) { String line; while ((line = br.readLine()) != null) { if (line.toLowerCase().contains("plugins.security")) { @@ -360,7 +361,7 @@ private static void setAdminPassword() { } else { File adminPasswordFile = new File(ADMIN_PASSWORD_FILE_PATH); if (adminPasswordFile.exists() && adminPasswordFile.length() > 0) { - try (BufferedReader br = new BufferedReader(new FileReader(ADMIN_PASSWORD_FILE_PATH))) { + try (BufferedReader br = new BufferedReader(new FileReader(ADMIN_PASSWORD_FILE_PATH, StandardCharsets.UTF_8))) { ADMIN_PASSWORD = br.readLine(); } } @@ -415,8 +416,8 @@ private static void writePasswordToInternalUsersFile(String adminPassword, Strin Path internalUsersPath = Paths.get(internalUsersFile); try ( - BufferedReader reader = new BufferedReader(new FileReader(internalUsersFile)); - BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath.toFile())) + BufferedReader reader = new BufferedReader(new FileReader(internalUsersFile, StandardCharsets.UTF_8)); + BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath.toFile(), StandardCharsets.UTF_8)) ) { String line; while ((line = reader.readLine()) != null) { @@ -441,7 +442,7 @@ public static void createDemoCertificates() { for (DemoCertificate cert : DemoCertificate.values()) { String filePath = OPENSEARCH_CONF_DIR + File.separator + cert.getFileName(); try { - FileWriter fileWriter = new FileWriter(filePath); + FileWriter fileWriter = new FileWriter(filePath, StandardCharsets.UTF_8); fileWriter.write(cert.getContent()); fileWriter.close(); } catch (IOException e) { @@ -457,7 +458,7 @@ public static void createDemoCertificates() { private static void writeSecurityConfigToOpenSearchYML() { String securityConfig = buildSecurityConfigString(); - try (FileWriter writer = new FileWriter(OPENSEARCH_CONF_FILE, true)) { + try (FileWriter writer = new FileWriter(OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8, true)) { writer.write(securityConfig); } catch (IOException e) { System.err.println("Exception writing security configuration to opensearch.yml."); @@ -548,7 +549,7 @@ private static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) * @throws IOException if there was exception reading the file */ private static boolean isStringAlreadyPresentInFile(String filePath, String searchString) throws IOException { - try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + try (BufferedReader reader = new BufferedReader(new FileReader(filePath, StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.matches(searchString)) { @@ -593,7 +594,7 @@ private static void finishScriptExecution() { // Read the last line of the security-admin script String lastLine = ""; - try (BufferedReader reader = new BufferedReader(new FileReader(securityAdminDemoScriptPath))) { + try (BufferedReader reader = new BufferedReader(new FileReader(securityAdminDemoScriptPath, StandardCharsets.UTF_8))) { String currentLine; while ((currentLine = reader.readLine()) != null) { lastLine = currentLine; @@ -663,7 +664,7 @@ private static void createSecurityAdminDemoScript(String securityAdminScriptPath } // Write securityadmin_demo script - FileWriter writer = new FileWriter(securityAdminDemoScriptPath); + FileWriter writer = new FileWriter(securityAdminDemoScriptPath, StandardCharsets.UTF_8); for (String command : securityAdminCommands) { writer.write(command + "\n"); } From e1c7c089549c6f50f2bb2d383982f04cb982686c Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Fri, 10 Nov 2023 00:59:32 -0500 Subject: [PATCH 19/27] Fixes edge-case with assumeyes functionality Signed-off-by: Darshit Chanpura --- .../opensearch/security/tools/InstallDemoConfiguration.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index dcb488421d..76899846a7 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -39,6 +39,7 @@ */ public final class InstallDemoConfiguration { private static boolean assumeyes = false; + private static boolean installDemoCertificates = false; private static boolean initsecurity = false; private static boolean cluster_mode = false; private static int skip_updates = -1; @@ -173,6 +174,9 @@ private static void gatherUserInputs() { cluster_mode = confirmAction(scanner, "Enable cluster mode?"); } } + } else { + initsecurity = true; + cluster_mode = true; } } From 354e952109741b89400b1d406bdd2de1d4a88037 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 13 Nov 2023 11:54:55 -0500 Subject: [PATCH 20/27] Addresses some spelling errors Signed-off-by: Darshit Chanpura --- .../opensearch/security/tools/InstallDemoConfiguration.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java index 76899846a7..270d1ee0d6 100644 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java @@ -89,7 +89,7 @@ public static void main(String[] options) { } /** - * Prints deprecation warning and other headers for the scrip + * Prints deprecation warning and other headers for the script */ private static void printScriptHeaders() { System.out.println("**************************************************************************"); @@ -169,7 +169,7 @@ private static void gatherUserInputs() { } if (!cluster_mode) { - System.out.println("Cluster mode requires maybe additional setup of:"); + System.out.println("Cluster mode requires additional setup of:"); System.out.println(" - Virtual memory (vm.max_map_count)\n"); cluster_mode = confirmAction(scanner, "Enable cluster mode?"); } From ed760914d3697d5f3c88fa9fd9517ea6d2db076d Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 13 Nov 2023 13:04:06 -0500 Subject: [PATCH 21/27] Rewrites the java tool to be modular Signed-off-by: Darshit Chanpura --- .../tools/InstallDemoConfiguration.java | 858 ------------------ .../democonfig/CertificateGenerator.java | 49 + .../tools/democonfig/DemoCertificate.java | 174 ++++ .../democonfig/ExecutionEnvironment.java | 9 + .../democonfig/InstallDemoConfiguration.java | 377 ++++++++ .../democonfig/SecurityConfigurator.java | 316 +++++++ tools/install_demo_configuration.bat | 2 +- tools/install_demo_configuration.sh | 2 +- 8 files changed, 927 insertions(+), 860 deletions(-) delete mode 100644 src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java create mode 100644 src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java create mode 100644 src/main/java/org/opensearch/security/tools/democonfig/DemoCertificate.java create mode 100644 src/main/java/org/opensearch/security/tools/democonfig/ExecutionEnvironment.java create mode 100644 src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java create mode 100644 src/main/java/org/opensearch/security/tools/democonfig/SecurityConfigurator.java diff --git a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java deleted file mode 100644 index 270d1ee0d6..0000000000 --- a/src/main/java/org/opensearch/security/tools/InstallDemoConfiguration.java +++ /dev/null @@ -1,858 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * - * The OpenSearch Contributors require contributions made to - * this file be licensed under the Apache-2.0 license or a - * compatible open source license. - * - * Modifications Copyright OpenSearch Contributors. See - * GitHub history for details. - */ - -package org.opensearch.security.tools; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.attribute.PosixFilePermission; -import java.util.HashSet; -import java.util.Scanner; -import java.util.Set; - -import org.opensearch.common.settings.Settings; -import org.opensearch.security.dlic.rest.validation.PasswordValidator; -import org.opensearch.security.dlic.rest.validation.RequestContentValidator; - -import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_MIN_LENGTH; -import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX; -import static org.opensearch.security.user.UserService.generatePassword; - -/** - * This standalone class installs demo security configuration - */ -public final class InstallDemoConfiguration { - private static boolean assumeyes = false; - private static boolean installDemoCertificates = false; - private static boolean initsecurity = false; - private static boolean cluster_mode = false; - private static int skip_updates = -1; - private static String SCRIPT_DIR; - private static String BASE_DIR; - private static String OPENSEARCH_CONF_FILE; - private static String OPENSEARCH_BIN_DIR; - private static String OPENSEARCH_PLUGINS_DIR; - private static String OPENSEARCH_LIB_PATH; - private static String OPENSEARCH_INSTALL_TYPE; - private static String OPENSEARCH_CONF_DIR; - private static String OPENSEARCH_VERSION; - private static String SECURITY_VERSION; - - private static ExecutionEnvironment environment = ExecutionEnvironment.demo; - - private static final String OS = System.getProperty("os.name") - + " " - + System.getProperty("os.version") - + " " - + System.getProperty("os.arch"); - - private static final String FILE_EXTENSION = OS.toLowerCase().contains("win") ? ".bat" : ".sh"; - - private static final String SYSTEM_INDICES = ".plugins-ml-config, .plugins-ml-connector, .plugins-ml-model-group, .plugins-ml-model, " - + ".plugins-ml-task, .plugins-ml-conversation-meta, .plugins-ml-conversation-interactions, .opendistro-alerting-config, .opendistro-alerting-alert*, " - + ".opendistro-anomaly-results*, .opendistro-anomaly-detector*, .opendistro-anomaly-checkpoints, .opendistro-anomaly-detection-state, " - + ".opendistro-reports-*, .opensearch-notifications-*, .opensearch-notebooks, .opensearch-observability, .ql-datasources, " - + ".opendistro-asynchronous-search-response*, .replication-metadata-store, .opensearch-knn-models, .geospatial-ip2geo-data*"; - - /** - * Main method that coordinates the execution of various security-related tasks. - * - * @param options the options passed to the script - */ - public static void main(String[] options) { - printScriptHeaders(); - readOptions(options); - gatherUserInputs(); - initializeVariables(); - printVariables(); - checkIfSecurityPluginIsAlreadyConfigured(); - setAdminPassword(); - createDemoCertificates(); - writeSecurityConfigToOpenSearchYML(); - finishScriptExecution(); - } - - /** - * Prints deprecation warning and other headers for the script - */ - private static void printScriptHeaders() { - System.out.println("**************************************************************************"); - System.out.println("** This tool will be deprecated in the next major release of OpenSearch **"); - System.out.println("** https://github.com/opensearch-project/security/issues/1755 **"); - System.out.println("**************************************************************************"); - System.out.println("\n"); - System.out.println("OpenSearch Security Demo Installer"); - System.out.println("** Warning: Do not use on production or public reachable systems **"); - } - - /** - * Reads the options passed to the script - * @param options an array of strings containing options passed to the script - */ - private static void readOptions(String[] options) { - // set script execution dir - SCRIPT_DIR = options[0]; - - for (int i = 1; i < options.length; i++) { - switch (options[i]) { - case "-y": - assumeyes = true; - break; - case "-i": - initsecurity = true; - break; - case "-c": - cluster_mode = true; - break; - case "-s": - skip_updates = 0; - break; - case "-t": - environment = ExecutionEnvironment.test; - break; - case "-h": - case "-?": - showHelp(); - return; - default: - System.out.println("Invalid option: " + options[i]); - } - } - } - - /** - * Prints the help menu when -h option is passed - */ - private static void showHelp() { - System.out.println("install_demo_configuration.sh [-y] [-i] [-c]"); - System.out.println(" -h show help"); - System.out.println(" -y confirm all installation dialogues automatically"); - System.out.println(" -i initialize Security plugin with default configuration (default is to ask if -y is not given)"); - System.out.println(" -c enable cluster mode by binding to all network interfaces (default is to ask if -y is not given)"); - System.out.println(" -s skip updates if config is already applied to opensearch.yml"); - System.out.println( - " -t set the execution environment to `test` to skip password validation. Should be used only for testing. (default is set to `demo`)" - ); - System.exit(0); - } - - /** - * Prompt the user and collect user inputs - * Input collection will be skipped if -y option was passed - */ - private static void gatherUserInputs() { - if (!assumeyes) { - try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) { - - if (!confirmAction(scanner, "Install demo certificates?")) { - System.exit(0); - } - - if (!initsecurity) { - initsecurity = confirmAction(scanner, "Initialize Security Modules?"); - } - - if (!cluster_mode) { - System.out.println("Cluster mode requires additional setup of:"); - System.out.println(" - Virtual memory (vm.max_map_count)\n"); - cluster_mode = confirmAction(scanner, "Enable cluster mode?"); - } - } - } else { - initsecurity = true; - cluster_mode = true; - } - } - - /** - * Helper method to scan user inputs. - * @param scanner object to be used for scanning user input - * @param message prompt question - * @return true or false based on user input - */ - private static boolean confirmAction(Scanner scanner, String message) { - System.out.print(message + " [y/N] "); - String response = scanner.nextLine(); - return response.equalsIgnoreCase("yes") || response.equalsIgnoreCase("y"); - } - - /** - * Initialize all class level variables required - */ - private static void initializeVariables() { - setBaseDir(); - setOpenSearchVariables(); - setSecurityVariables(); - } - - /** - * Sets the base directory to be used by the script - */ - private static void setBaseDir() { - File baseDirFile = new File(SCRIPT_DIR).getParentFile().getParentFile().getParentFile(); - BASE_DIR = baseDirFile != null ? baseDirFile.getAbsolutePath() : null; - - if (BASE_DIR == null || !new File(BASE_DIR).isDirectory()) { - System.out.println("DEBUG: basedir does not exist"); - System.exit(-1); - } - - BASE_DIR += File.separator; - } - - /** - * Sets the variables for items at OpenSearch level - */ - private static void setOpenSearchVariables() { - OPENSEARCH_CONF_FILE = BASE_DIR + "config" + File.separator + "opensearch.yml"; - OPENSEARCH_BIN_DIR = BASE_DIR + "bin" + File.separator; - OPENSEARCH_PLUGINS_DIR = BASE_DIR + "plugins" + File.separator; - String OPENSEARCH_MODULES_DIR = BASE_DIR + "modules" + File.separator; - OPENSEARCH_LIB_PATH = BASE_DIR + "lib" + File.separator; - OPENSEARCH_INSTALL_TYPE = determineInstallType(); - - if (!(new File(OPENSEARCH_CONF_FILE).exists())) { - System.out.println("Unable to determine OpenSearch config directory. Quit."); - System.exit(-1); - } - - if (!(new File(OPENSEARCH_BIN_DIR).exists())) { - System.out.println("Unable to determine OpenSearch bin directory. Quit."); - System.exit(-1); - } - - if (!(new File(OPENSEARCH_PLUGINS_DIR).exists())) { - System.out.println("Unable to determine OpenSearch plugins directory. Quit."); - System.exit(-1); - } - - if (!(new File(OPENSEARCH_MODULES_DIR).exists())) { - System.out.println("Unable to determine OpenSearch modules directory. Quit."); - // System.exit(-1); - } - - if (!(new File(OPENSEARCH_LIB_PATH).exists())) { - System.out.println("Unable to determine OpenSearch lib directory. Quit."); - System.exit(-1); - } - - OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_FILE).getParent(); - OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_DIR).getAbsolutePath() + File.separator; - } - - /** - * Returns the installation type based on the underlying operating system - * @return will be one of `.zip`, `.tar.gz` or `rpm/deb` - */ - private static String determineInstallType() { - // windows (.bat execution) - if (OS.toLowerCase().contains("win")) { - return ".zip"; - } - - // other OS (.sh execution) - if (new File("/usr/share/opensearch").equals(new File(BASE_DIR))) { - OPENSEARCH_CONF_FILE = "/usr/share/opensearch/config/opensearch.yml"; - if (!new File(OPENSEARCH_CONF_FILE).exists()) { - OPENSEARCH_CONF_FILE = "/etc/opensearch/opensearch.yml"; - } - return "rpm/deb"; - } - return ".tar.gz"; - } - - /** - * Sets the path variables for items at OpenSearch security plugin level - */ - private static void setSecurityVariables() { - if (!(new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").exists())) { - System.out.println("OpenSearch Security plugin not installed. Quit."); - System.exit(-1); - } - - // Extract OpenSearch version and Security version - File[] opensearchLibFiles = new File(OPENSEARCH_LIB_PATH).listFiles( - pathname -> pathname.getName().startsWith("opensearch-") && pathname.getName().endsWith(".jar") - ); - - if (opensearchLibFiles != null && opensearchLibFiles.length > 0) { - OPENSEARCH_VERSION = opensearchLibFiles[0].getName().replaceAll("opensearch-(.*).jar", "$1"); - } - - File[] securityFiles = new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").listFiles( - pathname -> pathname.getName().startsWith("opensearch-security-") && pathname.getName().endsWith(".jar") - ); - - if (securityFiles != null && securityFiles.length > 0) { - SECURITY_VERSION = securityFiles[0].getName().replaceAll("opensearch-security-(.*).jar", "$1"); - } - } - - /** - * Prints the initialized variables - */ - private static void printVariables() { - System.out.println("OpenSearch install type: " + OPENSEARCH_INSTALL_TYPE + " on " + OS); - System.out.println("OpenSearch config dir: " + OPENSEARCH_CONF_DIR); - System.out.println("OpenSearch config file: " + OPENSEARCH_CONF_FILE); - System.out.println("OpenSearch bin dir: " + OPENSEARCH_BIN_DIR); - System.out.println("OpenSearch plugins dir: " + OPENSEARCH_PLUGINS_DIR); - System.out.println("OpenSearch lib dir: " + OPENSEARCH_LIB_PATH); - System.out.println("Detected OpenSearch Version: " + OPENSEARCH_VERSION); - System.out.println("Detected OpenSearch Security Version: " + SECURITY_VERSION); - } - - /** - * Checks if security plugin is already configured. If so, the script execution will not continue. - */ - private static void checkIfSecurityPluginIsAlreadyConfigured() { - // Check if the configuration file contains the 'plugins.security' string - if (OPENSEARCH_CONF_FILE != null && new File(OPENSEARCH_CONF_FILE).exists()) { - try (BufferedReader br = new BufferedReader(new FileReader(OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8))) { - String line; - while ((line = br.readLine()) != null) { - if (line.toLowerCase().contains("plugins.security")) { - System.out.println(OPENSEARCH_CONF_FILE + " seems to be already configured for Security. Quit."); - System.exit(skip_updates); - } - } - } catch (IOException e) { - System.err.println("Error reading configuration file."); - System.exit(-1); - } - } else { - System.err.println("OpenSearch configuration file does not exist. Quit."); - System.exit(-1); - } - } - - /** - * Replaces the admin password in internal_users.yml with the custom or generated password - */ - private static void setAdminPassword() { - String ADMIN_PASSWORD = ""; - String initialAdminPassword = System.getenv("initialAdminPassword"); - String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; - String INTERNAL_USERS_FILE_PATH = OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; - boolean shouldValidatePassword = environment.equals(ExecutionEnvironment.demo); - try { - final PasswordValidator passwordValidator = PasswordValidator.of( - Settings.builder() - .put(SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX, "(?=.*[A-Z])(?=.*[^a-zA-Z\\\\d])(?=.*[0-9])(?=.*[a-z]).{8,}") - .put(SECURITY_RESTAPI_PASSWORD_MIN_LENGTH, 8) - .build() - ); - - // Read custom password - if (initialAdminPassword != null && !initialAdminPassword.isEmpty()) { - ADMIN_PASSWORD = initialAdminPassword; - } else { - File adminPasswordFile = new File(ADMIN_PASSWORD_FILE_PATH); - if (adminPasswordFile.exists() && adminPasswordFile.length() > 0) { - try (BufferedReader br = new BufferedReader(new FileReader(ADMIN_PASSWORD_FILE_PATH, StandardCharsets.UTF_8))) { - ADMIN_PASSWORD = br.readLine(); - } - } - } - - // If script execution environment is set to demo, validate custom password, else if set to test, skip validation - if (shouldValidatePassword - && !ADMIN_PASSWORD.isEmpty() - && passwordValidator.validate("admin", ADMIN_PASSWORD) != RequestContentValidator.ValidationError.NONE) { - System.out.println("Password " + ADMIN_PASSWORD + " is weak. Please re-try with a stronger password."); - System.exit(-1); - } - - // if ADMIN_PASSWORD is still an empty string, it implies no custom password was provided. We proceed with generating a new one. - if (ADMIN_PASSWORD.isEmpty()) { - System.out.println("No custom admin password found. Generating a new password now."); - // generate a new random password - // We always validate a generated password - while (passwordValidator.validate("admin", ADMIN_PASSWORD) != RequestContentValidator.ValidationError.NONE) { - ADMIN_PASSWORD = generatePassword(); - } - } - - // print the password to the logs - System.out.println("\t***************************************************"); - System.out.println("\t\tADMIN PASSWORD SET TO: " + ADMIN_PASSWORD); - System.out.println("\t***************************************************"); - - writePasswordToInternalUsersFile(ADMIN_PASSWORD, INTERNAL_USERS_FILE_PATH); - - } catch (IOException e) { - System.out.println("Exception: " + e.getMessage()); - System.exit(-1); - } - } - - /** - * Generate password hash and update it in the internal_users.yml file - * @param adminPassword the password to be hashed and updated - * @param internalUsersFile the file path string to internal_users.yml file - * @throws IOException while reading, writing to files - */ - private static void writePasswordToInternalUsersFile(String adminPassword, String internalUsersFile) throws IOException { - String hashedAdminPassword = Hasher.hash(adminPassword.toCharArray()); - - if (hashedAdminPassword.isEmpty()) { - System.out.println("Hash the admin password failure, see console for details"); - System.exit(-1); - } - - Path tempFilePath = Paths.get(internalUsersFile + ".tmp"); - Path internalUsersPath = Paths.get(internalUsersFile); - - try ( - BufferedReader reader = new BufferedReader(new FileReader(internalUsersFile, StandardCharsets.UTF_8)); - BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath.toFile(), StandardCharsets.UTF_8)) - ) { - String line; - while ((line = reader.readLine()) != null) { - if (line.matches(" *hash: *\"\\$2a\\$12\\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"")) { - line = line.replace( - "\"$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"", - "\"" + hashedAdminPassword + "\"" - ); - } - writer.write(line + System.lineSeparator()); - } - } catch (IOException e) { - throw new IOException("Unable to update the internal users file with the hashed password."); - } - Files.move(tempFilePath, internalUsersPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING); - } - - /** - * Creates demo super-admin, node and root certificates - */ - public static void createDemoCertificates() { - for (DemoCertificate cert : DemoCertificate.values()) { - String filePath = OPENSEARCH_CONF_DIR + File.separator + cert.getFileName(); - try { - FileWriter fileWriter = new FileWriter(filePath, StandardCharsets.UTF_8); - fileWriter.write(cert.getContent()); - fileWriter.close(); - } catch (IOException e) { - System.err.println("Error writing certificate file: " + cert.getFileName()); - System.exit(-1); - } - } - } - - /** - * Update opensearch.yml with security configuration information - */ - private static void writeSecurityConfigToOpenSearchYML() { - String securityConfig = buildSecurityConfigString(); - - try (FileWriter writer = new FileWriter(OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8, true)) { - writer.write(securityConfig); - } catch (IOException e) { - System.err.println("Exception writing security configuration to opensearch.yml."); - System.exit(-1); - } - } - - /** - * Helper method to build security configuration to append to opensearch.yml - * @return the configuration string to be written to opensearch.yml - */ - private static String buildSecurityConfigString() { - StringBuilder securityConfigLines = new StringBuilder(); - - securityConfigLines.append("\n") - .append("######## Start OpenSearch Security Demo Configuration ########\n") - .append("# WARNING: revise all the lines below before you go into production\n") - .append("plugins.security.ssl.transport.pemcert_filepath: esnode.pem\n") - .append("plugins.security.ssl.transport.pemkey_filepath: esnode-key.pem\n") - .append("plugins.security.ssl.transport.pemtrustedcas_filepath: root-ca.pem\n") - .append("plugins.security.ssl.transport.enforce_hostname_verification: false\n") - .append("plugins.security.ssl.http.enabled: true\n") - .append("plugins.security.ssl.http.pemcert_filepath: esnode.pem\n") - .append("plugins.security.ssl.http.pemkey_filepath: esnode-key.pem\n") - .append("plugins.security.ssl.http.pemtrustedcas_filepath: root-ca.pem\n") - .append("plugins.security.allow_unsafe_democertificates: true\n"); - - if (initsecurity) { - securityConfigLines.append("plugins.security.allow_default_init_securityindex: true\n"); - } - - securityConfigLines.append("plugins.security.authcz.admin_dn:\n - CN=kirk,OU=client,O=client,L=test, C=de\n\n"); - - securityConfigLines.append("plugins.security.system_indices.enabled: true\n" + "plugins.security.system_indices.indices: [") - .append(SYSTEM_INDICES) - .append("]\n"); - - if (!isNetworkHostAlreadyPresent(OPENSEARCH_CONF_FILE)) { - if (cluster_mode) { - securityConfigLines.append("network.host: 0.0.0.0\n"); - securityConfigLines.append("node.name: smoketestnode\n"); - securityConfigLines.append("cluster.initial_cluster_manager_nodes: smoketestnode\n"); - } - } - - if (!isNodeMaxLocalStorageNodesAlreadyPresent(OPENSEARCH_CONF_FILE)) { - securityConfigLines.append("node.max_local_storage_nodes: 3\n"); - } - - securityConfigLines.append("######## End OpenSearch Security Demo Configuration ########\n"); - - return securityConfigLines.toString(); - } - - /** - * Helper method to check if network.host config is present - * @param filePath path to opensearch.yml - * @return true is present, false otherwise - */ - private static boolean isNetworkHostAlreadyPresent(String filePath) { - try { - String searchString = "^network.host"; - return isStringAlreadyPresentInFile(filePath, searchString); - } catch (IOException e) { - return false; - } - } - - /** - * Helper method to check if node.max_local_storage_nodes config is present - * @param filePath path to opensearch.yml - * @return true if present, false otherwise - */ - private static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) { - try { - String searchString = "^node.max_local_storage_nodes"; - return isStringAlreadyPresentInFile(filePath, searchString); - } catch (IOException e) { - return false; - } - } - - /** - * Checks if given string is already present in the file - * @param filePath path to file in which given string should be searched - * @param searchString the string to be searched for - * @return true if string is present, false otherwise - * @throws IOException if there was exception reading the file - */ - private static boolean isStringAlreadyPresentInFile(String filePath, String searchString) throws IOException { - try (BufferedReader reader = new BufferedReader(new FileReader(filePath, StandardCharsets.UTF_8))) { - String line; - while ((line = reader.readLine()) != null) { - if (line.matches(searchString)) { - return true; - } - } - } - return false; - } - - /** - * Prints end of script execution message and creates security admin demo file. - */ - private static void finishScriptExecution() { - System.out.println("### Success"); - System.out.println("### Execute this script now on all your nodes and then start all nodes"); - - try { - String securityAdminScriptPath = OPENSEARCH_PLUGINS_DIR - + "opensearch-security" - + File.separator - + "tools" - + File.separator - + "securityadmin" - + FILE_EXTENSION; - String securityAdminDemoScriptPath = OPENSEARCH_CONF_DIR + "securityadmin_demo" + FILE_EXTENSION; - - createSecurityAdminDemoScript(securityAdminScriptPath, securityAdminDemoScriptPath); - - // Make securityadmin_demo script executable - // not needed for windows - if (!OS.toLowerCase().contains("win")) { - Path file = Paths.get(securityAdminDemoScriptPath); - Set perms = new HashSet<>(); - // Add the execute permission for owner, group, and others - perms.add(PosixFilePermission.OWNER_READ); - perms.add(PosixFilePermission.OWNER_EXECUTE); - perms.add(PosixFilePermission.GROUP_EXECUTE); - perms.add(PosixFilePermission.OTHERS_EXECUTE); - Files.setPosixFilePermissions(file, perms); - } - - // Read the last line of the security-admin script - String lastLine = ""; - try (BufferedReader reader = new BufferedReader(new FileReader(securityAdminDemoScriptPath, StandardCharsets.UTF_8))) { - String currentLine; - while ((currentLine = reader.readLine()) != null) { - lastLine = currentLine; - } - } - - if (!initsecurity) { - System.out.println("### After the whole cluster is up execute: "); - System.out.println(lastLine); - System.out.println("### or run ." + File.separator + "securityadmin_demo" + FILE_EXTENSION); - System.out.println("### After that you can also use the Security Plugin ConfigurationGUI"); - } else { - System.out.println("### OpenSearch Security will be automatically initialized."); - System.out.println("### If you like to change the runtime configuration "); - System.out.println( - "### change the files in .." - + File.separator - + ".." - + File.separator - + ".." - + File.separator - + "config" - + File.separator - + "opensearch-security and execute: " - ); - System.out.println(lastLine); - System.out.println("### or run ." + File.separator + "securityadmin_demo" + FILE_EXTENSION); - System.out.println("### To use the Security Plugin ConfigurationGUI"); - } - - System.out.println("### To access your secured cluster open https://: and log in with admin/admin."); - System.out.println("### (Ignore the SSL certificate warning because we installed self-signed demo certificates)"); - - } catch (Exception e) { - System.out.println(e.getMessage()); - } - } - - /** - * Helper method to create security_admin_demo.(sh|bat) - * @param securityAdminScriptPath path to original script - * @param securityAdminDemoScriptPath path to security admin demo script - * @throws IOException if there was error reading/writing the file - */ - private static void createSecurityAdminDemoScript(String securityAdminScriptPath, String securityAdminDemoScriptPath) - throws IOException { - String[] securityAdminCommands; - - String securityAdminExecutionPath = securityAdminScriptPath - + "\" -cd \"" - + OPENSEARCH_CONF_DIR - + "opensearch-security\" -icl -key \"" - + OPENSEARCH_CONF_DIR - + DemoCertificate.ADMIN_CERT_KEY.getFileName() - + "\" -cert \"" - + OPENSEARCH_CONF_DIR - + DemoCertificate.ADMIN_CERT.getFileName() - + "\" -cacert \"" - + OPENSEARCH_CONF_DIR - + DemoCertificate.ROOT_CA.getFileName() - + "\" -nhnv"; - - if (OS.toLowerCase().contains("win")) { - securityAdminCommands = new String[] { "@echo off", "call \"" + securityAdminExecutionPath }; - } else { - securityAdminCommands = new String[] { "#!/bin/bash", "sudo" + " \"" + securityAdminExecutionPath }; - } - - // Write securityadmin_demo script - FileWriter writer = new FileWriter(securityAdminDemoScriptPath, StandardCharsets.UTF_8); - for (String command : securityAdminCommands) { - writer.write(command + "\n"); - } - writer.close(); - } -} - -/** - * Enum for demo certificates - */ -enum DemoCertificate { - ADMIN_CERT( - "kirk.pem", - "-----BEGIN CERTIFICATE-----\n" - + "MIIEmDCCA4CgAwIBAgIUZjrlDPP8azRDPZchA/XEsx0X2iYwDQYJKoZIhvcNAQEL\n" - + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt\n" - + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl\n" - + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v\n" - + "dCBDQTAeFw0yMzA4MjkyMDA2MzdaFw0zMzA4MjYyMDA2MzdaME0xCzAJBgNVBAYT\n" - + "AmRlMQ0wCwYDVQQHDAR0ZXN0MQ8wDQYDVQQKDAZjbGllbnQxDzANBgNVBAsMBmNs\n" - + "aWVudDENMAsGA1UEAwwEa2lyazCCASIwDQYJKoZIhvcNA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\n" - + "1bUzP59iu7f3r567I4ob8Vy7PP+Ov35p7Vv4oDHHwgsdRzX6pvL6mmwVrQ3BfVec\n" - + "h9Dqprr+ukYmjho76g6k5cQuRaB6MxqldzUg+2E7IHQP8MCF+co51uZq2nl33mtp\n" - + "RGr6JbdHXc96zsLTL3saJQ8AWEfu1gbTVrwyRA==\n" - + "-----END CERTIFICATE-----" - ), - ADMIN_CERT_KEY( - "kirk-key.pem", - "-----BEGIN PRIVATE KEY-----\n" - + "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCVXDgEJQorgfXp\n" - + "gpY0TgF55bD2xuzxN5Dc9rDfgWxrsOvOloMpd7k6FR71bKWjJi1KptSmM/cDElky\n" - + "AWYKSfYWGiGxsQ+EQW+6kwCfEOHXQldn+0+JcWqP+osSPjtJfwRvRN5kRqP69MPo\n" - + "7U0N2kdqenqMWjmG1chDGLRSOEGU5HIBiDxsZtOcvMaJ8b1eaW0lvS+6gFQ80AvB\n" - + "GBkDDCOHHLtDXBylrZk2CQP8AzxNicIZ4B8G3CG3OHA8+nBtEtxZoIihrrkqlMt+\n" - + "b/5N8u8zB0Encew0kdrc4R/2wS//ahr6U+9Siq8T7WsUtGwKj3BJClg6OyDJRhlu\n" - + "y2gFnxoPAgMBAAECggEAP5TOycDkx+megAWVoHV2fmgvgZXkBrlzQwUG/VZQi7V4\n" - + "ZGzBMBVltdqI38wc5MtbK3TCgHANnnKgor9iq02Z4wXDwytPIiti/ycV9CDRKvv0\n" - + "TnD2hllQFjN/IUh5n4thHWbRTxmdM7cfcNgX3aZGkYbLBVVhOMtn4VwyYu/Mxy8j\n" - + "xClZT2xKOHkxqwmWPmdDTbAeZIbSv7RkIGfrKuQyUGUaWhrPslvYzFkYZ0umaDgQ\n" - + "OAthZew5Bz3OfUGOMPLH61SVPuJZh9zN1hTWOvT65WFWfsPd2yStI+WD/5PU1Doo\n" - + "1RyeHJO7s3ug8JPbtNJmaJwHe9nXBb/HXFdqb976yQKBgQDNYhpu+MYSYupaYqjs\n" - + "9YFmHQNKpNZqgZ4ceRFZ6cMJoqpI5dpEMqToFH7tpor72Lturct2U9nc2WR0HeEs\n" - + "/6tiptyMPTFEiMFb1opQlXF2ae7LeJllntDGN0Q6vxKnQV+7VMcXA0Y8F7tvGDy3\n" - + "qJu5lfvB1mNM2I6y/eMxjBuQhwKBgQC6K41DXMFro0UnoO879pOQYMydCErJRmjG\n" - + "/tZSy3Wj4KA/QJsDSViwGfvdPuHZRaG9WtxdL6kn0w1exM9Rb0bBKl36lvi7o7xv\n" - + "M+Lw9eyXMkww8/F5d7YYH77gIhGo+RITkKI3+5BxeBaUnrGvmHrpmpgRXWmINqr0\n" - + "0jsnN3u0OQKBgCf45vIgItSjQb8zonLz2SpZjTFy4XQ7I92gxnq8X0Q5z3B+o7tQ\n" - + "K/4rNwTju/sGFHyXAJlX+nfcK4vZ4OBUJjP+C8CTjEotX4yTNbo3S6zjMyGQqDI5\n" - + "9aIOUY4pb+TzeUFJX7If5gR+DfGyQubvvtcg1K3GHu9u2l8FwLj87sRzAoGAflQF\n" - + "RHuRiG+/AngTPnZAhc0Zq0kwLkpH2Rid6IrFZhGLy8AUL/O6aa0IGoaMDLpSWUJp\n" - + "nBY2S57MSM11/MVslrEgGmYNnI4r1K25xlaqV6K6ztEJv6n69327MS4NG8L/gCU5\n" - + "3pEm38hkUi8pVYU7in7rx4TCkrq94OkzWJYurAkCgYATQCL/rJLQAlJIGulp8s6h\n" - + "mQGwy8vIqMjAdHGLrCS35sVYBXG13knS52LJHvbVee39AbD5/LlWvjJGlQMzCLrw\n" - + "F7oILW5kXxhb8S73GWcuMbuQMFVHFONbZAZgn+C9FW4l7XyRdkrbR1MRZ2km8YMs\n" - + "/AHmo368d4PSNRMMzLHw8Q==\n" - + "-----END PRIVATE KEY-----" - ), - NODE_CERT( - "esnode.pem", - "-----BEGIN CERTIFICATE-----\n" - + "MIIEPDCCAySgAwIBAgIUZjrlDPP8azRDPZchA/XEs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gQU0/qDQaY10jIo\n" - + "wCjLUpz/HfQXyt8wHwYDVR0jBBgwFoAUF4ffoFrrZhKn1dD4uhJFPLcrAJwwDQYJ\n" - + "KoZIhvcNAQELBQADggEBAD2hkndVih6TWxoe/oOW0i2Bq7ScNO/n7/yHWL04HJmR\n" - + "MaHv/Xjc8zLFLgHuHaRvC02ikWIJyQf5xJt0Oqu2GVbqXH9PBGKuEP2kCsRRyU27\n" - + "zTclAzfQhqmKBTYQ/3lJ3GhRQvXIdYTe+t4aq78TCawp1nSN+vdH/1geG6QjMn5N\n" - + "1FU8tovDd4x8Ib/0dv8RJx+n9gytI8n/giIaDCEbfLLpe4EkV5e5UNpOnRgJjjuy\n" - + "vtZutc81TQnzBtkS9XuulovDE0qI+jQrKkKu8xgGLhgH0zxnPkKtUg2I3Aq6zl1L\n" - + "zYkEOUF8Y25J6WeY88Yfnc0iigI+Pnz5NK8R9GL7TYo=\n" - + "-----END CERTIFICATE-----" - ), - NODE_KEY( - "esnode-key.pem", - "-----BEGIN PRIVATE KEY-----\n" - + "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCm93kXteDQHMAv\n" - + "bUPNPW5pyRHKDD42XGWSgq0k1D29C/UdyL21HLzTJa49ZU2ldIkSKs9JqbkHdyK0\n" - + "o8MO6L8dotLoYbxDWbJFW8bp1w6tDTU0HGkn47XVu3EwbfrTENg3jFu+Oem6a/50\n" - + "1SzITzJWtS0cn2dIFOBimTVpT/4Zv5qrXA6Cp4biOmoTYWhi/qQl8d0IaADiqoZ1\n" - + "MvZbZ6x76qTrRAbg+UWkpTEXoH1xTc8ndibR7+HP6OTqCKvo1NhE8uP4pY+fWd6b\n" - + "6l+KLo3IKpfTbAIJXIO+M67FLtWKtttDao94B069skzKk6FPgW/OZh6PRCD0oxOa\n" - + "vV+ld2SjAgMBAAECggEAQK1+uAOZeaSZggW2jQut+MaN4JHLi61RH2cFgU3COLgo\n" - + "FIiNjFn8f2KKU3gpkt1It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PtX0FrT1zIosibmlud\n" - + "tu49A/0KZu4PBjrFMYTSEWGNJez3Fb2VsJwylVl6HivwbP61FhlYfyksCzQQFU71\n" - + "+x7Nmybp7PmpEBECr3deoZKQ/acNHn0iwb0It+YqV5+TquQebqgwK6WCLsMuiYKT\n" - + "bg/ch9Rhxbq22yrVgWHh6epp\n" - + "-----END PRIVATE KEY-----" - ), - ROOT_CA( - "root-ca.pem", - "-----BEGIN CERTIFICATE-----\n" - + "MIIExjCCA66gAwIBAgIUd+SvPvzan5P2TQbEZ4zj4Gt6FYowDQYJKoZIhvcNAQEL\n" - + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt\n" - + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl\n" - + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v\n" - + "dCBDQTAeFw0yMzA4MjkwNDIwMDNaFw0yMzA5MjgwNDIwMDNaMIGPMRMwEQYKCZIm\n" - + "iZPyLGQBGRYDY29tMRcwFQYKCZImiZPyLGQBGRYHZXhhbXBsZTEZMBcGA1UECgwQ\n" - + "RXhhbXBsZSBDb20gSW5jLjEhMB8GA1UECwwYRXhhbXBsZSBDb20gSW5jLiBSb290\n" - + "IENBMSEwHwYDVQQDDBhFeGFtcGxlIENvbSBJbmMuIFJvb3QgQ0EwggEiMA0GCSqG\n" - + "SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDEPyN7J9VGPyJcQmCBl5TGwfSzvVdWwoQU\n" - + "j9aEsdfFJ6pBCDQSsj8Lv4RqL0dZra7h7SpZLLX/YZcnjikrYC+rP5OwsI9xEE/4\n" - + "U98CsTBPhIMgqFK6SzNE5494BsAk4cL72dOOc8tX19oDS/PvBULbNkthQ0aAF1dg\n" - + "vbrHvu7hq7LisB5ZRGHVE1k/AbCs2PaaKkn2jCw/b+U0Ml9qPuuEgz2mAqJDGYoA\n" - + "WSR4YXrOcrmPuRqbws464YZbJW898/0Pn/U300ed+4YHiNYLLJp51AMkR4YEw969\n" - + "VRPbWIvLrd0PQBooC/eLrL6rvud/GpYhdQEUx8qcNCKd4bz3OaQ5AgMBAAGjggEW\n" - + "MIIBEjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQU\n" - + "F4ffoFrrZhKn1dD4uhJFPLcrAJwwgc8GA1UdIwSBxzCBxIAUF4ffoFrrZhKn1dD4\n" - + "uhJFPLcrAJyhgZWkgZIwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJ\n" - + "k/IsZAEZFgdleGFtcGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYD\n" - + "VQQLDBhFeGFtcGxlIENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUg\n" - + "Q29tIEluYy4gUm9vdCBDQYIUd+SvPvzan5P2TQbEZ4zj4Gt6FYowDQYJKoZIhvcN\n" - + "AQELBQADggEBAIopqco/k9RSjouTeKP4z0EVUxdD4qnNh1GLSRqyAVe0aChyKF5f\n" - + "qt1Bd1XCY8D16RgekkKGHDpJhGCpel+vtIoXPBxUaGQNYxmJCf5OzLMODlcrZk5i\n" - + "jHIcv/FMeK02NBcz/WQ3mbWHVwXLhmwqa2zBsF4FmPCJAbFLchLhkAv1HJifHbnD\n" - + "jQzlKyl5jxam/wtjWxSm0iyso0z2TgyzY+MESqjEqB1hZkCFzD1xtUOCxbXgtKae\n" - + "dgfHVFuovr3fNLV3GvQk0s9okDwDUcqV7DSH61e5bUMfE84o3of8YA7+HUoPV5Du\n" - + "8sTOKRf7ncGXdDRA8aofW268pTCuIu3+g/Y=\n" - + "-----END CERTIFICATE-----" - ); - - private final String fileName; - private final String content; - - DemoCertificate(String fileName, String content) { - this.fileName = fileName; - this.content = content; - } - - public String getFileName() { - return fileName; - } - - public String getContent() { - return content; - } -} - -/** - * The environment in which the script is being executed - */ -enum ExecutionEnvironment { - demo, // default value - test // to be used only for tests -} diff --git a/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java b/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java new file mode 100644 index 0000000000..6ad41fefcc --- /dev/null +++ b/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java @@ -0,0 +1,49 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.tools.democonfig; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +/** + * This class creates demo certificate files + */ +public class CertificateGenerator extends InstallDemoConfiguration { + + /** + * Creates demo super-admin, node and root certificates + */ + public void createDemoCertificates() { + for (DemoCertificate cert : DemoCertificate.values()) { + String filePath = OPENSEARCH_CONF_DIR + File.separator + cert.getFileName(); + writeCertificateToFile(filePath, cert.getContent()); + } + } + + /** + * Helper method to write the certificates to their own file + * @param filePath the file which needs to be written + * @param content the content which needs to be written to this file + */ + private static void writeCertificateToFile(String filePath, String content) { + try { + FileWriter fileWriter = new FileWriter(filePath, StandardCharsets.UTF_8); + fileWriter.write(content); + fileWriter.close(); + } catch (IOException e) { + System.err.println("Error writing certificate file: " + filePath); + System.exit(-1); + } + } +} diff --git a/src/main/java/org/opensearch/security/tools/democonfig/DemoCertificate.java b/src/main/java/org/opensearch/security/tools/democonfig/DemoCertificate.java new file mode 100644 index 0000000000..53fe0e8525 --- /dev/null +++ b/src/main/java/org/opensearch/security/tools/democonfig/DemoCertificate.java @@ -0,0 +1,174 @@ +package org.opensearch.security.tools.democonfig; + +/** + * Enum for demo certificates + */ +public enum DemoCertificate { + ADMIN_CERT( + "kirk.pem", + "-----BEGIN CERTIFICATE-----\n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"LGQBGRYDY29tMRcwFQYKCZImiZPyLGQBGRYHZXhhbXBsZTEZMBcGA1UECgwQRXhh\n" + + "bXBsZSBDb20gSW5jLjEhMB8GA1UECwwYRXhhbXBsZSBDb20gSW5jLiBSb290IENB\n" + + "MSEwHwYDVQQDDBhFeGFtcGxlIENvbSBJbmMuIFJvb3QgQ0GCFHfkrz782p+T9k0G\n" + + "xGeM4+BrehWKMB0GA1UdDgQWBBSjMS8tgguX/V7KSGLoGg7K6XMzIDANBgkqhkiG\n" + + "9w0BAQsFAAOCAQEANMwD1JYlwAh82yG1gU3WSdh/tb6gqaSzZK7R6I0L7slaXN9m\n" + + "y2ErUljpTyaHrdiBFmPhU/2Kj2r+fIUXtXdDXzizx/JdmueT0nG9hOixLqzfoC9p\n" + + "fAhZxM62RgtyZoaczQN82k1/geMSwRpEndFe3OH7arkS/HSbIFxQhAIy229eWe5d\n" + + "1bUzP59iu7f3r567I4ob8Vy7PP+Ov35p7Vv4oDHHwgsdRzX6pvL6mmwVrQ3BfVec\n" + + "h9Dqprr+ukYmjho76g6k5cQuRaB6MxqldzUg+2E7IHQP8MCF+co51uZq2nl33mtp\n" + + "RGr6JbdHXc96zsLTL3saJQ8AWEfu1gbTVrwyRA==\n" + + "-----END CERTIFICATE-----" + ), + ADMIN_CERT_KEY( + "kirk-key.pem", + "-----BEGIN PRIVATE KEY-----\n" + + "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCVXDgEJQorgfXp\n" + + "gpY0TgF55bD2xuzxN5Dc9rDfgWxrsOvOloMpd7k6FR71bKWjJi1KptSmM/cDElky\n" + + "AWYKSfYWGiGxsQ+EQW+6kwCfEOHXQldn+0+JcWqP+osSPjtJfwRvRN5kRqP69MPo\n" + + "7U0N2kdqenqMWjmG1chDGLRSOEGU5HIBiDxsZtOcvMaJ8b1eaW0lvS+6gFQ80AvB\n" + + "GBkDDCOHHLtDXBylrZk2CQP8AzxNicIZ4B8G3CG3OHA8+nBtE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+ "RHuRiG+/AngTPnZAhc0Zq0kwLkpH2Rid6IrFZhGLy8AUL/O6aa0IGoaMDLpSWUJp\n" + + "nBY2S57MSM11/MVslrEgGmYNnI4r1K25xlaqV6K6ztEJv6n69327MS4NG8L/gCU5\n" + + "3pEm38hkUi8pVYU7in7rx4TCkrq94OkzWJYurAkCgYATQCL/rJLQAlJIGulp8s6h\n" + + "mQGwy8vIqMjAdHGLrCS35sVYBXG13knS52LJHvbVee39AbD5/LlWvjJGlQMzCLrw\n" + + "F7oILW5kXxhb8S73GWcuMbuQMFVHFONbZAZgn+C9FW4l7XyRdkrbR1MRZ2km8YMs\n" + + "/AHmo368d4PSNRMMzLHw8Q==\n" + + "-----END PRIVATE KEY-----" + ), + NODE_CERT( + "esnode.pem", + "-----BEGIN CERTIFICATE-----\n" + + "MIIEPDCCAySgAwIBAgIUZjrlDPP8azRDPZchA/XEsx0X2iIwDQYJKoZIhvcNAQEL\n" + + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt\n" + + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl\n" + + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v\n" + + "dCBDQTAeFw0yMzA4MjkwNDIzMTJaFw0zMzA4MjYwNDIzMTJaMFcxCzAJBgNVBAYT\n" + + "AmRlMQ0wCwYDVQQHDAR0ZXN0MQ0wCwYDVQQKDARub2RlMQ0wCwYDVQQLDARub2Rl\n" + + "MRswGQYDVQQDDBJub2RlLTAuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUA\n" + + "A4IBDwAwggEKAoIBAQCm93kXteDQHMAvbUPNPW5pyRHKDD42XGWSgq0k1D29C/Ud\n" + + "yL21HLzTJa49ZU2ldIkSKs9JqbkHdyK0o8MO6L8dotLoYbxDWbJFW8bp1w6tDTU0\n" + + "HGkn47XVu3EwbfrTENg3jFu+Oem6a/501SzITzJWtS0cn2dIFOBimTVpT/4Zv5qr\n" + + "XA6Cp4biOmoTYWhi/qQl8d0IaADiqoZ1MvZbZ6x76qTrRAbg+UWkpTEXoH1xTc8n\n" + + "dibR7+HP6OTqCKvo1NhE8uP4pY+fWd6b6l+KLo3IKpfTbAIJXIO+M67FLtWKtttD\n" + + "ao94B069skzKk6FPgW/OZh6PRCD0oxOavV+ld2SjAgMBAAGjgcYwgcMwRwYDVR0R\n" + + "BEAwPogFKgMEBQWCEm5vZGUtMC5leGFtcGxlLmNvbYIJbG9jYWxob3N0hxAAAAAA\n" + + "AAAAAAAAAAAAAAABhwR/AAABMAsGA1UdDwQEAwIF4DAdBgNVHSUEFjAUBggrBgEF\n" + + "BQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQU0/qDQaY10jIo\n" + + "wCjLUpz/HfQXyt8wHwYDVR0jBBgwFoAUF4ffoFrrZhKn1dD4uhJFPLcrAJwwDQYJ\n" + + "KoZIhvcNAQELBQADggEBAD2hkndVih6TWxoe/oOW0i2Bq7ScNO/n7/yHWL04HJmR\n" + + "MaHv/Xjc8zLFLgHuHaRvC02ikWIJyQf5xJt0Oqu2GVbqXH9PBGKuEP2kCsRRyU27\n" + + "zTclAzfQhqmKBTYQ/3lJ3GhRQvXIdYTe+t4aq78TCawp1nSN+vdH/1geG6QjMn5N\n" + + "1FU8tovDd4x8Ib/0dv8RJx+n9gytI8n/giIaDCEbfLLpe4EkV5e5UNpOnRgJjjuy\n" + + "vtZutc81TQnzBtkS9XuulovDE0qI+jQrKkKu8xgGLhgH0zxnPkKtUg2I3Aq6zl1L\n" + + "zYkEOUF8Y25J6WeY88Yfnc0iigI+Pnz5NK8R9GL7TYo=\n" + + "-----END CERTIFICATE-----" + ), + NODE_KEY( + "esnode-key.pem", + "-----BEGIN PRIVATE KEY-----\n" + + "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCm93kXteDQHMAv\n" + + "bUPNPW5pyRHKDD42XGWSgq0k1D29C/UdyL21HLzTJa49ZU2ldIkSKs9JqbkHdyK0\n" + + "o8MO6L8dotLoYbxDWbJFW8bp1w6tDTU0HGkn47XVu3EwbfrTENg3jFu+Oem6a/50\n" + + "1SzITzJWtS0cn2dIFOBimTVpT/4Zv5qrXA6Cp4biOmoTYWhi/qQl8d0IaADiqoZ1\n" + + "MvZbZ6x76qTrRAbg+UWkpTEXoH1xTc8ndibR7+HP6OTqCKvo1NhE8uP4pY+fWd6b\n" + + "6l+KLo3IKpfTbAIJXIO+M67FLtWKtttDao94B069skzKk6FPgW/OZh6PRCD0oxOa\n" + + "vV+ld2SjAgMBAAECggEAQK1+uAOZeaSZggW2jQut+MaN4JHLi61RH2cFgU3COLgo\n" + + "FIiNjFn8f2KKU3gpkt1It8PjlmprpYut4wHI7r6UQfuv7ZrmncRiPWHm9PB82+ZQ\n" + + "5MXYqj4YUxoQJ62Cyz4sM6BobZDrjG6HHGTzuwiKvHHkbsEE9jQ4E5m7yfbVvM0O\n" + + "zvwrSOM1tkZihKSTpR0j2+taji914tjBssbn12TMZQL5ItGnhR3luY8mEwT9MNkZ\n" + + "xg0VcREoAH+pu9FE0vPUgLVzhJ3be7qZTTSRqv08bmW+y1plu80GbppePcgYhEow\n" + + "dlW4l6XPJaHVSn1lSFHE6QAx6sqiAnBz0NoTPIaLyQKBgQDZqDOlhCRciMRicSXn\n" + + "7yid9rhEmdMkySJHTVFOidFWwlBcp0fGxxn8UNSBcXdSy7GLlUtH41W9PWl8tp9U\n" + + "hQiiXORxOJ7ZcB80uNKXF01hpPj2DpFPWyHFxpDkWiTAYpZl68rOlYujxZUjJIej\n" + + "VvcykBC2BlEOG9uZv2kxcqLyJwKBgQDEYULTxaTuLIa17wU3nAhaainKB3vHxw9B\n" + + "Ksy5p3ND43UNEKkQm7K/WENx0q47TA1mKD9i+BhaLod98mu0YZ+BCUNgWKcBHK8c\n" + + "uXpauvM/pLhFLXZ2jvEJVpFY3J79FSRK8bwE9RgKfVKMMgEk4zOyZowS8WScOqiy\n" + + "hnQn1vKTJQKBgElhYuAnl9a2qXcC7KOwRsJS3rcKIVxijzL4xzOyVShp5IwIPbOv\n" + + "hnxBiBOH/JGmaNpFYBcBdvORE9JfA4KMQ2fx53agfzWRjoPI1/7mdUk5RFI4gRb/\n" + + "A3jZRBoopgFSe6ArCbnyQxzYzToG48/Wzwp19ZxYrtUR4UyJct6f5n27AoGBAJDh\n" + + "KIpQQDOvCdtjcbfrF4aM2DPCfaGPzENJriwxy6oEPzDaX8Bu/dqI5Ykt43i/zQrX\n" + + "GpyLaHvv4+oZVTiI5UIvcVO9U8hQPyiz9f7F+fu0LHZs6f7hyhYXlbe3XFxeop3f\n" + + "5dTKdWgXuTTRF2L9dABkA2deS9mutRKwezWBMQk5AoGBALPtX0FrT1zIosibmlud\n" + + "tu49A/0KZu4PBjrFMYTSEWGNJez3Fb2VsJwylVl6HivwbP61FhlYfyksCzQQFU71\n" + + "+x7Nmybp7PmpEBECr3deoZKQ/acNHn0iwb0It+YqV5+TquQebqgwK6WCLsMuiYKT\n" + + "bg/ch9Rhxbq22yrVgWHh6epp\n" + + "-----END PRIVATE KEY-----" + ), + ROOT_CA( + "root-ca.pem", + "-----BEGIN CERTIFICATE-----\n" + + "MIIExjCCA66gAwIBAgIUd+SvPvzan5P2TQbEZ4zj4Gt6FYowDQYJKoZIhvcNAQEL\n" + + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt\n" + + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl\n" + + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v\n" + + "dCBDQTAeFw0yMzA4MjkwNDIwMDNaFw0yMzA5MjgwNDIwMDNaMIGPMR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IhvcN\n" + + "AQELBQADggEBAIopqco/k9RSjouTeKP4z0EVUxdD4qnNh1GLSRqyAVe0aChyKF5f\n" + + "qt1Bd1XCY8D16RgekkKGHDpJhGCpel+vtIoXPBxUaGQNYxmJCf5OzLMODlcrZk5i\n" + + "jHIcv/FMeK02NBcz/WQ3mbWHVwXLhmwqa2zBsF4FmPCJAbFLchLhkAv1HJifHbnD\n" + + "jQzlKyl5jxam/wtjWxSm0iyso0z2TgyzY+MESqjEqB1hZkCFzD1xtUOCxbXgtKae\n" + + "dgfHVFuovr3fNLV3GvQk0s9okDwDUcqV7DSH61e5bUMfE84o3of8YA7+HUoPV5Du\n" + + "8sTOKRf7ncGXdDRA8aofW268pTCuIu3+g/Y=\n" + + "-----END CERTIFICATE-----" + ); + + private final String fileName; + private final String content; + + DemoCertificate(String fileName, String content) { + this.fileName = fileName; + this.content = content; + } + + public String getFileName() { + return fileName; + } + + public String getContent() { + return content; + } +} diff --git a/src/main/java/org/opensearch/security/tools/democonfig/ExecutionEnvironment.java b/src/main/java/org/opensearch/security/tools/democonfig/ExecutionEnvironment.java new file mode 100644 index 0000000000..c7840ee6bf --- /dev/null +++ b/src/main/java/org/opensearch/security/tools/democonfig/ExecutionEnvironment.java @@ -0,0 +1,9 @@ +package org.opensearch.security.tools.democonfig; + +/** + * The environment in which the demo config installation script is being executed + */ +public enum ExecutionEnvironment { + demo, // default value + test // to be used only for tests +} diff --git a/src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java new file mode 100644 index 0000000000..662e417b75 --- /dev/null +++ b/src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java @@ -0,0 +1,377 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.tools.democonfig; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.PosixFilePermission; +import java.util.HashSet; +import java.util.Scanner; +import java.util.Set; + +/** + * This class installs demo configuration for security plugin + */ +public class InstallDemoConfiguration { + + static boolean assumeyes = false; + static boolean initsecurity = false; + static boolean cluster_mode = false; + static int skip_updates = -1; + static String SCRIPT_DIR; + static String BASE_DIR; + static String OPENSEARCH_CONF_FILE; + static String OPENSEARCH_BIN_DIR; + static String OPENSEARCH_PLUGINS_DIR; + static String OPENSEARCH_LIB_PATH; + static String OPENSEARCH_INSTALL_TYPE; + static String OPENSEARCH_CONF_DIR; + static String OPENSEARCH_VERSION; + static String SECURITY_VERSION; + + static ExecutionEnvironment environment = ExecutionEnvironment.demo; + + static final String OS = System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch"); + + static final String FILE_EXTENSION = OS.toLowerCase().contains("win") ? ".bat" : ".sh"; + + static final String SYSTEM_INDICES = ".plugins-ml-config, .plugins-ml-connector, .plugins-ml-model-group, .plugins-ml-model, " + + ".plugins-ml-task, .plugins-ml-conversation-meta, .plugins-ml-conversation-interactions, .opendistro-alerting-config, .opendistro-alerting-alert*, " + + ".opendistro-anomaly-results*, .opendistro-anomaly-detector*, .opendistro-anomaly-checkpoints, .opendistro-anomaly-detection-state, " + + ".opendistro-reports-*, .opensearch-notifications-*, .opensearch-notebooks, .opensearch-observability, .ql-datasources, " + + ".opendistro-asynchronous-search-response*, .replication-metadata-store, .opensearch-knn-models, .geospatial-ip2geo-data*"; + + static SecurityConfigurator securityConfigurator; + static CertificateGenerator certificateGenerator; + + public static void main(String[] options) { + securityConfigurator = new SecurityConfigurator(); + certificateGenerator = new CertificateGenerator(); + + printScriptHeaders(); + readOptions(options); + gatherUserInputs(); + initializeVariables(); + printVariables(); + securityConfigurator.configureSecurity(); + certificateGenerator.createDemoCertificates(); + finishScriptExecution(); + } + + /** + * Prints deprecation warning and other headers for the script + */ + private static void printScriptHeaders() { + System.out.println("**************************************************************************"); + System.out.println("** This tool will be deprecated in the next major release of OpenSearch **"); + System.out.println("** https://github.com/opensearch-project/security/issues/1755 **"); + System.out.println("**************************************************************************"); + System.out.println("\n"); + System.out.println("OpenSearch Security Demo Installer"); + System.out.println("** Warning: Do not use on production or public reachable systems **"); + } + + /** + * Reads the options passed to the script + * @param options an array of strings containing options passed to the script + */ + private static void readOptions(String[] options) { + // set script execution dir + SCRIPT_DIR = options[0]; + + for (int i = 1; i < options.length; i++) { + switch (options[i]) { + case "-y": + assumeyes = true; + break; + case "-i": + initsecurity = true; + break; + case "-c": + cluster_mode = true; + break; + case "-s": + skip_updates = 0; + break; + case "-t": + environment = ExecutionEnvironment.test; + break; + case "-h": + case "-?": + showHelp(); + return; + default: + System.out.println("Invalid option: " + options[i]); + } + } + } + + /** + * Prints the help menu when -h option is passed + */ + private static void showHelp() { + System.out.println("install_demo_configuration.sh [-y] [-i] [-c]"); + System.out.println(" -h show help"); + System.out.println(" -y confirm all installation dialogues automatically"); + System.out.println(" -i initialize Security plugin with default configuration (default is to ask if -y is not given)"); + System.out.println(" -c enable cluster mode by binding to all network interfaces (default is to ask if -y is not given)"); + System.out.println(" -s skip updates if config is already applied to opensearch.yml"); + System.out.println( + " -t set the execution environment to `test` to skip password validation. Should be used only for testing. (default is set to `demo`)" + ); + System.exit(0); + } + + /** + * Prompt the user and collect user inputs + * Input collection will be skipped if -y option was passed + */ + private static void gatherUserInputs() { + if (!assumeyes) { + try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) { + + if (!confirmAction(scanner, "Install demo certificates?")) { + System.exit(0); + } + + if (!initsecurity) { + initsecurity = confirmAction(scanner, "Initialize Security Modules?"); + } + + if (!cluster_mode) { + System.out.println("Cluster mode requires additional setup of:"); + System.out.println(" - Virtual memory (vm.max_map_count)\n"); + cluster_mode = confirmAction(scanner, "Enable cluster mode?"); + } + } + } else { + initsecurity = true; + cluster_mode = true; + } + } + + /** + * Helper method to scan user inputs. + * @param scanner object to be used for scanning user input + * @param message prompt question + * @return true or false based on user input + */ + private static boolean confirmAction(Scanner scanner, String message) { + System.out.print(message + " [y/N] "); + String response = scanner.nextLine(); + return response.equalsIgnoreCase("yes") || response.equalsIgnoreCase("y"); + } + + /** + * Initialize all class level variables required + */ + private static void initializeVariables() { + setBaseDir(); + setOpenSearchVariables(); + setSecurityVariables(); + } + + /** + * Sets the base directory to be used by the script + */ + private static void setBaseDir() { + File baseDirFile = new File(SCRIPT_DIR).getParentFile().getParentFile().getParentFile(); + BASE_DIR = baseDirFile != null ? baseDirFile.getAbsolutePath() : null; + + if (BASE_DIR == null || !new File(BASE_DIR).isDirectory()) { + System.out.println("DEBUG: basedir does not exist"); + System.exit(-1); + } + + BASE_DIR += File.separator; + } + + /** + * Sets the variables for items at OpenSearch level + */ + private static void setOpenSearchVariables() { + OPENSEARCH_CONF_FILE = BASE_DIR + "config" + File.separator + "opensearch.yml"; + OPENSEARCH_BIN_DIR = BASE_DIR + "bin" + File.separator; + OPENSEARCH_PLUGINS_DIR = BASE_DIR + "plugins" + File.separator; + String OPENSEARCH_MODULES_DIR = BASE_DIR + "modules" + File.separator; + OPENSEARCH_LIB_PATH = BASE_DIR + "lib" + File.separator; + OPENSEARCH_INSTALL_TYPE = determineInstallType(); + + if (!(new File(OPENSEARCH_CONF_FILE).exists())) { + System.out.println("Unable to determine OpenSearch config directory. Quit."); + System.exit(-1); + } + + if (!(new File(OPENSEARCH_BIN_DIR).exists())) { + System.out.println("Unable to determine OpenSearch bin directory. Quit."); + System.exit(-1); + } + + if (!(new File(OPENSEARCH_PLUGINS_DIR).exists())) { + System.out.println("Unable to determine OpenSearch plugins directory. Quit."); + System.exit(-1); + } + + if (!(new File(OPENSEARCH_MODULES_DIR).exists())) { + System.out.println("Unable to determine OpenSearch modules directory. Quit."); + // System.exit(-1); + } + + if (!(new File(OPENSEARCH_LIB_PATH).exists())) { + System.out.println("Unable to determine OpenSearch lib directory. Quit."); + System.exit(-1); + } + + OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_FILE).getParent(); + OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_DIR).getAbsolutePath() + File.separator; + } + + /** + * Returns the installation type based on the underlying operating system + * @return will be one of `.zip`, `.tar.gz` or `rpm/deb` + */ + private static String determineInstallType() { + // windows (.bat execution) + if (OS.toLowerCase().contains("win")) { + return ".zip"; + } + + // other OS (.sh execution) + if (new File("/usr/share/opensearch").equals(new File(BASE_DIR))) { + OPENSEARCH_CONF_FILE = "/usr/share/opensearch/config/opensearch.yml"; + if (!new File(OPENSEARCH_CONF_FILE).exists()) { + OPENSEARCH_CONF_FILE = "/etc/opensearch/opensearch.yml"; + } + return "rpm/deb"; + } + return ".tar.gz"; + } + + /** + * Sets the path variables for items at OpenSearch security plugin level + */ + private static void setSecurityVariables() { + if (!(new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").exists())) { + System.out.println("OpenSearch Security plugin not installed. Quit."); + System.exit(-1); + } + + // Extract OpenSearch version and Security version + File[] opensearchLibFiles = new File(OPENSEARCH_LIB_PATH).listFiles( + pathname -> pathname.getName().startsWith("opensearch-") && pathname.getName().endsWith(".jar") + ); + + if (opensearchLibFiles != null && opensearchLibFiles.length > 0) { + OPENSEARCH_VERSION = opensearchLibFiles[0].getName().replaceAll("opensearch-(.*).jar", "$1"); + } + + File[] securityFiles = new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").listFiles( + pathname -> pathname.getName().startsWith("opensearch-security-") && pathname.getName().endsWith(".jar") + ); + + if (securityFiles != null && securityFiles.length > 0) { + SECURITY_VERSION = securityFiles[0].getName().replaceAll("opensearch-security-(.*).jar", "$1"); + } + } + + /** + * Prints the initialized variables + */ + private static void printVariables() { + System.out.println("OpenSearch install type: " + OPENSEARCH_INSTALL_TYPE + " on " + OS); + System.out.println("OpenSearch config dir: " + OPENSEARCH_CONF_DIR); + System.out.println("OpenSearch config file: " + OPENSEARCH_CONF_FILE); + System.out.println("OpenSearch bin dir: " + OPENSEARCH_BIN_DIR); + System.out.println("OpenSearch plugins dir: " + OPENSEARCH_PLUGINS_DIR); + System.out.println("OpenSearch lib dir: " + OPENSEARCH_LIB_PATH); + System.out.println("Detected OpenSearch Version: " + OPENSEARCH_VERSION); + System.out.println("Detected OpenSearch Security Version: " + SECURITY_VERSION); + } + + /** + * Prints end of script execution message and creates security admin demo file. + */ + private static void finishScriptExecution() { + System.out.println("### Success"); + System.out.println("### Execute this script now on all your nodes and then start all nodes"); + + try { + String securityAdminScriptPath = OPENSEARCH_PLUGINS_DIR + + "opensearch-security" + + File.separator + + "tools" + + File.separator + + "securityadmin" + + FILE_EXTENSION; + String securityAdminDemoScriptPath = OPENSEARCH_CONF_DIR + "securityadmin_demo" + FILE_EXTENSION; + + securityConfigurator.createSecurityAdminDemoScript(securityAdminScriptPath, securityAdminDemoScriptPath); + + // Make securityadmin_demo script executable + // not needed for windows + if (!OS.toLowerCase().contains("win")) { + Path file = Paths.get(securityAdminDemoScriptPath); + Set perms = new HashSet<>(); + // Add the execute permission for owner, group, and others + perms.add(PosixFilePermission.OWNER_READ); + perms.add(PosixFilePermission.OWNER_EXECUTE); + perms.add(PosixFilePermission.GROUP_EXECUTE); + perms.add(PosixFilePermission.OTHERS_EXECUTE); + Files.setPosixFilePermissions(file, perms); + } + + // Read the last line of the security-admin script + String lastLine = ""; + try (BufferedReader reader = new BufferedReader(new FileReader(securityAdminDemoScriptPath, StandardCharsets.UTF_8))) { + String currentLine; + while ((currentLine = reader.readLine()) != null) { + lastLine = currentLine; + } + } + + if (!initsecurity) { + System.out.println("### After the whole cluster is up execute: "); + System.out.println(lastLine); + System.out.println("### or run ." + File.separator + "securityadmin_demo" + FILE_EXTENSION); + System.out.println("### After that you can also use the Security Plugin ConfigurationGUI"); + } else { + System.out.println("### OpenSearch Security will be automatically initialized."); + System.out.println("### If you like to change the runtime configuration "); + System.out.println( + "### change the files in .." + + File.separator + + ".." + + File.separator + + ".." + + File.separator + + "config" + + File.separator + + "opensearch-security and execute: " + ); + System.out.println(lastLine); + System.out.println("### or run ." + File.separator + "securityadmin_demo" + FILE_EXTENSION); + System.out.println("### To use the Security Plugin ConfigurationGUI"); + } + + System.out.println("### To access your secured cluster open https://: and log in with admin/admin."); + System.out.println("### (Ignore the SSL certificate warning because we installed self-signed demo certificates)"); + + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/src/main/java/org/opensearch/security/tools/democonfig/SecurityConfigurator.java b/src/main/java/org/opensearch/security/tools/democonfig/SecurityConfigurator.java new file mode 100644 index 0000000000..4b3ac3c3be --- /dev/null +++ b/src/main/java/org/opensearch/security/tools/democonfig/SecurityConfigurator.java @@ -0,0 +1,316 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +package org.opensearch.security.tools.democonfig; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.opensearch.common.settings.Settings; +import org.opensearch.security.dlic.rest.validation.PasswordValidator; +import org.opensearch.security.dlic.rest.validation.RequestContentValidator; +import org.opensearch.security.tools.Hasher; + +import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_MIN_LENGTH; +import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX; +import static org.opensearch.security.user.UserService.generatePassword; + +/** + * This class updates the security related configuration, as needed. + */ +public class SecurityConfigurator extends InstallDemoConfiguration { + + /** + * Configures security related changes to the opensearch configuration + * 1. Checks if plugins is already configuration. If yes, exit + * 2. Sets the custom admin password (Generates one if none is provided) + * 3. Write the security config to opensearch.yml + */ + public void configureSecurity() { + checkIfSecurityPluginIsAlreadyConfigured(); + setAdminPassword(); + writeSecurityConfigToOpenSearchYML(); + } + + /** + * Replaces the admin password in internal_users.yml with the custom or generated password + */ + private static void setAdminPassword() { + String ADMIN_PASSWORD = ""; + String initialAdminPassword = System.getenv("initialAdminPassword"); + String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; + String INTERNAL_USERS_FILE_PATH = OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; + boolean shouldValidatePassword = environment.equals(ExecutionEnvironment.demo); + try { + final PasswordValidator passwordValidator = PasswordValidator.of( + Settings.builder() + .put(SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX, "(?=.*[A-Z])(?=.*[^a-zA-Z\\\\d])(?=.*[0-9])(?=.*[a-z]).{8,}") + .put(SECURITY_RESTAPI_PASSWORD_MIN_LENGTH, 8) + .build() + ); + + // Read custom password + if (initialAdminPassword != null && !initialAdminPassword.isEmpty()) { + ADMIN_PASSWORD = initialAdminPassword; + } else { + File adminPasswordFile = new File(ADMIN_PASSWORD_FILE_PATH); + if (adminPasswordFile.exists() && adminPasswordFile.length() > 0) { + try (BufferedReader br = new BufferedReader(new FileReader(ADMIN_PASSWORD_FILE_PATH, StandardCharsets.UTF_8))) { + ADMIN_PASSWORD = br.readLine(); + } + } + } + + // If script execution environment is set to demo, validate custom password, else if set to test, skip validation + if (shouldValidatePassword + && !ADMIN_PASSWORD.isEmpty() + && passwordValidator.validate("admin", ADMIN_PASSWORD) != RequestContentValidator.ValidationError.NONE) { + System.out.println("Password " + ADMIN_PASSWORD + " is weak. Please re-try with a stronger password."); + System.exit(-1); + } + + // if ADMIN_PASSWORD is still an empty string, it implies no custom password was provided. We proceed with generating a new one. + if (ADMIN_PASSWORD.isEmpty()) { + System.out.println("No custom admin password found. Generating a new password now."); + // generate a new random password + // We always validate a generated password + while (passwordValidator.validate("admin", ADMIN_PASSWORD) != RequestContentValidator.ValidationError.NONE) { + ADMIN_PASSWORD = generatePassword(); + } + } + + // print the password to the logs + System.out.println("\t***************************************************"); + System.out.println("\t\tADMIN PASSWORD SET TO: " + ADMIN_PASSWORD); + System.out.println("\t***************************************************"); + + writePasswordToInternalUsersFile(ADMIN_PASSWORD, INTERNAL_USERS_FILE_PATH); + + } catch (IOException e) { + System.out.println("Exception: " + e.getMessage()); + System.exit(-1); + } + } + + /** + * Generate password hash and update it in the internal_users.yml file + * @param adminPassword the password to be hashed and updated + * @param internalUsersFile the file path string to internal_users.yml file + * @throws IOException while reading, writing to files + */ + private static void writePasswordToInternalUsersFile(String adminPassword, String internalUsersFile) throws IOException { + String hashedAdminPassword = Hasher.hash(adminPassword.toCharArray()); + + if (hashedAdminPassword.isEmpty()) { + System.out.println("Hash the admin password failure, see console for details"); + System.exit(-1); + } + + Path tempFilePath = Paths.get(internalUsersFile + ".tmp"); + Path internalUsersPath = Paths.get(internalUsersFile); + + try ( + BufferedReader reader = new BufferedReader(new FileReader(internalUsersFile, StandardCharsets.UTF_8)); + BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath.toFile(), StandardCharsets.UTF_8)) + ) { + String line; + while ((line = reader.readLine()) != null) { + if (line.matches(" *hash: *\"\\$2a\\$12\\$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"")) { + line = line.replace( + "\"$2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG\"", + "\"" + hashedAdminPassword + "\"" + ); + } + writer.write(line + System.lineSeparator()); + } + } catch (IOException e) { + throw new IOException("Unable to update the internal users file with the hashed password."); + } + Files.move(tempFilePath, internalUsersPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING); + } + + /** + * Checks if security plugin is already configured. If so, the script execution will not continue. + */ + private static void checkIfSecurityPluginIsAlreadyConfigured() { + // Check if the configuration file contains the 'plugins.security' string + if (OPENSEARCH_CONF_FILE != null && new File(OPENSEARCH_CONF_FILE).exists()) { + try (BufferedReader br = new BufferedReader(new FileReader(OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8))) { + String line; + while ((line = br.readLine()) != null) { + if (line.toLowerCase().contains("plugins.security")) { + System.out.println(OPENSEARCH_CONF_FILE + " seems to be already configured for Security. Quit."); + System.exit(skip_updates); + } + } + } catch (IOException e) { + System.err.println("Error reading configuration file."); + System.exit(-1); + } + } else { + System.err.println("OpenSearch configuration file does not exist. Quit."); + System.exit(-1); + } + } + + /** + * Update opensearch.yml with security configuration information + */ + private static void writeSecurityConfigToOpenSearchYML() { + String securityConfig = buildSecurityConfigString(); + + try (FileWriter writer = new FileWriter(OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8, true)) { + writer.write(securityConfig); + } catch (IOException e) { + System.err.println("Exception writing security configuration to opensearch.yml."); + System.exit(-1); + } + } + + /** + * Helper method to build security configuration to append to opensearch.yml + * @return the configuration string to be written to opensearch.yml + */ + private static String buildSecurityConfigString() { + StringBuilder securityConfigLines = new StringBuilder(); + + securityConfigLines.append("\n") + .append("######## Start OpenSearch Security Demo Configuration ########\n") + .append("# WARNING: revise all the lines below before you go into production\n") + .append("plugins.security.ssl.transport.pemcert_filepath: esnode.pem\n") + .append("plugins.security.ssl.transport.pemkey_filepath: esnode-key.pem\n") + .append("plugins.security.ssl.transport.pemtrustedcas_filepath: root-ca.pem\n") + .append("plugins.security.ssl.transport.enforce_hostname_verification: false\n") + .append("plugins.security.ssl.http.enabled: true\n") + .append("plugins.security.ssl.http.pemcert_filepath: esnode.pem\n") + .append("plugins.security.ssl.http.pemkey_filepath: esnode-key.pem\n") + .append("plugins.security.ssl.http.pemtrustedcas_filepath: root-ca.pem\n") + .append("plugins.security.allow_unsafe_democertificates: true\n"); + + if (initsecurity) { + securityConfigLines.append("plugins.security.allow_default_init_securityindex: true\n"); + } + + securityConfigLines.append("plugins.security.authcz.admin_dn:\n - CN=kirk,OU=client,O=client,L=test, C=de\n\n"); + + securityConfigLines.append("plugins.security.system_indices.enabled: true\n" + "plugins.security.system_indices.indices: [") + .append(SYSTEM_INDICES) + .append("]\n"); + + if (!isNetworkHostAlreadyPresent(OPENSEARCH_CONF_FILE)) { + if (cluster_mode) { + securityConfigLines.append("network.host: 0.0.0.0\n"); + securityConfigLines.append("node.name: smoketestnode\n"); + securityConfigLines.append("cluster.initial_cluster_manager_nodes: smoketestnode\n"); + } + } + + if (!isNodeMaxLocalStorageNodesAlreadyPresent(OPENSEARCH_CONF_FILE)) { + securityConfigLines.append("node.max_local_storage_nodes: 3\n"); + } + + securityConfigLines.append("######## End OpenSearch Security Demo Configuration ########\n"); + + return securityConfigLines.toString(); + } + + /** + * Helper method to check if network.host config is present + * @param filePath path to opensearch.yml + * @return true is present, false otherwise + */ + private static boolean isNetworkHostAlreadyPresent(String filePath) { + try { + String searchString = "^network.host"; + return isStringAlreadyPresentInFile(filePath, searchString); + } catch (IOException e) { + return false; + } + } + + /** + * Helper method to check if node.max_local_storage_nodes config is present + * @param filePath path to opensearch.yml + * @return true if present, false otherwise + */ + private static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) { + try { + String searchString = "^node.max_local_storage_nodes"; + return isStringAlreadyPresentInFile(filePath, searchString); + } catch (IOException e) { + return false; + } + } + + /** + * Checks if given string is already present in the file + * @param filePath path to file in which given string should be searched + * @param searchString the string to be searched for + * @return true if string is present, false otherwise + * @throws IOException if there was exception reading the file + */ + private static boolean isStringAlreadyPresentInFile(String filePath, String searchString) throws IOException { + try (BufferedReader reader = new BufferedReader(new FileReader(filePath, StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + if (line.matches(searchString)) { + return true; + } + } + } + return false; + } + + /** + * Helper method to create security_admin_demo.(sh|bat) + * @param securityAdminScriptPath path to original script + * @param securityAdminDemoScriptPath path to security admin demo script + * @throws IOException if there was error reading/writing the file + */ + void createSecurityAdminDemoScript(String securityAdminScriptPath, String securityAdminDemoScriptPath) throws IOException { + String[] securityAdminCommands; + + String securityAdminExecutionPath = securityAdminScriptPath + + "\" -cd \"" + + OPENSEARCH_CONF_DIR + + "opensearch-security\" -icl -key \"" + + OPENSEARCH_CONF_DIR + + DemoCertificate.ADMIN_CERT_KEY.getFileName() + + "\" -cert \"" + + OPENSEARCH_CONF_DIR + + DemoCertificate.ADMIN_CERT.getFileName() + + "\" -cacert \"" + + OPENSEARCH_CONF_DIR + + DemoCertificate.ROOT_CA.getFileName() + + "\" -nhnv"; + + if (OS.toLowerCase().contains("win")) { + securityAdminCommands = new String[] { "@echo off", "call \"" + securityAdminExecutionPath }; + } else { + securityAdminCommands = new String[] { "#!/bin/bash", "sudo" + " \"" + securityAdminExecutionPath }; + } + + // Write securityadmin_demo script + FileWriter writer = new FileWriter(securityAdminDemoScriptPath, StandardCharsets.UTF_8); + for (String command : securityAdminCommands) { + writer.write(command + "\n"); + } + writer.close(); + } +} diff --git a/tools/install_demo_configuration.bat b/tools/install_demo_configuration.bat index 7296a05a2e..52d836b2a3 100755 --- a/tools/install_demo_configuration.bat +++ b/tools/install_demo_configuration.bat @@ -11,4 +11,4 @@ if defined OPENSEARCH_JAVA_HOME ( exit /b 1 ) -%BIN_PATH% -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.InstallDemoConfiguration %DIR% %* 2> nul \ No newline at end of file +%BIN_PATH% -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.democonfig.InstallDemoConfiguration %DIR% %* 2> nul \ No newline at end of file diff --git a/tools/install_demo_configuration.sh b/tools/install_demo_configuration.sh index ccd59fe34a..a80f8c54b2 100755 --- a/tools/install_demo_configuration.sh +++ b/tools/install_demo_configuration.sh @@ -27,4 +27,4 @@ else echo "WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use $(which $BIN_PATH)" fi -"$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.InstallDemoConfiguration "$DIR" "$@" 2>/dev/null +"$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.democonfig.InstallDemoConfiguration "$DIR" "$@" 2>/dev/null From 5866fb99778531fe27cb1fb1cebfd5f6e417d77e Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 13 Nov 2023 13:22:49 -0500 Subject: [PATCH 22/27] Formats some print statements Signed-off-by: Darshit Chanpura --- .../security/tools/democonfig/InstallDemoConfiguration.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java index 662e417b75..24eea3a647 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java @@ -81,8 +81,8 @@ private static void printScriptHeaders() { System.out.println("** https://github.com/opensearch-project/security/issues/1755 **"); System.out.println("**************************************************************************"); System.out.println("\n"); - System.out.println("OpenSearch Security Demo Installer"); - System.out.println("** Warning: Do not use on production or public reachable systems **"); + System.out.println("### OpenSearch Security Demo Installer"); + System.out.println("### ** Warning: Do not use on production or public reachable systems **"); } /** From a2c327d900309bdbf9bd8dfc2938b2a21ecb5bc4 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 13 Nov 2023 13:58:29 -0500 Subject: [PATCH 23/27] Refactors some class names Signed-off-by: Darshit Chanpura --- .../tools/democonfig/CertificateGenerator.java | 4 ++-- .../{DemoCertificate.java => Certificates.java} | 4 ++-- ...nstallDemoConfiguration.java => Installer.java} | 10 +++++----- ...urator.java => SecuritySettingsConfigurer.java} | 14 +++++++------- tools/install_demo_configuration.bat | 2 +- tools/install_demo_configuration.sh | 2 +- 6 files changed, 18 insertions(+), 18 deletions(-) rename src/main/java/org/opensearch/security/tools/democonfig/{DemoCertificate.java => Certificates.java} (99%) rename src/main/java/org/opensearch/security/tools/democonfig/{InstallDemoConfiguration.java => Installer.java} (97%) rename src/main/java/org/opensearch/security/tools/democonfig/{SecurityConfigurator.java => SecuritySettingsConfigurer.java} (97%) diff --git a/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java b/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java index 6ad41fefcc..a08ead5483 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java @@ -19,13 +19,13 @@ /** * This class creates demo certificate files */ -public class CertificateGenerator extends InstallDemoConfiguration { +public class CertificateGenerator extends Installer { /** * Creates demo super-admin, node and root certificates */ public void createDemoCertificates() { - for (DemoCertificate cert : DemoCertificate.values()) { + for (Certificates cert : Certificates.values()) { String filePath = OPENSEARCH_CONF_DIR + File.separator + cert.getFileName(); writeCertificateToFile(filePath, cert.getContent()); } diff --git a/src/main/java/org/opensearch/security/tools/democonfig/DemoCertificate.java b/src/main/java/org/opensearch/security/tools/democonfig/Certificates.java similarity index 99% rename from src/main/java/org/opensearch/security/tools/democonfig/DemoCertificate.java rename to src/main/java/org/opensearch/security/tools/democonfig/Certificates.java index 53fe0e8525..6821147e8c 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/DemoCertificate.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/Certificates.java @@ -3,7 +3,7 @@ /** * Enum for demo certificates */ -public enum DemoCertificate { +public enum Certificates { ADMIN_CERT( "kirk.pem", "-----BEGIN CERTIFICATE-----\n" @@ -159,7 +159,7 @@ public enum DemoCertificate { private final String fileName; private final String content; - DemoCertificate(String fileName, String content) { + Certificates(String fileName, String content) { this.fileName = fileName; this.content = content; } diff --git a/src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java b/src/main/java/org/opensearch/security/tools/democonfig/Installer.java similarity index 97% rename from src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java rename to src/main/java/org/opensearch/security/tools/democonfig/Installer.java index 24eea3a647..4c7c79a1e5 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/InstallDemoConfiguration.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/Installer.java @@ -26,7 +26,7 @@ /** * This class installs demo configuration for security plugin */ -public class InstallDemoConfiguration { +public class Installer { static boolean assumeyes = false; static boolean initsecurity = false; @@ -55,11 +55,11 @@ public class InstallDemoConfiguration { + ".opendistro-reports-*, .opensearch-notifications-*, .opensearch-notebooks, .opensearch-observability, .ql-datasources, " + ".opendistro-asynchronous-search-response*, .replication-metadata-store, .opensearch-knn-models, .geospatial-ip2geo-data*"; - static SecurityConfigurator securityConfigurator; + static SecuritySettingsConfigurer securitySettingsConfigurer; static CertificateGenerator certificateGenerator; public static void main(String[] options) { - securityConfigurator = new SecurityConfigurator(); + securitySettingsConfigurer = new SecuritySettingsConfigurer(); certificateGenerator = new CertificateGenerator(); printScriptHeaders(); @@ -67,7 +67,7 @@ public static void main(String[] options) { gatherUserInputs(); initializeVariables(); printVariables(); - securityConfigurator.configureSecurity(); + securitySettingsConfigurer.configureSecuritySettings(); certificateGenerator.createDemoCertificates(); finishScriptExecution(); } @@ -319,7 +319,7 @@ private static void finishScriptExecution() { + FILE_EXTENSION; String securityAdminDemoScriptPath = OPENSEARCH_CONF_DIR + "securityadmin_demo" + FILE_EXTENSION; - securityConfigurator.createSecurityAdminDemoScript(securityAdminScriptPath, securityAdminDemoScriptPath); + securitySettingsConfigurer.createSecurityAdminDemoScript(securityAdminScriptPath, securityAdminDemoScriptPath); // Make securityadmin_demo script executable // not needed for windows diff --git a/src/main/java/org/opensearch/security/tools/democonfig/SecurityConfigurator.java b/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java similarity index 97% rename from src/main/java/org/opensearch/security/tools/democonfig/SecurityConfigurator.java rename to src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java index 4b3ac3c3be..d7367925e5 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/SecurityConfigurator.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java @@ -34,7 +34,7 @@ /** * This class updates the security related configuration, as needed. */ -public class SecurityConfigurator extends InstallDemoConfiguration { +public class SecuritySettingsConfigurer extends Installer { /** * Configures security related changes to the opensearch configuration @@ -42,16 +42,16 @@ public class SecurityConfigurator extends InstallDemoConfiguration { * 2. Sets the custom admin password (Generates one if none is provided) * 3. Write the security config to opensearch.yml */ - public void configureSecurity() { + public void configureSecuritySettings() { checkIfSecurityPluginIsAlreadyConfigured(); - setAdminPassword(); + updateAdminPassword(); writeSecurityConfigToOpenSearchYML(); } /** * Replaces the admin password in internal_users.yml with the custom or generated password */ - private static void setAdminPassword() { + private static void updateAdminPassword() { String ADMIN_PASSWORD = ""; String initialAdminPassword = System.getenv("initialAdminPassword"); String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; @@ -291,13 +291,13 @@ void createSecurityAdminDemoScript(String securityAdminScriptPath, String securi + OPENSEARCH_CONF_DIR + "opensearch-security\" -icl -key \"" + OPENSEARCH_CONF_DIR - + DemoCertificate.ADMIN_CERT_KEY.getFileName() + + Certificates.ADMIN_CERT_KEY.getFileName() + "\" -cert \"" + OPENSEARCH_CONF_DIR - + DemoCertificate.ADMIN_CERT.getFileName() + + Certificates.ADMIN_CERT.getFileName() + "\" -cacert \"" + OPENSEARCH_CONF_DIR - + DemoCertificate.ROOT_CA.getFileName() + + Certificates.ROOT_CA.getFileName() + "\" -nhnv"; if (OS.toLowerCase().contains("win")) { diff --git a/tools/install_demo_configuration.bat b/tools/install_demo_configuration.bat index 52d836b2a3..5767166b26 100755 --- a/tools/install_demo_configuration.bat +++ b/tools/install_demo_configuration.bat @@ -11,4 +11,4 @@ if defined OPENSEARCH_JAVA_HOME ( exit /b 1 ) -%BIN_PATH% -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.democonfig.InstallDemoConfiguration %DIR% %* 2> nul \ No newline at end of file +%BIN_PATH% -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.democonfig.Installer %DIR% %* 2> nul \ No newline at end of file diff --git a/tools/install_demo_configuration.sh b/tools/install_demo_configuration.sh index a80f8c54b2..6203e6126f 100755 --- a/tools/install_demo_configuration.sh +++ b/tools/install_demo_configuration.sh @@ -27,4 +27,4 @@ else echo "WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use $(which $BIN_PATH)" fi -"$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.democonfig.InstallDemoConfiguration "$DIR" "$@" 2>/dev/null +"$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.democonfig.Installer "$DIR" "$@" 2>/dev/null From f60a315f645aacdd544a1f2aba49bfe87e694830 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Tue, 14 Nov 2023 23:37:30 -0500 Subject: [PATCH 24/27] Exits script when java is not found Signed-off-by: Darshit Chanpura --- tools/install_demo_configuration.sh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tools/install_demo_configuration.sh b/tools/install_demo_configuration.sh index 6203e6126f..7835f7c675 100755 --- a/tools/install_demo_configuration.sh +++ b/tools/install_demo_configuration.sh @@ -19,12 +19,14 @@ fi BIN_PATH="java" # now set the path to java: first OPENSEARCH_JAVA_HOME, then JAVA_HOME -if [ ! -z "$OPENSEARCH_JAVA_HOME" ]; then +if [ -n "$OPENSEARCH_JAVA_HOME" ]; then BIN_PATH="$OPENSEARCH_JAVA_HOME/bin/java" -elif [ ! -z "$JAVA_HOME" ]; then +elif [ -n "$JAVA_HOME" ]; then BIN_PATH="$JAVA_HOME/bin/java" else - echo "WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use $(which $BIN_PATH)" + echo "Unable to find java runtime" + echo "OPENSEARCH_JAVA_HOME or JAVA_HOME must be defined" + exit 1 fi "$BIN_PATH" $JAVA_OPTS -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.democonfig.Installer "$DIR" "$@" 2>/dev/null From 680306bbdaebb6f4910773dea6660de6be83a54b Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Tue, 14 Nov 2023 23:56:06 -0500 Subject: [PATCH 25/27] Fixes checkstyle violations due to recent changes to a file in main Signed-off-by: Darshit Chanpura --- .../java/org/opensearch/security/httpclient/HttpClient.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/opensearch/security/httpclient/HttpClient.java b/src/main/java/org/opensearch/security/httpclient/HttpClient.java index 8c31a5f9c9..43b5107b70 100644 --- a/src/main/java/org/opensearch/security/httpclient/HttpClient.java +++ b/src/main/java/org/opensearch/security/httpclient/HttpClient.java @@ -33,6 +33,7 @@ import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; +import com.google.common.collect.Lists; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder; import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; @@ -52,6 +53,7 @@ import org.apache.hc.core5.ssl.SSLContexts; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; + import org.opensearch.action.index.IndexRequest; import org.opensearch.action.index.IndexResponse; import org.opensearch.action.support.WriteRequest.RefreshPolicy; @@ -62,8 +64,6 @@ import org.opensearch.client.RestHighLevelClient; import org.opensearch.common.xcontent.XContentType; -import com.google.common.collect.Lists; - public class HttpClient implements Closeable { public static class HttpClientBuilder { From 3d8449fe6c250c3ddf5c1664977f8e52b7e0c63d Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Wed, 15 Nov 2023 11:54:46 -0500 Subject: [PATCH 26/27] Makes all static methods package-private for tests Signed-off-by: Darshit Chanpura --- .../democonfig/CertificateGenerator.java | 2 +- .../security/tools/democonfig/Installer.java | 24 +++++++++---------- .../SecuritySettingsConfigurer.java | 16 ++++++------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java b/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java index a08ead5483..bc18d3a62e 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java @@ -36,7 +36,7 @@ public void createDemoCertificates() { * @param filePath the file which needs to be written * @param content the content which needs to be written to this file */ - private static void writeCertificateToFile(String filePath, String content) { + static void writeCertificateToFile(String filePath, String content) { try { FileWriter fileWriter = new FileWriter(filePath, StandardCharsets.UTF_8); fileWriter.write(content); diff --git a/src/main/java/org/opensearch/security/tools/democonfig/Installer.java b/src/main/java/org/opensearch/security/tools/democonfig/Installer.java index 4c7c79a1e5..947d49e691 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/Installer.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/Installer.java @@ -75,7 +75,7 @@ public static void main(String[] options) { /** * Prints deprecation warning and other headers for the script */ - private static void printScriptHeaders() { + static void printScriptHeaders() { System.out.println("**************************************************************************"); System.out.println("** This tool will be deprecated in the next major release of OpenSearch **"); System.out.println("** https://github.com/opensearch-project/security/issues/1755 **"); @@ -89,7 +89,7 @@ private static void printScriptHeaders() { * Reads the options passed to the script * @param options an array of strings containing options passed to the script */ - private static void readOptions(String[] options) { + static void readOptions(String[] options) { // set script execution dir SCRIPT_DIR = options[0]; @@ -123,7 +123,7 @@ private static void readOptions(String[] options) { /** * Prints the help menu when -h option is passed */ - private static void showHelp() { + static void showHelp() { System.out.println("install_demo_configuration.sh [-y] [-i] [-c]"); System.out.println(" -h show help"); System.out.println(" -y confirm all installation dialogues automatically"); @@ -140,7 +140,7 @@ private static void showHelp() { * Prompt the user and collect user inputs * Input collection will be skipped if -y option was passed */ - private static void gatherUserInputs() { + static void gatherUserInputs() { if (!assumeyes) { try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) { @@ -170,7 +170,7 @@ private static void gatherUserInputs() { * @param message prompt question * @return true or false based on user input */ - private static boolean confirmAction(Scanner scanner, String message) { + static boolean confirmAction(Scanner scanner, String message) { System.out.print(message + " [y/N] "); String response = scanner.nextLine(); return response.equalsIgnoreCase("yes") || response.equalsIgnoreCase("y"); @@ -179,7 +179,7 @@ private static boolean confirmAction(Scanner scanner, String message) { /** * Initialize all class level variables required */ - private static void initializeVariables() { + static void initializeVariables() { setBaseDir(); setOpenSearchVariables(); setSecurityVariables(); @@ -188,7 +188,7 @@ private static void initializeVariables() { /** * Sets the base directory to be used by the script */ - private static void setBaseDir() { + static void setBaseDir() { File baseDirFile = new File(SCRIPT_DIR).getParentFile().getParentFile().getParentFile(); BASE_DIR = baseDirFile != null ? baseDirFile.getAbsolutePath() : null; @@ -203,7 +203,7 @@ private static void setBaseDir() { /** * Sets the variables for items at OpenSearch level */ - private static void setOpenSearchVariables() { + static void setOpenSearchVariables() { OPENSEARCH_CONF_FILE = BASE_DIR + "config" + File.separator + "opensearch.yml"; OPENSEARCH_BIN_DIR = BASE_DIR + "bin" + File.separator; OPENSEARCH_PLUGINS_DIR = BASE_DIR + "plugins" + File.separator; @@ -244,7 +244,7 @@ private static void setOpenSearchVariables() { * Returns the installation type based on the underlying operating system * @return will be one of `.zip`, `.tar.gz` or `rpm/deb` */ - private static String determineInstallType() { + static String determineInstallType() { // windows (.bat execution) if (OS.toLowerCase().contains("win")) { return ".zip"; @@ -264,7 +264,7 @@ private static String determineInstallType() { /** * Sets the path variables for items at OpenSearch security plugin level */ - private static void setSecurityVariables() { + static void setSecurityVariables() { if (!(new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").exists())) { System.out.println("OpenSearch Security plugin not installed. Quit."); System.exit(-1); @@ -291,7 +291,7 @@ private static void setSecurityVariables() { /** * Prints the initialized variables */ - private static void printVariables() { + static void printVariables() { System.out.println("OpenSearch install type: " + OPENSEARCH_INSTALL_TYPE + " on " + OS); System.out.println("OpenSearch config dir: " + OPENSEARCH_CONF_DIR); System.out.println("OpenSearch config file: " + OPENSEARCH_CONF_FILE); @@ -305,7 +305,7 @@ private static void printVariables() { /** * Prints end of script execution message and creates security admin demo file. */ - private static void finishScriptExecution() { + static void finishScriptExecution() { System.out.println("### Success"); System.out.println("### Execute this script now on all your nodes and then start all nodes"); diff --git a/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java b/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java index d7367925e5..17c2a34091 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java @@ -51,7 +51,7 @@ public void configureSecuritySettings() { /** * Replaces the admin password in internal_users.yml with the custom or generated password */ - private static void updateAdminPassword() { + static void updateAdminPassword() { String ADMIN_PASSWORD = ""; String initialAdminPassword = System.getenv("initialAdminPassword"); String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; @@ -114,7 +114,7 @@ private static void updateAdminPassword() { * @param internalUsersFile the file path string to internal_users.yml file * @throws IOException while reading, writing to files */ - private static void writePasswordToInternalUsersFile(String adminPassword, String internalUsersFile) throws IOException { + static void writePasswordToInternalUsersFile(String adminPassword, String internalUsersFile) throws IOException { String hashedAdminPassword = Hasher.hash(adminPassword.toCharArray()); if (hashedAdminPassword.isEmpty()) { @@ -148,7 +148,7 @@ private static void writePasswordToInternalUsersFile(String adminPassword, Strin /** * Checks if security plugin is already configured. If so, the script execution will not continue. */ - private static void checkIfSecurityPluginIsAlreadyConfigured() { + static void checkIfSecurityPluginIsAlreadyConfigured() { // Check if the configuration file contains the 'plugins.security' string if (OPENSEARCH_CONF_FILE != null && new File(OPENSEARCH_CONF_FILE).exists()) { try (BufferedReader br = new BufferedReader(new FileReader(OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8))) { @@ -172,7 +172,7 @@ private static void checkIfSecurityPluginIsAlreadyConfigured() { /** * Update opensearch.yml with security configuration information */ - private static void writeSecurityConfigToOpenSearchYML() { + static void writeSecurityConfigToOpenSearchYML() { String securityConfig = buildSecurityConfigString(); try (FileWriter writer = new FileWriter(OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8, true)) { @@ -187,7 +187,7 @@ private static void writeSecurityConfigToOpenSearchYML() { * Helper method to build security configuration to append to opensearch.yml * @return the configuration string to be written to opensearch.yml */ - private static String buildSecurityConfigString() { + static String buildSecurityConfigString() { StringBuilder securityConfigLines = new StringBuilder(); securityConfigLines.append("\n") @@ -235,7 +235,7 @@ private static String buildSecurityConfigString() { * @param filePath path to opensearch.yml * @return true is present, false otherwise */ - private static boolean isNetworkHostAlreadyPresent(String filePath) { + static boolean isNetworkHostAlreadyPresent(String filePath) { try { String searchString = "^network.host"; return isStringAlreadyPresentInFile(filePath, searchString); @@ -249,7 +249,7 @@ private static boolean isNetworkHostAlreadyPresent(String filePath) { * @param filePath path to opensearch.yml * @return true if present, false otherwise */ - private static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) { + static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) { try { String searchString = "^node.max_local_storage_nodes"; return isStringAlreadyPresentInFile(filePath, searchString); @@ -265,7 +265,7 @@ private static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) * @return true if string is present, false otherwise * @throws IOException if there was exception reading the file */ - private static boolean isStringAlreadyPresentInFile(String filePath, String searchString) throws IOException { + static boolean isStringAlreadyPresentInFile(String filePath, String searchString) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(filePath, StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { From 4244150b0a780ff1536f7e244e7f0085257e1f99 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Thu, 16 Nov 2023 10:56:34 -0500 Subject: [PATCH 27/27] Remove unwanted variable, adds a missing catch block and converts enum variables to all-caps Signed-off-by: Darshit Chanpura --- .../tools/democonfig/CertificateGenerator.java | 2 +- .../tools/democonfig/ExecutionEnvironment.java | 4 ++-- .../security/tools/democonfig/Installer.java | 17 +++-------------- .../democonfig/SecuritySettingsConfigurer.java | 5 ++++- 4 files changed, 10 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java b/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java index bc18d3a62e..a7b39c226e 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java @@ -22,7 +22,7 @@ public class CertificateGenerator extends Installer { /** - * Creates demo super-admin, node and root certificates + * Creates demo super-admin, node and root certificates by iterating through Certificates enum */ public void createDemoCertificates() { for (Certificates cert : Certificates.values()) { diff --git a/src/main/java/org/opensearch/security/tools/democonfig/ExecutionEnvironment.java b/src/main/java/org/opensearch/security/tools/democonfig/ExecutionEnvironment.java index c7840ee6bf..9f901c4487 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/ExecutionEnvironment.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/ExecutionEnvironment.java @@ -4,6 +4,6 @@ * The environment in which the demo config installation script is being executed */ public enum ExecutionEnvironment { - demo, // default value - test // to be used only for tests + DEMO, // default value + TEST // to be used only for tests } diff --git a/src/main/java/org/opensearch/security/tools/democonfig/Installer.java b/src/main/java/org/opensearch/security/tools/democonfig/Installer.java index 947d49e691..0b166ad580 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/Installer.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/Installer.java @@ -43,7 +43,7 @@ public class Installer { static String OPENSEARCH_VERSION; static String SECURITY_VERSION; - static ExecutionEnvironment environment = ExecutionEnvironment.demo; + static ExecutionEnvironment environment = ExecutionEnvironment.DEMO; static final String OS = System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch"); @@ -73,14 +73,9 @@ public static void main(String[] options) { } /** - * Prints deprecation warning and other headers for the script + * Prints headers that indicate the start of script execution */ static void printScriptHeaders() { - System.out.println("**************************************************************************"); - System.out.println("** This tool will be deprecated in the next major release of OpenSearch **"); - System.out.println("** https://github.com/opensearch-project/security/issues/1755 **"); - System.out.println("**************************************************************************"); - System.out.println("\n"); System.out.println("### OpenSearch Security Demo Installer"); System.out.println("### ** Warning: Do not use on production or public reachable systems **"); } @@ -108,7 +103,7 @@ static void readOptions(String[] options) { skip_updates = 0; break; case "-t": - environment = ExecutionEnvironment.test; + environment = ExecutionEnvironment.TEST; break; case "-h": case "-?": @@ -207,7 +202,6 @@ static void setOpenSearchVariables() { OPENSEARCH_CONF_FILE = BASE_DIR + "config" + File.separator + "opensearch.yml"; OPENSEARCH_BIN_DIR = BASE_DIR + "bin" + File.separator; OPENSEARCH_PLUGINS_DIR = BASE_DIR + "plugins" + File.separator; - String OPENSEARCH_MODULES_DIR = BASE_DIR + "modules" + File.separator; OPENSEARCH_LIB_PATH = BASE_DIR + "lib" + File.separator; OPENSEARCH_INSTALL_TYPE = determineInstallType(); @@ -226,11 +220,6 @@ static void setOpenSearchVariables() { System.exit(-1); } - if (!(new File(OPENSEARCH_MODULES_DIR).exists())) { - System.out.println("Unable to determine OpenSearch modules directory. Quit."); - // System.exit(-1); - } - if (!(new File(OPENSEARCH_LIB_PATH).exists())) { System.out.println("Unable to determine OpenSearch lib directory. Quit."); System.exit(-1); diff --git a/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java b/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java index 17c2a34091..1e318c38b9 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java @@ -56,7 +56,7 @@ static void updateAdminPassword() { String initialAdminPassword = System.getenv("initialAdminPassword"); String ADMIN_PASSWORD_FILE_PATH = OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; String INTERNAL_USERS_FILE_PATH = OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; - boolean shouldValidatePassword = environment.equals(ExecutionEnvironment.demo); + boolean shouldValidatePassword = environment.equals(ExecutionEnvironment.DEMO); try { final PasswordValidator passwordValidator = PasswordValidator.of( Settings.builder() @@ -73,6 +73,9 @@ static void updateAdminPassword() { if (adminPasswordFile.exists() && adminPasswordFile.length() > 0) { try (BufferedReader br = new BufferedReader(new FileReader(ADMIN_PASSWORD_FILE_PATH, StandardCharsets.UTF_8))) { ADMIN_PASSWORD = br.readLine(); + } catch (IOException e) { + System.out.println("Error reading admin password from initialAdminPassword.txt."); + System.exit(-1); } } }