From 06d8c29eea9a648c463e6063542283222e5b1805 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura <35282393+DarshitChanpura@users.noreply.github.com> Date: Tue, 12 Dec 2023 17:24:47 -0500 Subject: [PATCH] Updates demo script to execute with bundled jdk (#3777) Signed-off-by: Darshit Chanpura --- build.gradle | 4 + .../democonfig/CertificateGenerator.java | 10 +- .../tools/democonfig/Certificates.java | 307 ++++++++++-------- .../security/tools/democonfig/Installer.java | 257 +++++++++------ .../SecuritySettingsConfigurer.java | 246 ++++++++------ tools/install_demo_configuration.bat | 29 +- tools/install_demo_configuration.sh | 46 ++- 7 files changed, 555 insertions(+), 344 deletions(-) diff --git a/build.gradle b/build.gradle index 2ed4ad6830..4b22f1665f 100644 --- a/build.gradle +++ b/build.gradle @@ -256,6 +256,8 @@ test { jvmArgs += "-Xmx3072m" if (JavaVersion.current() > JavaVersion.VERSION_1_8) { jvmArgs += "--add-opens=java.base/java.io=ALL-UNNAMED" + // this is needed to reflect access system env map. + jvmArgs += "--add-opens=java.base/java.util=ALL-UNNAMED" } retry { failOnPassedAfterRetry = false @@ -303,6 +305,8 @@ def setCommonTestConfig(Test task) { task.jvmArgs += "-Xmx3072m" if (JavaVersion.current() > JavaVersion.VERSION_1_8) { task.jvmArgs += "--add-opens=java.base/java.io=ALL-UNNAMED" + // this is needed to reflect access system env map. + task.jvmArgs += "--add-opens=java.base/java.util=ALL-UNNAMED" } task.retry { failOnPassedAfterRetry = false 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 a7b39c226e..077bf4610f 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/CertificateGenerator.java @@ -19,14 +19,20 @@ /** * This class creates demo certificate files */ -public class CertificateGenerator extends Installer { +public class CertificateGenerator { + + private final Installer installer; + + public CertificateGenerator(Installer installer) { + this.installer = installer; + } /** * Creates demo super-admin, node and root certificates by iterating through Certificates enum */ public void createDemoCertificates() { for (Certificates cert : Certificates.values()) { - String filePath = OPENSEARCH_CONF_DIR + File.separator + cert.getFileName(); + String filePath = this.installer.OPENSEARCH_CONF_DIR + File.separator + cert.getFileName(); writeCertificateToFile(filePath, cert.getContent()); } } diff --git a/src/main/java/org/opensearch/security/tools/democonfig/Certificates.java b/src/main/java/org/opensearch/security/tools/democonfig/Certificates.java index c776a5e29b..8e2af4dac7 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/Certificates.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/Certificates.java @@ -11,168 +11,191 @@ package org.opensearch.security.tools.democonfig; +import java.util.List; +import java.util.function.Supplier; + /** * Enum for demo certificates */ public enum Certificates { ADMIN_CERT( "kirk.pem", - "-----BEGIN CERTIFICATE-----\n" - + "MIIEmDCCA4CgAwIBAgIUZjrlDPP8azRDPZchA/XEsx0X2iYwDQYJKoZIhvcNAQEL\n" - + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt\n" - + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl\n" - + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v\n" - + "dCBDQTAeFw0yMzA4MjkyMDA2MzdaFw0zMzA4MjYyMDA2MzdaME0xCzAJBgNVBAYT\n" - + "AmRlMQ0wCwYDVQQHDAR0ZXN0MQ8wDQYDVQQKDAZjbGllbnQxDzANBgNVBAsMBmNs\n" - + "aWVudDENMAsGA1UEAwwEa2lyazCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" - + "ggEBAJVcOAQlCiuB9emCljROAXnlsPbG7PE3kNz2sN+BbGuw686Wgyl3uToVHvVs\n" - + "paMmLUqm1KYz9wMSWTIBZgpJ9hYaIbGxD4RBb7qTAJ8Q4ddCV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"RGr6JbdHXc96zsLTL3saJQ8AWEfu1gbTVrwyRA==\n" - + "-----END CERTIFICATE-----" + () -> getCertContent( + List.of( + "-----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-----" + ) + ) ), 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" - + "GBkDDCOHHLtDXBylrZk2CQP8AzxNic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8FwLj87sRzAoGAflQF\n" - + "RHuRiG+/AngTPnZAhc0Zq0kwLkpH2Rid6IrFZhGLy8AUL/O6aa0IGoaMDLpSWUJp\n" - + "nBY2S57MSM11/MVslrEgGmYNnI4r1K25xlaqV6K6ztEJv6n69327MS4NG8L/gCU5\n" - + "3pEm38hkUi8pVYU7in7rx4TCkrq94OkzWJYurAkCgYATQCL/rJLQAlJIGulp8s6h\n" - + "mQGwy8vIqMjAdHGLrCS35sVYBXG13knS52LJHvbVee39AbD5/LlWvjJGlQMzCLrw\n" - + "F7oILW5kXxhb8S73GWcuMbuQMFVHFONbZAZgn+C9FW4l7XyRdkrbR1MRZ2km8YMs\n" - + "/AHmo368d4PSNRMMzLHw8Q==\n" - + "-----END PRIVATE KEY-----" + () -> getCertContent( + List.of( + "-----BEGIN PRIVATE KEY-----", + "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCVXDgEJQorgfXp", + "gpY0TgF55bD2xuzxN5Dc9rDfgWxrsOvOloMpd7k6FR71bKWjJi1KptSmM/cDElky", + "AWYKSfYWGiGxsQ+EQW+6kwCfEOHXQldn+0+JcWqP+osSPjtJfwRvRN5kRqP69MPo", + "7U0N2kdqenqMWjmG1chDGLRSOEGU5HIBiDxsZtOcvMaJ8b1eaW0lvS+6gFQ80AvB", + "GBkDDCOHHLtDXBylrZk2CQP8AzxNicIZ4B8G3CG3OHA8+nBtEtxZoIihrrkqlMt+", + "b/5N8u8zB0Encew0kdrc4R/2wS//ahr6U+9Siq8T7WsUtGwKj3BJClg6OyDJRhlu", + "y2gFnxoPAgMBAAECggEAP5TOycDkx+megAWVoHV2fmgvgZXkBrlzQwUG/VZQi7V4", + "ZGzBMBVltdqI38wc5MtbK3TCgHANnnKgor9iq02Z4wXDwytPIiti/ycV9CDRKvv0", + "TnD2hllQFjN/IUh5n4thHWbRTxmdM7cfcNgX3aZGkYbLBVVhOMtn4VwyYu/Mxy8j", + "xClZT2xKOHkxqwmWPmdDT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+ "-----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-----" + () -> getCertContent( + List.of( + "-----BEGIN CERTIFICATE-----", + "MIIEPDCCAySgAwIBAgIUZjrlDPP8azRDPZchA/XEsx0X2iIwDQYJKoZIhvcNAQEL", + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt", + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl", + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v", + "dCBDQTAeFw0yMzA4MjkwNDIzMTJaFw0zMzA4MjYwNDIzMTJaMFcxCzAJBgNVBAYT", + "AmRlMQ0wCwYDVQQHDAR0ZXN0MQ0wCwYDVQQKDARub2RlMQ0wCwYDVQQLDARub2R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Aq6zl1L", + "zYkEOUF8Y25J6WeY88Yfnc0iigI+Pnz5NK8R9GL7TYo=", + "-----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-----" + () -> getCertContent( + List.of( + "-----BEGIN PRIVATE KEY-----", + "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCm93kXteDQHMAv", + "bUPNPW5pyRHKDD42XGWSgq0k1D29C/UdyL21HLzTJa49ZU2ldIkSKs9JqbkHdyK0", + "o8MO6L8dotLoYbxDWbJFW8bp1w6tDTU0HGkn47XVu3EwbfrTENg3jFu+Oem6a/50", + "1SzITzJWtS0cn2dIFOBimTVpT/4Zv5qrXA6Cp4biOmoTYWhi/qQl8d0IaADiqoZ1", + "MvZbZ6x76qTrRAbg+UWkpTEXoH1xTc8ndibR7+HP6OTqCKvo1NhE8uP4pY+fWd6b", + "6l+KLo3IKpfTbAIJXIO+M67FLtWKtttDao94B069skzKk6FPgW/OZh6PRCD0oxOa", + "vV+ld2SjAgMBAAECggEAQK1+uAOZeaSZggW2jQut+MaN4JHLi61RH2cFgU3COLgo", + "FIiNjFn8f2KKU3gpkt1It8PjlmprpYut4wHI7r6UQfuv7ZrmncRiPWHm9PB82+ZQ", + "5MXYqj4YUxoQJ62Cyz4sM6BobZDrjG6HHGTzuwiKvHHkbsEE9jQ4E5m7yfbVvM0O", + "zvwrSOM1tkZihKSTpR0j2+taji914tjBssbn12TMZQL5ItGnhR3luY8mEwT9MNkZ", + "xg0VcREoAH+pu9FE0vPUgLVzhJ3be7qZTTSRqv08bmW+y1plu80GbppePcgYhEow", + "dlW4l6XPJaHVSn1lSFHE6QAx6sqiAnBz0NoTPIaLyQKBgQDZqDOlhCRciMRicSXn", + "7yid9rhEmdMkySJHTVFOidFWwlBcp0fGxxn8UNSBcXdSy7GLlUtH41W9PWl8tp9U", + "hQiiXORxOJ7ZcB80uNKXF01hpPj2DpFPWyHFxpDkWiTAYpZl68rOlYujxZUjJIej", + "VvcykBC2BlEOG9uZv2kxcqLyJwKBgQDEYULTxaTuLIa17wU3nAhaainKB3vHxw9B", + "Ksy5p3ND43UNEKkQm7K/WENx0q47TA1mKD9i+BhaLod98mu0YZ+BCUNgWKcBHK8c", + "uXpauvM/pLhFLXZ2jvEJVpFY3J79FSRK8bwE9RgKfVKMMgEk4zOyZowS8WScOqiy", + "hnQn1vKTJQKBgElhYuAnl9a2qXcC7KOwRsJS3rcKIVxijzL4xzOyVShp5IwIPbOv", + "hnxBiBOH/JGmaNpFYBcBdvORE9JfA4KMQ2fx53agfzWRjoPI1/7mdUk5RFI4gRb/", + "A3jZRBoopgFSe6ArCbnyQxzYzToG48/Wzwp19ZxYrtUR4UyJct6f5n27AoGBAJDh", + "KIpQQDOvCdtjcbfrF4aM2DPCfaGPzENJriwxy6oEPzDaX8Bu/dqI5Ykt43i/zQrX", + "GpyLaHvv4+oZVTiI5UIvcVO9U8hQPyiz9f7F+fu0LHZs6f7hyhYXlbe3XFxeop3f", + "5dTKdWgXuTTRF2L9dABkA2deS9mutRKwezWBMQk5AoGBALPtX0FrT1zIosibmlud", + "tu49A/0KZu4PBjrFMYTSEWGNJez3Fb2VsJwylVl6HivwbP61FhlYfyksCzQQFU71", + "+x7Nmybp7PmpEBECr3deoZKQ/acNHn0iwb0It+YqV5+TquQebqgwK6WCLsMuiYKT", + "bg/ch9Rhxbq22yrVgWHh6epp", + "-----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" - + "SIb3DQEBAQUAA4IBDwA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gyzY+MESqjEqB1hZkCFzD1xtUOCxbXgtKae\n" - + "dgfHVFuovr3fNLV3GvQk0s9okDwDUcqV7DSH61e5bUMfE84o3of8YA7+HUoPV5Du\n" - + "8sTOKRf7ncGXdDRA8aofW268pTCuIu3+g/Y=\n" - + "-----END CERTIFICATE-----" + () -> getCertContent( + List.of( + "-----BEGIN CERTIFICATE-----", + "MIIExjCCA66gAwIBAgIUd+SvPvzan5P2TQbEZ4zj4Gt6FYowDQYJKoZIhvcNAQEL", + "BQAwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJk/IsZAEZFgdleGFt", + "cGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYDVQQLDBhFeGFtcGxl", + "IENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUgQ29tIEluYy4gUm9v", + "dCBDQTAeFw0yMzA4MjkwNDIwMDNaFw0yMzA5MjgwNDIwMDNaMIGPMRMwEQYKCZIm", + "iZPyLGQBGRYDY29tMRcwFQYKCZImiZPyLGQBGRYHZXhhbXBsZTEZMBcGA1UECgwQ", + "RXhhbXBsZSBDb20gSW5jLjEhMB8GA1UECwwYRXhhbXBsZSBDb20gSW5jLiBSb290", + "IENBMSEwHwYDVQQDDBhFeGFtcGxlIENvbSBJbmMuIFJvb3QgQ0EwggEiMA0GCSqG", + "SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDEPyN7J9VGPyJcQmCBl5TGwfSzvVdWwoQU", + "j9aEsdfFJ6pBCDQSsj8Lv4RqL0dZra7h7SpZLLX/YZcnjikrYC+rP5OwsI9xEE/4", + "U98CsTBPhIMgqFK6SzNE5494BsAk4cL72dOOc8tX19oDS/PvBULbNkthQ0aAF1dg", + "vbrHvu7hq7LisB5ZRGHVE1k/AbCs2PaaKkn2jCw/b+U0Ml9qPuuEgz2mAqJDGYoA", + "WSR4YXrOcrmPuRqbws464YZbJW898/0Pn/U300ed+4YHiNYLLJp51AMkR4YEw969", + "VRPbWIvLrd0PQBooC/eLrL6rvud/GpYhdQEUx8qcNCKd4bz3OaQ5AgMBAAGjggEW", + "MIIBEjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQU", + "F4ffoFrrZhKn1dD4uhJFPLcrAJwwgc8GA1UdIwSBxzCBxIAUF4ffoFrrZhKn1dD4", + "uhJFPLcrAJyhgZWkgZIwgY8xEzARBgoJkiaJk/IsZAEZFgNjb20xFzAVBgoJkiaJ", + "k/IsZAEZFgdleGFtcGxlMRkwFwYDVQQKDBBFeGFtcGxlIENvbSBJbmMuMSEwHwYD", + "VQQLDBhFeGFtcGxlIENvbSBJbmMuIFJvb3QgQ0ExITAfBgNVBAMMGEV4YW1wbGUg", + "Q29tIEluYy4gUm9vdCBDQYIUd+SvPvzan5P2TQbEZ4zj4Gt6FYowDQYJKoZIhvcN", + "AQELBQADggEBAIopqco/k9RSjouTeKP4z0EVUxdD4qnNh1GLSRqyAVe0aChyKF5f", + "qt1Bd1XCY8D16RgekkKGHDpJhGCpel+vtIoXPBxUaGQNYxmJCf5OzLMODlcrZk5i", + "jHIcv/FMeK02NBcz/WQ3mbWHVwXLhmwqa2zBsF4FmPCJAbFLchLhkAv1HJifHbnD", + "jQzlKyl5jxam/wtjWxSm0iyso0z2TgyzY+MESqjEqB1hZkCFzD1xtUOCxbXgtKae", + "dgfHVFuovr3fNLV3GvQk0s9okDwDUcqV7DSH61e5bUMfE84o3of8YA7+HUoPV5Du", + "8sTOKRf7ncGXdDRA8aofW268pTCuIu3+g/Y=", + "-----END CERTIFICATE-----" + ) + ) ); private final String fileName; - private final String content; + private final Supplier contentSupplier; - Certificates(String fileName, String content) { + Certificates(String fileName, Supplier contentSupplier) { this.fileName = fileName; - this.content = content; + this.contentSupplier = contentSupplier; } public String getFileName() { @@ -180,6 +203,10 @@ public String getFileName() { } public String getContent() { - return content; + return contentSupplier.get(); + } + + private static String getCertContent(List certLines) { + return String.join(System.lineSeparator(), certLines); } } 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 0b166ad580..500c65f825 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/Installer.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/Installer.java @@ -23,47 +23,83 @@ import java.util.Scanner; import java.util.Set; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + /** * This class installs demo configuration for security plugin */ public class Installer { - 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; + // Singleton Pattern + private static Installer instance; - static ExecutionEnvironment environment = ExecutionEnvironment.DEMO; + private static SecuritySettingsConfigurer securitySettingsConfigurer; - static final String OS = System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch"); + private static CertificateGenerator certificateGenerator; - static final String FILE_EXTENSION = OS.toLowerCase().contains("win") ? ".bat" : ".sh"; + boolean assumeyes = false; + boolean initsecurity = false; + boolean cluster_mode = false; + int skip_updates = -1; + String SCRIPT_DIR; + String BASE_DIR; + String OPENSEARCH_CONF_FILE; + String OPENSEARCH_BIN_DIR; + String OPENSEARCH_PLUGINS_DIR; + String OPENSEARCH_LIB_PATH; + String OPENSEARCH_INSTALL_TYPE; + String OPENSEARCH_CONF_DIR; + String OPENSEARCH_VERSION; + String SECURITY_VERSION; - 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*"; + ExecutionEnvironment environment = ExecutionEnvironment.DEMO; - static SecuritySettingsConfigurer securitySettingsConfigurer; - static CertificateGenerator certificateGenerator; + String OS; - public static void main(String[] options) { - securitySettingsConfigurer = new SecuritySettingsConfigurer(); - certificateGenerator = new CertificateGenerator(); + final String FILE_EXTENSION; - printScriptHeaders(); + static File RPM_DEB_OPENSEARCH_HOME = new File("/usr/share/opensearch"); + + private final Options options; + + // To print help information for this script + private final HelpFormatter formatter = new HelpFormatter(); + + /** + * We do not want this class to be instantiated more than once, + * as we are following Singleton Factory pattern + */ + private Installer() { + this.OS = System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch"); + FILE_EXTENSION = OS.toLowerCase().contains("win") ? ".bat" : ".sh"; + options = new Options(); + } + + /** + * Returns a singleton instance of this class + * @return an existing instance OR a new instance if there was no existing instance + */ + public static Installer getInstance() { + if (instance == null) { + instance = new Installer(); + securitySettingsConfigurer = new SecuritySettingsConfigurer(instance); + certificateGenerator = new CertificateGenerator(instance); + } + return instance; + } + + /** + * Installs the demo security configuration + * @param options the options passed to the script + */ + public void installDemoConfiguration(String[] options) { readOptions(options); + printScriptHeaders(); gatherUserInputs(); initializeVariables(); printVariables(); @@ -72,6 +108,44 @@ public static void main(String[] options) { finishScriptExecution(); } + public static void main(String[] options) { + Installer installer = Installer.getInstance(); + installer.buildOptions(); + installer.installDemoConfiguration(options); + } + + /** + * Builds options supported by this tool + */ + void buildOptions() { + options.addOption("h", "show-help", false, "Shows help for this tool."); + options.addOption("y", "answer-yes-to-all-prompts", false, "Confirm all installation dialogues automatically."); + options.addOption( + "i", + "initialize-security", + false, + "Initialize Security plugin with default configuration (default is to ask if -y is not given)." + ); + options.addOption( + "c", + "enable-cluster-mode", + false, + "Enable cluster mode by binding to all network interfaces (default is to ask if -y is not given)." + ); + options.addOption( + "s", + "skip-updates-when-already-configured", + false, + "Skip updates if config is already applied to opensearch.yml." + ); + options.addOption( + "t", + "test-execution-environment", + false, + "Set the execution environment to `test` to skip password validation. Should be used only for testing. (default is set to `demo`)" + ); + } + /** * Prints headers that indicate the start of script execution */ @@ -82,52 +156,37 @@ static void printScriptHeaders() { /** * Reads the options passed to the script - * @param options an array of strings containing options passed to the script + * @param args an array of strings containing options passed to the script */ - static void readOptions(String[] options) { + void readOptions(String[] args) { // 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]); + SCRIPT_DIR = args[0]; + + CommandLineParser parser = new DefaultParser(); + try { + CommandLine line = parser.parse(options, args); + + if (line.hasOption("h")) { + showHelp(); + return; } + assumeyes = line.hasOption("y"); + initsecurity = line.hasOption("i"); + cluster_mode = line.hasOption("c"); + skip_updates = line.hasOption("s") ? 0 : -1; + environment = line.hasOption("t") ? ExecutionEnvironment.TEST : environment; + + } catch (ParseException exp) { + System.out.println("ERR: Parsing failed. Reason: " + exp.getMessage()); + System.exit(-1); } } /** * Prints the help menu when -h option is passed */ - 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`)" - ); + void showHelp() { + formatter.printHelp("install_demo_configuration.sh", options, true); System.exit(0); } @@ -135,7 +194,7 @@ static void showHelp() { * Prompt the user and collect user inputs * Input collection will be skipped if -y option was passed */ - static void gatherUserInputs() { + void gatherUserInputs() { if (!assumeyes) { try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) { @@ -149,7 +208,7 @@ static void gatherUserInputs() { if (!cluster_mode) { System.out.println("Cluster mode requires additional setup of:"); - System.out.println(" - Virtual memory (vm.max_map_count)\n"); + System.out.println(" - Virtual memory (vm.max_map_count)" + System.lineSeparator()); cluster_mode = confirmAction(scanner, "Enable cluster mode?"); } } @@ -165,7 +224,7 @@ static void gatherUserInputs() { * @param message prompt question * @return true or false based on user input */ - static boolean confirmAction(Scanner scanner, String message) { + boolean confirmAction(Scanner scanner, String message) { System.out.print(message + " [y/N] "); String response = scanner.nextLine(); return response.equalsIgnoreCase("yes") || response.equalsIgnoreCase("y"); @@ -174,7 +233,7 @@ static boolean confirmAction(Scanner scanner, String message) { /** * Initialize all class level variables required */ - static void initializeVariables() { + void initializeVariables() { setBaseDir(); setOpenSearchVariables(); setSecurityVariables(); @@ -183,7 +242,7 @@ static void initializeVariables() { /** * Sets the base directory to be used by the script */ - static void setBaseDir() { + void setBaseDir() { File baseDirFile = new File(SCRIPT_DIR).getParentFile().getParentFile().getParentFile(); BASE_DIR = baseDirFile != null ? baseDirFile.getAbsolutePath() : null; @@ -198,50 +257,62 @@ static void setBaseDir() { /** * Sets the variables for items at OpenSearch level */ - static void setOpenSearchVariables() { + 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_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."); + Set errorMessages = validatePaths(); + + if (!errorMessages.isEmpty()) { + errorMessages.forEach(System.out::println); System.exit(-1); } + OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_FILE).getParent(); + OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_DIR).getAbsolutePath() + File.separator; + } + + /** + * Helper method + * Returns a set of error messages for the paths that didn't contain files/directories + * @return a set containing error messages if any, empty otherwise + */ + private Set validatePaths() { + Set errorMessages = new HashSet<>(); + if (!(new File(OPENSEARCH_CONF_FILE).exists())) { + errorMessages.add("Unable to determine OpenSearch config file. Quit."); + } + if (!(new File(OPENSEARCH_BIN_DIR).exists())) { - System.out.println("Unable to determine OpenSearch bin directory. Quit."); - System.exit(-1); + errorMessages.add("Unable to determine OpenSearch bin directory. Quit."); } if (!(new File(OPENSEARCH_PLUGINS_DIR).exists())) { - System.out.println("Unable to determine OpenSearch plugins directory. Quit."); - System.exit(-1); + errorMessages.add("Unable to determine OpenSearch plugins directory. Quit."); } if (!(new File(OPENSEARCH_LIB_PATH).exists())) { - System.out.println("Unable to determine OpenSearch lib directory. Quit."); - System.exit(-1); + errorMessages.add("Unable to determine OpenSearch lib directory. Quit."); } - - OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_FILE).getParent(); - OPENSEARCH_CONF_DIR = new File(OPENSEARCH_CONF_DIR).getAbsolutePath() + File.separator; + return errorMessages; } /** * Returns the installation type based on the underlying operating system * @return will be one of `.zip`, `.tar.gz` or `rpm/deb` */ - static String determineInstallType() { + 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 (RPM_DEB_OPENSEARCH_HOME.exists() && RPM_DEB_OPENSEARCH_HOME.equals(new File(BASE_DIR))) { + OPENSEARCH_CONF_FILE = RPM_DEB_OPENSEARCH_HOME.getAbsolutePath() + "/config/opensearch.yml"; if (!new File(OPENSEARCH_CONF_FILE).exists()) { OPENSEARCH_CONF_FILE = "/etc/opensearch/opensearch.yml"; } @@ -253,7 +324,7 @@ static String determineInstallType() { /** * Sets the path variables for items at OpenSearch security plugin level */ - static void setSecurityVariables() { + void setSecurityVariables() { if (!(new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").exists())) { System.out.println("OpenSearch Security plugin not installed. Quit."); System.exit(-1); @@ -261,11 +332,11 @@ static void setSecurityVariables() { // Extract OpenSearch version and Security version File[] opensearchLibFiles = new File(OPENSEARCH_LIB_PATH).listFiles( - pathname -> pathname.getName().startsWith("opensearch-") && pathname.getName().endsWith(".jar") + pathname -> pathname.getName().matches("opensearch-core-(.*).jar") ); if (opensearchLibFiles != null && opensearchLibFiles.length > 0) { - OPENSEARCH_VERSION = opensearchLibFiles[0].getName().replaceAll("opensearch-(.*).jar", "$1"); + OPENSEARCH_VERSION = opensearchLibFiles[0].getName().replaceAll("opensearch-core-(.*).jar", "$1"); } File[] securityFiles = new File(OPENSEARCH_PLUGINS_DIR + "opensearch-security").listFiles( @@ -280,7 +351,7 @@ static void setSecurityVariables() { /** * Prints the initialized variables */ - static void printVariables() { + 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); @@ -294,7 +365,7 @@ static void printVariables() { /** * Prints end of script execution message and creates security admin demo file. */ - static void finishScriptExecution() { + void finishScriptExecution() { System.out.println("### Success"); System.out.println("### Execute this script now on all your nodes and then start all nodes"); @@ -356,7 +427,11 @@ static void finishScriptExecution() { 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( + "### To access your secured cluster open https://: and log in with admin/" + + SecuritySettingsConfigurer.ADMIN_PASSWORD + + "." + ); System.out.println("### (Ignore the SSL certificate warning because we installed self-signed demo certificates)"); } catch (Exception e) { 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 a5daa579dd..ac9b0651fd 100644 --- a/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java +++ b/src/main/java/org/opensearch/security/tools/democonfig/SecuritySettingsConfigurer.java @@ -21,20 +21,62 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.databind.JsonNode; import org.opensearch.common.settings.Settings; +import org.opensearch.security.DefaultObjectMapper; import org.opensearch.security.dlic.rest.validation.PasswordValidator; import org.opensearch.security.dlic.rest.validation.RequestContentValidator; import org.opensearch.security.tools.Hasher; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; + 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 SecuritySettingsConfigurer extends Installer { +public class SecuritySettingsConfigurer { + + static final List REST_ENABLED_ROLES = List.of("all_access", "security_rest_api_access"); + static final List SYSTEM_INDICES = List.of( + ".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 String ADMIN_PASSWORD = ""; + static String ADMIN_USERNAME = "admin"; + + private final Installer installer; + + public SecuritySettingsConfigurer(Installer installer) { + this.installer = installer; + } /** * Configures security related changes to the opensearch configuration @@ -51,12 +93,11 @@ public void configureSecuritySettings() { /** * Replaces the admin password in internal_users.yml with the custom or generated password */ - static void updateAdminPassword() { - 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); + void updateAdminPassword() { + String initialAdminPassword = System.getenv().get("initialAdminPassword"); + String ADMIN_PASSWORD_FILE_PATH = installer.OPENSEARCH_CONF_DIR + "initialAdminPassword.txt"; + String INTERNAL_USERS_FILE_PATH = installer.OPENSEARCH_CONF_DIR + "opensearch-security" + File.separator + "internal_users.yml"; + boolean shouldValidatePassword = installer.environment.equals(ExecutionEnvironment.DEMO); try { final PasswordValidator passwordValidator = PasswordValidator.of( Settings.builder() @@ -83,19 +124,15 @@ static void updateAdminPassword() { // 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) { + && passwordValidator.validate(ADMIN_USERNAME, 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 is still an empty string, it implies no custom password was provided. We exit the setup. 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(); - } + System.out.println("No custom admin password found. Please provide a password."); + System.exit(-1); } // print the password to the logs @@ -106,7 +143,7 @@ static void updateAdminPassword() { writePasswordToInternalUsersFile(ADMIN_PASSWORD, INTERNAL_USERS_FILE_PATH); } catch (IOException e) { - System.out.println("Exception: " + e.getMessage()); + System.out.println("Exception updating the admin password : " + e.getMessage()); System.exit(-1); } } @@ -117,7 +154,7 @@ static void updateAdminPassword() { * @param internalUsersFile the file path string to internal_users.yml file * @throws IOException while reading, writing to files */ - static void writePasswordToInternalUsersFile(String adminPassword, String internalUsersFile) throws IOException { + void writePasswordToInternalUsersFile(String adminPassword, String internalUsersFile) throws IOException { String hashedAdminPassword = Hasher.hash(adminPassword.toCharArray()); if (hashedAdminPassword.isEmpty()) { @@ -151,15 +188,15 @@ static void writePasswordToInternalUsersFile(String adminPassword, String intern /** * Checks if security plugin is already configured. If so, the script execution will not continue. */ - static void checkIfSecurityPluginIsAlreadyConfigured() { + 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))) { + if (installer.OPENSEARCH_CONF_FILE != null && new File(installer.OPENSEARCH_CONF_FILE).exists()) { + try (BufferedReader br = new BufferedReader(new FileReader(installer.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); + System.out.println(installer.OPENSEARCH_CONF_FILE + " seems to be already configured for Security. Quit."); + System.exit(installer.skip_updates); } } } catch (IOException e) { @@ -175,66 +212,75 @@ static void checkIfSecurityPluginIsAlreadyConfigured() { /** * Update opensearch.yml with security configuration information */ - static void writeSecurityConfigToOpenSearchYML() { - String securityConfig = buildSecurityConfigString(); - - try (FileWriter writer = new FileWriter(OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8, true)) { - writer.write(securityConfig); + void writeSecurityConfigToOpenSearchYML() { + String configHeader = System.lineSeparator() + + System.lineSeparator() + + "######## Start OpenSearch Security Demo Configuration ########" + + System.lineSeparator() + + "# WARNING: revise all the lines below before you go into production" + + System.lineSeparator(); + String configFooter = "######## End OpenSearch Security Demo Configuration ########" + System.lineSeparator(); + + Map securityConfigAsMap = buildSecurityConfigMap(); + + try (FileWriter writer = new FileWriter(installer.OPENSEARCH_CONF_FILE, StandardCharsets.UTF_8, true)) { + writer.write(configHeader); + Yaml yaml = new Yaml(); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + String yamlString = yaml.dump(securityConfigAsMap); + writer.write(yamlString); + writer.write(configFooter); } catch (IOException e) { - System.err.println("Exception writing security configuration to opensearch.yml."); + System.err.println("Exception writing security configuration to opensearch.yml : " + e.getMessage()); System.exit(-1); } } /** * Helper method to build security configuration to append to opensearch.yml - * @return the configuration string to be written to opensearch.yml + * @return the configuration map to be written to opensearch.yml */ - 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"); + Map buildSecurityConfigMap() { + Map configMap = new LinkedHashMap<>(); + + configMap.put("plugins.security.ssl.transport.pemcert_filepath", Certificates.NODE_CERT.getFileName()); + configMap.put("plugins.security.ssl.transport.pemkey_filepath", Certificates.NODE_KEY.getFileName()); + configMap.put("plugins.security.ssl.transport.pemtrustedcas_filepath", Certificates.ROOT_CA.getFileName()); + configMap.put("plugins.security.ssl.transport.enforce_hostname_verification", false); + configMap.put("plugins.security.ssl.http.enabled", true); + configMap.put("plugins.security.ssl.http.pemcert_filepath", Certificates.NODE_CERT.getFileName()); + configMap.put("plugins.security.ssl.http.pemkey_filepath", Certificates.NODE_KEY.getFileName()); + configMap.put("plugins.security.ssl.http.pemtrustedcas_filepath", Certificates.ROOT_CA.getFileName()); + configMap.put("plugins.security.allow_unsafe_democertificates", true); + + if (installer.initsecurity) { + configMap.put("plugins.security.allow_default_init_securityindex", true); } - securityConfigLines.append("plugins.security.authcz.admin_dn:\n - CN=kirk,OU=client,O=client,L=test, C=de\n\n"); + configMap.put("plugins.security.authcz.admin_dn", List.of("CN=kirk,OU=client,O=client,L=test,C=de")); - securityConfigLines.append("plugins.security.audit.type: internal_opensearch\n"); - securityConfigLines.append("plugins.security.enable_snapshot_restore_privilege: true\n"); - securityConfigLines.append("plugins.security.check_snapshot_restore_write_privileges: true\n"); - securityConfigLines.append("plugins.security.restapi.roles_enabled: [\"all_access\", \"security_rest_api_access\"]\n"); + configMap.put("plugins.security.audit.type", "internal_opensearch"); + configMap.put("plugins.security.enable_snapshot_restore_privilege", true); + configMap.put("plugins.security.check_snapshot_restore_write_privileges", true); + configMap.put("plugins.security.restapi.roles_enabled", REST_ENABLED_ROLES); - securityConfigLines.append("plugins.security.system_indices.enabled: true\n"); - securityConfigLines.append("plugins.security.system_indices.indices: [").append(SYSTEM_INDICES).append("]\n"); + configMap.put("plugins.security.system_indices.enabled", true); + configMap.put("plugins.security.system_indices.indices", SYSTEM_INDICES); - 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 (!isNetworkHostAlreadyPresent(installer.OPENSEARCH_CONF_FILE)) { + if (installer.cluster_mode) { + configMap.put("network.host", "0.0.0.0"); + configMap.put("node.name", "smoketestnode"); + configMap.put("cluster.initial_cluster_manager_nodes", "smoketestnode"); } } - if (!isNodeMaxLocalStorageNodesAlreadyPresent(OPENSEARCH_CONF_FILE)) { - securityConfigLines.append("node.max_local_storage_nodes: 3\n"); + if (!isNodeMaxLocalStorageNodesAlreadyPresent(installer.OPENSEARCH_CONF_FILE)) { + configMap.put("node.max_local_storage_nodes", 3); } - securityConfigLines.append("######## End OpenSearch Security Demo Configuration ########\n"); - - return securityConfigLines.toString(); + return configMap; } /** @@ -244,8 +290,8 @@ static String buildSecurityConfigString() { */ static boolean isNetworkHostAlreadyPresent(String filePath) { try { - String searchString = "^network.host"; - return isStringAlreadyPresentInFile(filePath, searchString); + String searchString = "network.host"; + return isKeyPresentInYMLFile(filePath, searchString); } catch (IOException e) { return false; } @@ -258,30 +304,29 @@ static boolean isNetworkHostAlreadyPresent(String filePath) { */ static boolean isNodeMaxLocalStorageNodesAlreadyPresent(String filePath) { try { - String searchString = "^node.max_local_storage_nodes"; - return isStringAlreadyPresentInFile(filePath, searchString); + String searchString = "node.max_local_storage_nodes"; + return isKeyPresentInYMLFile(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 + * Checks if the given key is present in the yml file + * @param filePath path to yml file in which given key should be searched + * @param key the key to be searched for + * @return true if the key is present, false otherwise * @throws IOException if there was exception reading the file */ - 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; - } - } + static boolean isKeyPresentInYMLFile(String filePath, String key) throws IOException { + JsonNode node; + try { + node = DefaultObjectMapper.YAML_MAPPER.readTree(new File(filePath)); + } catch (IOException e) { + throw new RuntimeException(e); } - return false; + + return node.has(key); } /** @@ -291,33 +336,40 @@ static boolean isStringAlreadyPresentInFile(String filePath, String searchString * @throws IOException if there was error reading/writing the file */ void createSecurityAdminDemoScript(String securityAdminScriptPath, String securityAdminDemoScriptPath) throws IOException { - String[] securityAdminCommands; + String[] securityAdminCommands = getSecurityAdminCommands(securityAdminScriptPath); + // Write securityadmin_demo script + FileWriter writer = new FileWriter(securityAdminDemoScriptPath, StandardCharsets.UTF_8); + for (String command : securityAdminCommands) { + writer.write(command + System.lineSeparator()); + } + writer.close(); + } + + /** + * Return the command to be added to securityadmin_demo script + * @param securityAdminScriptPath the path to securityadmin.(sh|bat) + * @return the command string + */ + String[] getSecurityAdminCommands(String securityAdminScriptPath) { String securityAdminExecutionPath = securityAdminScriptPath + "\" -cd \"" - + OPENSEARCH_CONF_DIR + + installer.OPENSEARCH_CONF_DIR + "opensearch-security\" -icl -key \"" - + OPENSEARCH_CONF_DIR + + installer.OPENSEARCH_CONF_DIR + Certificates.ADMIN_CERT_KEY.getFileName() + "\" -cert \"" - + OPENSEARCH_CONF_DIR + + installer.OPENSEARCH_CONF_DIR + Certificates.ADMIN_CERT.getFileName() + "\" -cacert \"" - + OPENSEARCH_CONF_DIR + + installer.OPENSEARCH_CONF_DIR + Certificates.ROOT_CA.getFileName() + "\" -nhnv"; - if (OS.toLowerCase().contains("win")) { - securityAdminCommands = new String[] { "@echo off", "call \"" + securityAdminExecutionPath }; - } else { - securityAdminCommands = new String[] { "#!/bin/bash", "sudo" + " \"" + securityAdminExecutionPath }; + if (installer.OS.toLowerCase().contains("win")) { + return new String[] { "@echo off", "call \"" + securityAdminExecutionPath }; } - // Write securityadmin_demo script - FileWriter writer = new FileWriter(securityAdminDemoScriptPath, StandardCharsets.UTF_8); - for (String command : securityAdminCommands) { - writer.write(command + "\n"); - } - writer.close(); + return new String[] { "#!/bin/bash", "sudo" + " \"" + securityAdminExecutionPath }; } } diff --git a/tools/install_demo_configuration.bat b/tools/install_demo_configuration.bat index 5767166b26..5cf4d715fa 100755 --- a/tools/install_demo_configuration.bat +++ b/tools/install_demo_configuration.bat @@ -1,14 +1,29 @@ @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" +set CUR_DIR=%DIR% + +rem set opensearch home for instances when using bundled jdk +if not defined OPENSEARCH_HOME ( + for %%I in ("%DIR%..\..\..") do set "OPENSEARCH_HOME=%%~dpfI" +) +cd %CUR_DIR% + +if not "%OPENSEARCH_JAVA_HOME%" == "" ( + set "JAVA=%OPENSEARCH_JAVA_HOME%\bin\java.exe" + set JAVA_TYPE=OPENSEARCH_JAVA_HOME +) else if not "%JAVA_HOME%" == "" ( + set "JAVA=%JAVA_HOME%\bin\java.exe" + set JAVA_TYPE=JAVA_HOME ) else ( - echo Unable to find java runtime - echo OPENSEARCH_JAVA_HOME or JAVA_HOME must be defined + set "JAVA=%OPENSEARCH_HOME%\jdk\bin\java.exe" + set "JAVA_HOME=%OPENSEARCH_HOME%\jdk" + set JAVA_TYPE=bundled jdk +) + +if not exist "%JAVA%" ( + echo "could not find java in %JAVA_TYPE% at %JAVA%" >&2 exit /b 1 ) -%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 +"%JAVA%" -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "%DIR%\..\*;%DIR%\..\..\..\lib\*;%DIR%\..\deps\*" org.opensearch.security.tools.democonfig.Installer %DIR% %* 2> nul diff --git a/tools/install_demo_configuration.sh b/tools/install_demo_configuration.sh index 7835f7c675..d3a3ae8f75 100755 --- a/tools/install_demo_configuration.sh +++ b/tools/install_demo_configuration.sh @@ -1,6 +1,15 @@ #!/bin/bash #install_demo_configuration.sh [-y] +UNAME=$(uname -s) +if [ "$UNAME" = "FreeBSD" ]; then + OS="freebsd" +elif [ "$UNAME" = "Darwin" ]; then + OS="darwin" +else + OS="other" +fi + SCRIPT_PATH="${BASH_SOURCE[0]}" if ! [ -x "$(command -v realpath)" ]; then if [ -L "$SCRIPT_PATH" ]; then @@ -16,17 +25,40 @@ 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_HOME" ]; then + # move to opensearch root folder and set the variable + OPENSEARCH_HOME=`cd "$DIR/../../.."; pwd` +fi + +# now set the path to java: OPENSEARCH_JAVA_HOME -> JAVA_HOME -> bundled JRE -> bundled JDK if [ -n "$OPENSEARCH_JAVA_HOME" ]; then - BIN_PATH="$OPENSEARCH_JAVA_HOME/bin/java" + JAVA="$OPENSEARCH_JAVA_HOME/bin/java" + JAVA_TYPE="OPENSEARCH_JAVA_HOME" elif [ -n "$JAVA_HOME" ]; then - BIN_PATH="$JAVA_HOME/bin/java" + JAVA="$JAVA_HOME/bin/java" + JAVA_TYPE="JAVA_HOME" else - echo "Unable to find java runtime" - echo "OPENSEARCH_JAVA_HOME or JAVA_HOME must be defined" + if [ "$OS" = "darwin" ]; then + # macOS bundled Java + JAVA="$OPENSEARCH_HOME/jdk.app/Contents/Home/bin/java" + JAVA_TYPE="bundled jdk" + elif [ "$OS" = "freebsd" ]; then + # using FreeBSD default java from ports if JAVA_HOME is not set + JAVA="/usr/local/bin/java" + JAVA_TYPE="bundled jdk" + elif [ -d "$OPENSEARCH_HOME/jre" ]; then + JAVA="$OPENSEARCH_HOME/jre/bin/java" + JAVA_TYPE="bundled jre" + else + JAVA="$OPENSEARCH_HOME/jdk/bin/java" + JAVA_TYPE="bundled jdk" + fi +fi + +if [ ! -x "$JAVA" ]; then + echo "could not find java in $JAVA_TYPE at $JAVA" >&2 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 +"$JAVA" -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=OFF -cp "$DIR/../*:$DIR/../../../lib/*:$DIR/../deps/*" org.opensearch.security.tools.democonfig.Installer "$DIR" "$@" 2>/dev/null