Skip to content

Commit

Permalink
Alternative method
Browse files Browse the repository at this point in the history
Signed-off-by: Stephen Crawford <[email protected]>
  • Loading branch information
stephen-crawford committed Sep 7, 2023
1 parent bd10ee3 commit 900c4db
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 103 deletions.
63 changes: 0 additions & 63 deletions config/internal_users.yml
Original file line number Diff line number Diff line change
@@ -1,63 +0,0 @@
---
# This is the internal user database
# The hash value is a bcrypt hash and can be generated with plugin/tools/hash.sh

_meta:
type: "internalusers"
config_version: 2

# Define your internal users here

## Demo users

admin:
hash:
reserved: true
backend_roles:
- "admin"
description: "Demo admin user"

anomalyadmin:
hash: "$2y$12$TRwAAJgnNo67w3rVUz4FIeLx9Dy/llB79zf9I15CKJ9vkM4ZzAd3."
reserved: false
opendistro_security_roles:
- "anomaly_full_access"
description: "Demo anomaly admin user, using internal role"

kibanaserver:
hash: "$2a$12$4AcgAt3xwOWadA5s5blL6ev39OXDNhmOesEoo33eZtrq2N0YrU3H."
reserved: true
description: "Demo OpenSearch Dashboards user"

kibanaro:
hash: "$2a$12$JJSXNfTowz7Uu5ttXfeYpeYE0arACvcwlPBStB1F.MI7f0U9Z4DGC"
reserved: false
backend_roles:
- "kibanauser"
- "readall"
attributes:
attribute1: "value1"
attribute2: "value2"
attribute3: "value3"
description: "Demo OpenSearch Dashboards read only user, using external role mapping"

logstash:
hash: "$2a$12$u1ShR4l4uBS3Uv59Pa2y5.1uQuZBrZtmNfqB3iM/.jL0XoV9sghS2"
reserved: false
backend_roles:
- "logstash"
description: "Demo logstash user, using external role mapping"

readall:
hash: "$2a$12$ae4ycwzwvLtZxwZ82RmiEunBbIPiAmGZduBAjKN0TXdwQFtCwARz2"
reserved: false
backend_roles:
- "readall"
description: "Demo readall user, using external role mapping"

snapshotrestore:
hash: "$2y$12$DpwmetHKwgYnorbgdvORCenv4NAK8cPUg8AI6pxLCuWf/ALc0.v7W"
reserved: false
backend_roles:
- "snapshotrestore"
description: "Demo snapshotrestore user, using external role mapping"
Original file line number Diff line number Diff line change
Expand Up @@ -1830,7 +1830,6 @@ public void onNodeStarted(DiscoveryNode localNode) {
cr.initOnNodeStart();
}
this.localNode.set(localNode);
this.userService.setDefaultAdminPassword(settings.get(ConfigConstants.SECURITY_AUTHCZ_ADMIN_DEFAULT_PASSWORD, "admin"));
final Set<ModuleInfo> securityModules = ReflectionHelper.getModulesLoaded();
log.info("{} OpenSearch Security modules loaded so far: {}", securityModules.size(), securityModules);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,15 @@

package org.opensearch.security.configuration;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableMap;
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.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
Expand All @@ -41,13 +49,8 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.opensearch.ExceptionsHelper;
import org.opensearch.OpenSearchException;
import org.opensearch.ResourceAlreadyExistsException;
Expand All @@ -63,9 +66,9 @@
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.common.util.concurrent.ThreadContext.StoredContext;
import org.opensearch.core.common.Strings;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.env.Environment;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.security.auditlog.AuditLog;
import org.opensearch.security.auditlog.config.AuditConfig;
import org.opensearch.security.securityconf.DynamicConfigFactory;
Expand All @@ -76,6 +79,7 @@
import org.opensearch.security.support.ConfigHelper;
import org.opensearch.security.support.SecurityUtils;
import org.opensearch.threadpool.ThreadPool;
import static org.opensearch.security.dlic.rest.support.Utils.hash;

public class ConfigurationRepository {
private static final Logger LOGGER = LogManager.getLogger(ConfigurationRepository.class);
Expand Down Expand Up @@ -152,6 +156,7 @@ private ConfigurationRepository(
CType.ROLESMAPPING,
DEFAULT_CONFIG_VERSION
);
replaceAdminPassword(cd);
ConfigHelper.uploadFile(
client,
cd + "internal_users.yml",
Expand Down Expand Up @@ -488,4 +493,33 @@ private static String formatDate(long date) {
public static int getDefaultConfigVersion() {
return ConfigurationRepository.DEFAULT_CONFIG_VERSION;
}

private void replaceAdminPassword(String filePath) {
String plainText = settings.get(ConfigConstants.SECURITY_AUTHCZ_ADMIN_DEFAULT_PASSWORD, "admin");
String hashedPassword = hash(plainText.toCharArray());
File internalUsersFile = new File(filePath + "internal_users.yml");

try (BufferedReader reader = new BufferedReader(new FileReader(internalUsersFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(internalUsersFile))) {

StringBuilder updatedContent = new StringBuilder();
String line;

while ((line = reader.readLine()) != null) {
// Check if the line contains the admin user's hash and update it
if (line.trim().startsWith("admin:") && line.contains("hash:")) {
updatedContent.append("admin:\n");
updatedContent.append(" hash: ").append(hashedPassword).append("\n");
} else {
updatedContent.append(line).append("\n");
}
}

// Write the updated content back to the internal_users.yml file
writer.write(updatedContent.toString());
} catch (IOException e) {
// Handle the exception
e.printStackTrace();
}
}
}
33 changes: 0 additions & 33 deletions src/main/java/org/opensearch/security/user/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -314,37 +314,4 @@ public static void saveAndUpdateConfigs(
throw ExceptionsHelper.convertToOpenSearchException(e);
}
}

/**
* This method updates the default admin password by modifying the internal user store on node start.
*
* @param plainTextPassword The default password to be used -- specified in the opensearch.yml file
*/
public void setDefaultAdminPassword(String plainTextPassword) {
final SecurityDynamicConfiguration<?> internalUsersConfiguration = load(getUserConfigName(), false);

try {

if (!internalUsersConfiguration.exists("admin")) {
throw new UserServiceException(FAILED_ACCOUNT_RETRIEVAL_MESSAGE);
}

DefaultObjectMapper mapper = new DefaultObjectMapper();
JsonNode accountDetails = mapper.readTree(internalUsersConfiguration.getCEntry("admin").toString());
final ObjectNode contentAsNode = (ObjectNode) accountDetails;
contentAsNode.put("hash", hash(plainTextPassword.toCharArray()));

internalUsersConfiguration.remove("admin");
contentAsNode.remove("name");
internalUsersConfiguration.putCObject(
"admin",
DefaultObjectMapper.readTree(contentAsNode, internalUsersConfiguration.getImplementingClass())
);
saveAndUpdateConfigs(getUserConfigName().toString(), client, CType.INTERNALUSERS, internalUsersConfiguration);
} catch (IOException e) {
throw ExceptionsHelper.convertToOpenSearchException(e);
} catch (UserServiceException e) {
throw ExceptionsHelper.convertToOpenSearchException(e);
}
}
}

0 comments on commit 900c4db

Please sign in to comment.