-
Notifications
You must be signed in to change notification settings - Fork 282
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
[Security/Extension] Extension Authentication Backend #2672
Merged
RyanL1997
merged 17 commits into
opensearch-project:feature/extensions
from
RyanL1997:authentication-backend
May 11, 2023
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
38c2b5a
First commit to authentication-backend
RyanL1997 125a01e
Fix all test cases except testRolesArray
RyanL1997 4bba241
Add licences header and remove unused imports
RyanL1997 18c6687
Fix testRolesArray test
RyanL1997 b71df7d
Refactor some variables
RyanL1997 a74f5c6
Refactor 2nd
RyanL1997 77c70cb
Apply some coding suggestions
RyanL1997 d6ed7b9
Refactor the class under security pkgs
RyanL1997 a25f476
Checking word Bearer
RyanL1997 203b7b1
Fix some comments
RyanL1997 54135c7
Fix some if statements
RyanL1997 13a46a8
Fix error msgs
RyanL1997 0f5eb60
Remove bwcmode check
RyanL1997 725e7fe
Change some comments from dec_r into dr
RyanL1997 e4b8fbe
Fix variable name
RyanL1997 24f16b3
Remove unused imports
RyanL1997 6ee029c
change the term extension into ext in todo comment
RyanL1997 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
272 changes: 272 additions & 0 deletions
272
src/main/java/org/opensearch/security/http/HTTPOnBehalfOfJwtAuthenticator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,272 @@ | ||
/* | ||
* 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.http; | ||
|
||
import java.security.AccessController; | ||
import java.security.Key; | ||
import java.security.KeyFactory; | ||
import java.security.NoSuchAlgorithmException; | ||
import java.security.PrivilegedAction; | ||
import java.security.PublicKey; | ||
import java.security.spec.InvalidKeySpecException; | ||
import java.security.spec.X509EncodedKeySpec; | ||
import java.util.Arrays; | ||
import java.util.Map.Entry; | ||
import java.util.regex.Pattern; | ||
|
||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.JwtParser; | ||
import io.jsonwebtoken.Jwts; | ||
import io.jsonwebtoken.io.Decoders; | ||
import io.jsonwebtoken.security.WeakKeyException; | ||
import org.apache.commons.lang3.RandomStringUtils; | ||
import org.apache.hc.core5.http.HttpHeaders; | ||
import org.apache.logging.log4j.LogManager; | ||
import org.apache.logging.log4j.Logger; | ||
import org.greenrobot.eventbus.Subscribe; | ||
|
||
import org.opensearch.OpenSearchSecurityException; | ||
import org.opensearch.SpecialPermission; | ||
import org.opensearch.common.util.concurrent.ThreadContext; | ||
import org.opensearch.rest.RestChannel; | ||
import org.opensearch.rest.RestRequest; | ||
import org.opensearch.security.auth.HTTPAuthenticator; | ||
import org.opensearch.security.authtoken.jwt.EncryptionDecryptionUtil; | ||
import org.opensearch.security.securityconf.DynamicConfigModel; | ||
import org.opensearch.security.user.AuthCredentials; | ||
|
||
public class HTTPOnBehalfOfJwtAuthenticator implements HTTPAuthenticator { | ||
|
||
protected final Logger log = LogManager.getLogger(this.getClass()); | ||
|
||
private static final Pattern BEARER = Pattern.compile("^\\s*Bearer\\s.*", Pattern.CASE_INSENSITIVE); | ||
private static final String BEARER_PREFIX = "bearer "; | ||
|
||
//TODO: TO SEE IF WE NEED THE FINAL FOR FOLLOWING | ||
private JwtParser jwtParser; | ||
private String subjectKey; | ||
|
||
private String signingKey; | ||
private String encryptionKey; | ||
|
||
public HTTPOnBehalfOfJwtAuthenticator() { | ||
super(); | ||
init(); | ||
} | ||
|
||
// FOR TESTING | ||
public HTTPOnBehalfOfJwtAuthenticator(String signingKey, String encryptionKey){ | ||
this.signingKey = signingKey; | ||
this.encryptionKey = encryptionKey; | ||
init(); | ||
} | ||
|
||
private void init() { | ||
|
||
try { | ||
if(signingKey == null || signingKey.length() == 0) { | ||
log.error("signingKey must not be null or empty. JWT authentication will not work"); | ||
} else { | ||
|
||
signingKey = signingKey.replace("-----BEGIN PUBLIC KEY-----\n", ""); | ||
signingKey = signingKey.replace("-----END PUBLIC KEY-----", ""); | ||
|
||
byte[] decoded = Decoders.BASE64.decode(signingKey); | ||
Key key = null; | ||
|
||
try { | ||
key = getPublicKey(decoded, "RSA"); | ||
} catch (Exception e) { | ||
log.debug("No public RSA key, try other algos ({})", e.toString()); | ||
} | ||
|
||
try { | ||
key = getPublicKey(decoded, "EC"); | ||
} catch (Exception e) { | ||
log.debug("No public ECDSA key, try other algos ({})", e.toString()); | ||
} | ||
|
||
if(key != null) { | ||
jwtParser = Jwts.parser().setSigningKey(key); | ||
} else { | ||
jwtParser = Jwts.parser().setSigningKey(decoded); | ||
} | ||
|
||
} | ||
} catch (Throwable e) { | ||
log.error("Error while creating JWT authenticator", e); | ||
throw new RuntimeException(e); | ||
} | ||
|
||
subjectKey = "sub"; | ||
} | ||
|
||
@Override | ||
@SuppressWarnings("removal") | ||
public AuthCredentials extractCredentials(RestRequest request, ThreadContext context) throws OpenSearchSecurityException { | ||
final SecurityManager sm = System.getSecurityManager(); | ||
|
||
if (sm != null) { | ||
sm.checkPermission(new SpecialPermission()); | ||
} | ||
|
||
AuthCredentials creds = AccessController.doPrivileged(new PrivilegedAction<AuthCredentials>() { | ||
@Override | ||
public AuthCredentials run() { | ||
return extractCredentials0(request); | ||
} | ||
}); | ||
|
||
return creds; | ||
} | ||
|
||
private AuthCredentials extractCredentials0(final RestRequest request) { | ||
if (jwtParser == null) { | ||
log.error("Missing Signing Key. JWT authentication will not work"); | ||
return null; | ||
} | ||
|
||
String jwtToken = request.header(HttpHeaders.AUTHORIZATION); | ||
|
||
if (jwtToken == null || jwtToken.length() == 0) { | ||
if(log.isDebugEnabled()) { | ||
log.debug("No JWT token found in '{}' header", HttpHeaders.AUTHORIZATION); | ||
} | ||
return null; | ||
} | ||
|
||
if (!BEARER.matcher(jwtToken).matches()) { | ||
jwtToken = null; | ||
} | ||
|
||
final int index; | ||
if((index = jwtToken.toLowerCase().indexOf(BEARER_PREFIX)) > -1) { //detect Bearer | ||
jwtToken = jwtToken.substring(index+BEARER_PREFIX.length()); | ||
} else { | ||
if(log.isDebugEnabled()) { | ||
log.debug("No Bearer scheme found in header"); | ||
} | ||
} | ||
|
||
try { | ||
final Claims claims = jwtParser.parseClaimsJws(jwtToken).getBody(); | ||
|
||
final String subject = extractSubject(claims, request); | ||
|
||
final String audience = claims.getAudience(); | ||
|
||
//TODO: GET ROLESCLAIM DEPENDING ON THE STATUS OF BWC MODE. ON: er / OFF: dr | ||
Object rolesObject = null; | ||
String[] roles; | ||
|
||
try { | ||
rolesObject = claims.get("er"); | ||
} catch (Throwable e) { | ||
log.debug("No encrypted role founded in the claim, continue searching for decrypted roles."); | ||
} | ||
|
||
try { | ||
rolesObject = claims.get("dr"); | ||
} catch (Throwable e) { | ||
log.debug("No decrypted role founded in the claim."); | ||
} | ||
|
||
if (rolesObject == null) { | ||
log.warn( | ||
"Failed to get roles from JWT claims. Check if this key is correct and available in the JWT payload."); | ||
roles = new String[0]; | ||
} else { | ||
final String rolesClaim = rolesObject.toString(); | ||
|
||
// Extracting roles based on the compatbility mode | ||
String decryptedRoles = rolesClaim; | ||
if (rolesObject == claims.get("er")) { | ||
//TODO: WHERE TO GET THE ENCRYTION KEY | ||
decryptedRoles = EncryptionDecryptionUtil.decrypt(encryptionKey, rolesClaim); | ||
} | ||
roles = Arrays.stream(decryptedRoles.split(",")).map(String::trim).toArray(String[]::new); | ||
} | ||
|
||
if (subject == null) { | ||
log.error("No subject found in JWT token"); | ||
return null; | ||
} | ||
|
||
if (audience == null) { | ||
log.error("No audience found in JWT token"); | ||
} | ||
|
||
final AuthCredentials ac = new AuthCredentials(subject, roles).markComplete(); | ||
|
||
for(Entry<String, Object> claim: claims.entrySet()) { | ||
ac.addAttribute("attr.jwt."+claim.getKey(), String.valueOf(claim.getValue())); | ||
} | ||
|
||
return ac; | ||
|
||
} catch (WeakKeyException e) { | ||
log.error("Cannot authenticate user with JWT because of ", e); | ||
return null; | ||
} catch (Exception e) { | ||
if(log.isDebugEnabled()) { | ||
log.debug("Invalid or expired JWT token.", e); | ||
} | ||
return null; | ||
} | ||
} | ||
|
||
@Override | ||
public boolean reRequestAuthentication(final RestChannel channel, AuthCredentials creds) { | ||
return false; | ||
} | ||
|
||
@Override | ||
public String getType() { | ||
return "onbehalfof_jwt"; | ||
} | ||
|
||
//TODO: Extract the audience (ext_id) and inject it into thread context | ||
|
||
protected String extractSubject(final Claims claims, final RestRequest request) { | ||
String subject = claims.getSubject(); | ||
if(subjectKey != null) { | ||
// try to get roles from claims, first as Object to avoid having to catch the ExpectedTypeException | ||
Object subjectObject = claims.get(subjectKey, Object.class); | ||
if(subjectObject == null) { | ||
log.warn("Failed to get subject from JWT claims, check if subject_key '{}' is correct.", subjectKey); | ||
return null; | ||
} | ||
// We expect a String. If we find something else, convert to String but issue a warning | ||
if(!(subjectObject instanceof String)) { | ||
log.warn("Expected type String in the JWT for subject_key {}, but value was '{}' ({}). Will convert this value to String.", subjectKey, subjectObject, subjectObject.getClass()); | ||
} | ||
subject = String.valueOf(subjectObject); | ||
} | ||
return subject; | ||
} | ||
|
||
private static PublicKey getPublicKey(final byte[] keyBytes, final String algo) throws NoSuchAlgorithmException, InvalidKeySpecException { | ||
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); | ||
KeyFactory kf = KeyFactory.getInstance(algo); | ||
return kf.generatePublic(spec); | ||
} | ||
|
||
@Subscribe | ||
public void onDynamicConfigModelChanged(DynamicConfigModel dcm) { | ||
|
||
//TODO: #2615 FOR CONFIGURATION | ||
//For Testing | ||
signingKey = "abcd1234"; | ||
encryptionKey = RandomStringUtils.randomAlphanumeric(16); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not sure what "er" means. I know there are some conflicting opinions, but I am of the mind that we lose meaning at a certain point of abbreviating things. I am guessing this stands for "____ roles"? Perhaps we can make this a more meaningful key?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i think
er
stands forencrypted roles
.