Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implements token handlers and tests #2787

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/integrationTest/resources/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,6 @@ config:
authentication_backend:
type: "internal"
config: {}
on_behalf_of:
signing_key: "signing key"
encryption_key: "encryption key"
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,17 @@
import org.opensearch.extensions.ExtensionsManager;
import org.opensearch.http.HttpServerTransport;
import org.opensearch.http.HttpServerTransport.Dispatcher;
import org.opensearch.identity.Subject;
import org.opensearch.identity.tokens.TokenManager;
import org.opensearch.core.index.Index;

import org.opensearch.index.IndexModule;
import org.opensearch.index.cache.query.QueryCache;
import org.opensearch.indices.IndicesService;
import org.opensearch.indices.SystemIndexDescriptor;
import org.opensearch.indices.breaker.CircuitBreakerService;
import org.opensearch.plugins.ClusterPlugin;
import org.opensearch.plugins.IdentityPlugin;
import org.opensearch.plugins.MapperPlugin;
import org.opensearch.repositories.RepositoriesService;
import org.opensearch.rest.RestController;
Expand Down Expand Up @@ -142,9 +146,11 @@
import org.opensearch.security.dlic.rest.validation.PasswordValidator;
import org.opensearch.security.filter.SecurityFilter;
import org.opensearch.security.filter.SecurityRestFilter;
import org.opensearch.security.http.HTTPOnBehalfOfJwtAuthenticator;
import org.opensearch.security.http.SecurityHttpServerTransport;
import org.opensearch.security.http.SecurityNonSslHttpServerTransport;
import org.opensearch.security.http.XFFResolver;
import org.opensearch.security.identity.SecurityTokenManager;
import org.opensearch.security.privileges.PrivilegesEvaluator;
import org.opensearch.security.privileges.PrivilegesInterceptor;
import org.opensearch.security.privileges.RestLayerPrivilegesEvaluator;
Expand Down Expand Up @@ -193,7 +199,7 @@
import org.opensearch.watcher.ResourceWatcherService;
// CS-ENFORCE-SINGLE

public final class OpenSearchSecurityPlugin extends OpenSearchSecuritySSLPlugin implements ClusterPlugin, MapperPlugin {
public final class OpenSearchSecurityPlugin extends OpenSearchSecuritySSLPlugin implements ClusterPlugin, MapperPlugin, IdentityPlugin {

private static final String KEYWORD = ".keyword";
private static final Logger actionTrace = LogManager.getLogger("opendistro_security_action_trace");
Expand All @@ -207,7 +213,9 @@ public final class OpenSearchSecurityPlugin extends OpenSearchSecuritySSLPlugin
private volatile SecurityInterceptor si;
private volatile PrivilegesEvaluator evaluator;
private volatile UserService userService;
private volatile SecurityTokenManager securityTokenManager;
private volatile RestLayerPrivilegesEvaluator restLayerEvaluator;

private volatile ThreadPool threadPool;
private volatile ConfigurationRepository cr;
private volatile AdminDNs adminDns;
Expand Down Expand Up @@ -992,6 +1000,8 @@ public Collection<Object> createComponents(

userService = new UserService(cs, cr, settings, localClient);

securityTokenManager = new SecurityTokenManager(threadPool, clusterService, cr, localClient, settings, userService);

final XFFResolver xffResolver = new XFFResolver(threadPool);
backendRegistry = new BackendRegistry(settings, adminDns, xffResolver, auditLog, threadPool);

Expand Down Expand Up @@ -1036,6 +1046,8 @@ public Collection<Object> createComponents(
compatConfig
);

HTTPOnBehalfOfJwtAuthenticator acInstance = new HTTPOnBehalfOfJwtAuthenticator();

final DynamicConfigFactory dcf = new DynamicConfigFactory(cr, settings, configPath, localClient, threadPool, cih);
dcf.registerDCFListener(backendRegistry);
dcf.registerDCFListener(compatConfig);
Expand All @@ -1044,6 +1056,7 @@ public Collection<Object> createComponents(
dcf.registerDCFListener(evaluator);
dcf.registerDCFListener(restLayerEvaluator);
dcf.registerDCFListener(securityRestHandler);
dcf.registerDCFListener(acInstance);
if (!(auditLog instanceof NullAuditLog)) {
// Don't register if advanced modules is disabled in which case auditlog is instance of NullAuditLog
dcf.registerDCFListener(auditLog);
Expand Down Expand Up @@ -1886,12 +1899,23 @@ private static String handleKeyword(final String field) {
return field;
}


@Override
public Subject getSubject() {
return null;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we return some form of NoOp subject here instead of null?

}

@Override
public TokenManager getTokenManager() {
return securityTokenManager;

public static DiscoveryNode getLocalNode() {
return localNode;
}

public static void setLocalNode(DiscoveryNode node) {
localNode = node;

}

public static class GuiceHolder implements LifecycleComponent {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* 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.authtoken.jwt;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDecryptionUtil {

public static String encrypt(final String secret, final String data) {

byte[] decodedKey = Base64.getDecoder().decode(secret);

try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.ENCRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(cipherText);
} catch (Exception e) {
throw new RuntimeException("Error occurred while encrypting data", e);
}
}

public static String decrypt(final String secret, final String encryptedString) {

byte[] decodedKey = Base64.getDecoder().decode(secret);

try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
return new String(cipherText, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("Error occured while decrypting data", e);
}
}
}
191 changes: 191 additions & 0 deletions src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
/*
* 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.authtoken.jwt;

import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.LongSupplier;

import com.google.common.base.Strings;
import org.apache.cxf.jaxrs.json.basic.JsonMapObjectReaderWriter;
import org.apache.cxf.rs.security.jose.jwk.JsonWebKey;
import org.apache.cxf.rs.security.jose.jwk.KeyType;
import org.apache.cxf.rs.security.jose.jwk.PublicKeyUse;
import org.apache.cxf.rs.security.jose.jws.JwsUtils;
import org.apache.cxf.rs.security.jose.jwt.JoseJwtProducer;
import org.apache.cxf.rs.security.jose.jwt.JwtClaims;
import org.apache.cxf.rs.security.jose.jwt.JwtToken;
import org.apache.cxf.rs.security.jose.jwt.JwtUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.opensearch.common.settings.Settings;
import org.opensearch.common.transport.TransportAddress;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.security.securityconf.ConfigModel;
import org.opensearch.security.support.ConfigConstants;
import org.opensearch.security.user.User;
import org.opensearch.threadpool.ThreadPool;

public class JwtVendor {
private static final Logger logger = LogManager.getLogger(JwtVendor.class);

private static JsonMapObjectReaderWriter jsonMapReaderWriter = new JsonMapObjectReaderWriter();

private String claimsEncryptionKey;
private JsonWebKey signingKey;
private JoseJwtProducer jwtProducer;
private final LongSupplier timeProvider;

// TODO: Relocate/Remove them at once we make the descisions about the `roles`
private ConfigModel configModel;
private ThreadContext threadContext;

public JwtVendor(Settings settings) {
JoseJwtProducer jwtProducer = new JoseJwtProducer();
try {
this.signingKey = createJwkFromSettings(settings);
} catch (Exception e) {
throw new RuntimeException(e);
}
this.jwtProducer = jwtProducer;
if (settings.get("encryption_key") == null) {
throw new RuntimeException("encryption_key cannot be null");
} else {
this.claimsEncryptionKey = settings.get("encryption_key");
}
timeProvider = System::currentTimeMillis;
}

// For testing the expiration in the future
public JwtVendor(Settings settings, final LongSupplier timeProvider) {
JoseJwtProducer jwtProducer = new JoseJwtProducer();
try {
this.signingKey = createJwkFromSettings(settings);
} catch (Exception e) {
throw new RuntimeException(e);
}
this.jwtProducer = jwtProducer;
if (settings.get("encryption_key") == null) {
throw new RuntimeException("encryption_key cannot be null");
} else {
this.claimsEncryptionKey = settings.get("encryption_key");
}
this.timeProvider = timeProvider;
}

/*
* The default configuration of this web key should be:
* KeyType: OCTET
* PublicKeyUse: SIGN
* Encryption Algorithm: HS512
* */
static JsonWebKey createJwkFromSettings(Settings settings) throws Exception {
String signingKey = settings.get("signing_key");

if (!Strings.isNullOrEmpty(signingKey)) {

JsonWebKey jwk = new JsonWebKey();

jwk.setKeyType(KeyType.OCTET);
jwk.setAlgorithm("HS512");
jwk.setPublicKeyUse(PublicKeyUse.SIGN);
jwk.setProperty("k", signingKey);

return jwk;
} else {
Settings jwkSettings = settings.getAsSettings("jwt").getAsSettings("key");

if (jwkSettings.isEmpty()) {
throw new Exception("Settings for key is missing. Please specify at least the option signing_key with a shared secret.");
}

JsonWebKey jwk = new JsonWebKey();

for (String key : jwkSettings.keySet()) {
jwk.setProperty(key, jwkSettings.get(key));
}

return jwk;
}
}

// TODO:Getting roles from User
public Map<String, String> prepareClaimsForUser(User user, ThreadPool threadPool) {
Map<String, String> claims = new HashMap<>();
this.threadContext = threadPool.getThreadContext();
final TransportAddress caller = threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_REMOTE_ADDRESS);
Set<String> mappedRoles = mapRoles(user, caller);
claims.put("sub", user.getName());
claims.put("roles", String.join(",", mappedRoles));
return claims;
}

public Set<String> mapRoles(final User user, final TransportAddress caller) {
return this.configModel.mapSecurityRoles(user, caller);
}

public String createJwt(String issuer, String subject, String audience, Integer expirySeconds, List<String> roles) throws Exception {
long timeMillis = timeProvider.getAsLong();
Instant now = Instant.ofEpochMilli(timeProvider.getAsLong());

jwtProducer.setSignatureProvider(JwsUtils.getSignatureProvider(signingKey));
JwtClaims jwtClaims = new JwtClaims();
JwtToken jwt = new JwtToken(jwtClaims);

jwtClaims.setIssuer(issuer);

jwtClaims.setIssuedAt(timeMillis);

jwtClaims.setSubject(subject);

jwtClaims.setAudience(audience);

jwtClaims.setNotBefore(timeMillis);

if (expirySeconds == null) {
long expiryTime = timeProvider.getAsLong() + (300 * 1000);
jwtClaims.setExpiryTime(expiryTime);
} else if (expirySeconds > 0) {
long expiryTime = timeProvider.getAsLong() + (expirySeconds * 1000);
jwtClaims.setExpiryTime(expiryTime);
} else {
throw new Exception("The expiration time should be a positive integer");
}

// TODO: IF USER ENABLES THE BWC MODE, WE ARE EXPECTING TO SET PLAIN TEXT ROLE AS `dr`
if (roles != null) {
String listOfRoles = String.join(",", roles);
jwtClaims.setProperty("er", EncryptionDecryptionUtil.encrypt(claimsEncryptionKey, listOfRoles));
} else {
throw new Exception("Roles cannot be null");
}

String encodedJwt = jwtProducer.processJwt(jwt);

if (logger.isDebugEnabled()) {
logger.debug(
"Created JWT: "
+ encodedJwt
+ "\n"
+ jsonMapReaderWriter.toJson(jwt.getJwsHeaders())
+ "\n"
+ JwtUtils.claimsToJson(jwt.getClaims())
);
}

return encodedJwt;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import java.io.IOException;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import com.fasterxml.jackson.databind.JsonNode;
Expand Down Expand Up @@ -158,6 +159,8 @@ protected void handlePut(RestChannel channel, final RestRequest request, final C
return;
} catch (IOException ex) {
throw new IOException(ex);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}

// for existing users, hash is optional
Expand Down
Loading
Loading