|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License |
| 4 | + * 2.0; you may not use this file except in compliance with the Elastic License |
| 5 | + * 2.0. |
| 6 | + */ |
| 7 | + |
| 8 | +package org.elasticsearch.xpack.security.authc.service; |
| 9 | + |
| 10 | +import org.apache.logging.log4j.LogManager; |
| 11 | +import org.apache.logging.log4j.Logger; |
| 12 | +import org.apache.logging.log4j.message.ParameterizedMessage; |
| 13 | +import org.elasticsearch.ElasticsearchSecurityException; |
| 14 | +import org.elasticsearch.Version; |
| 15 | +import org.elasticsearch.action.ActionListener; |
| 16 | +import org.elasticsearch.common.CharArrays; |
| 17 | +import org.elasticsearch.common.hash.MessageDigests; |
| 18 | +import org.elasticsearch.common.io.stream.InputStreamStreamInput; |
| 19 | +import org.elasticsearch.common.io.stream.StreamInput; |
| 20 | +import org.elasticsearch.common.settings.SecureString; |
| 21 | +import org.elasticsearch.common.util.concurrent.ThreadContext; |
| 22 | +import org.elasticsearch.xpack.core.security.authc.Authentication; |
| 23 | +import org.elasticsearch.xpack.core.security.authz.RoleDescriptor; |
| 24 | +import org.elasticsearch.xpack.core.security.user.User; |
| 25 | +import org.elasticsearch.xpack.security.authc.service.ServiceAccount.ServiceAccountId; |
| 26 | +import org.elasticsearch.xpack.security.authc.support.SecurityTokenType; |
| 27 | + |
| 28 | +import java.io.ByteArrayInputStream; |
| 29 | +import java.io.IOException; |
| 30 | +import java.util.Base64; |
| 31 | +import java.util.Map; |
| 32 | + |
| 33 | +import static org.elasticsearch.xpack.security.authc.service.ElasticServiceAccounts.ACCOUNTS; |
| 34 | + |
| 35 | +public class ServiceAccountService { |
| 36 | + |
| 37 | + public static final String REALM_TYPE = "service_account"; |
| 38 | + public static final String REALM_NAME = "service_account"; |
| 39 | + public static final Version VERSION_MINIMUM = Version.V_8_0_0; |
| 40 | + |
| 41 | + private static final Logger logger = LogManager.getLogger(ServiceAccountService.class); |
| 42 | + |
| 43 | + private final ServiceAccountsCredentialStore serviceAccountsCredentialStore; |
| 44 | + |
| 45 | + public ServiceAccountService(ServiceAccountsCredentialStore serviceAccountsCredentialStore) { |
| 46 | + this.serviceAccountsCredentialStore = serviceAccountsCredentialStore; |
| 47 | + } |
| 48 | + |
| 49 | + public static boolean isServiceAccount(Authentication authentication) { |
| 50 | + return REALM_TYPE.equals(authentication.getAuthenticatedBy().getType()) && null == authentication.getLookedUpBy(); |
| 51 | + } |
| 52 | + |
| 53 | + // {@link org.elasticsearch.xpack.security.authc.TokenService#extractBearerTokenFromHeader extracted} from an HTTP authorization header. |
| 54 | + /** |
| 55 | + * Parses a token object from the content of a {@link ServiceAccountToken#asBearerString()} bearer string}. |
| 56 | + * This bearer string would typically be |
| 57 | + * |
| 58 | + * <p> |
| 59 | + * <strong>This method does not validate the credential, it simply parses it.</strong> |
| 60 | + * There is no guarantee that the {@link ServiceAccountToken#getSecret() secret} is valid, |
| 61 | + * or even that the {@link ServiceAccountToken#getAccountId() account} exists. |
| 62 | + * </p> |
| 63 | + * @param token A raw token string (if this is from an HTTP header, then the <code>"Bearer "</code> prefix must be removed before |
| 64 | + * calling this method. |
| 65 | + * @return An unvalidated token object. |
| 66 | + */ |
| 67 | + public static ServiceAccountToken tryParseToken(SecureString token) { |
| 68 | + try { |
| 69 | + if (token == null) { |
| 70 | + return null; |
| 71 | + } |
| 72 | + return doParseToken(token); |
| 73 | + } catch (IOException e) { |
| 74 | + logger.debug("Cannot parse possible service account token", e); |
| 75 | + return null; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + public void authenticateWithToken(ServiceAccountToken token, ThreadContext threadContext, String nodeName, |
| 80 | + ActionListener<Authentication> listener) { |
| 81 | + |
| 82 | + if (ElasticServiceAccounts.NAMESPACE.equals(token.getAccountId().namespace()) == false) { |
| 83 | + final ParameterizedMessage message = new ParameterizedMessage( |
| 84 | + "only [{}] service accounts are supported, but received [{}]", |
| 85 | + ElasticServiceAccounts.NAMESPACE, token.getAccountId().asPrincipal()); |
| 86 | + logger.debug(message); |
| 87 | + listener.onFailure(new ElasticsearchSecurityException(message.getFormattedMessage())); |
| 88 | + return; |
| 89 | + } |
| 90 | + |
| 91 | + final ServiceAccount account = ACCOUNTS.get(token.getAccountId().serviceName()); |
| 92 | + if (account == null) { |
| 93 | + final ParameterizedMessage message = new ParameterizedMessage( |
| 94 | + "the [{}] service account does not exist", token.getAccountId().asPrincipal()); |
| 95 | + logger.debug(message); |
| 96 | + listener.onFailure(new ElasticsearchSecurityException(message.getFormattedMessage())); |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + if (serviceAccountsCredentialStore.authenticate(token)) { |
| 101 | + listener.onResponse(success(account, token, nodeName)); |
| 102 | + } else { |
| 103 | + final ParameterizedMessage message = new ParameterizedMessage( |
| 104 | + "failed to authenticate service account [{}] with token name [{}]", |
| 105 | + token.getAccountId().asPrincipal(), |
| 106 | + token.getTokenName()); |
| 107 | + logger.debug(message); |
| 108 | + listener.onFailure(new ElasticsearchSecurityException(message.getFormattedMessage())); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + public void getRoleDescriptor(Authentication authentication, ActionListener<RoleDescriptor> listener) { |
| 113 | + assert isServiceAccount(authentication) : "authentication is not for service account: " + authentication; |
| 114 | + |
| 115 | + final ServiceAccountId accountId = ServiceAccountId.fromPrincipal(authentication.getUser().principal()); |
| 116 | + final ServiceAccount account = ACCOUNTS.get(accountId.serviceName()); |
| 117 | + if (account == null) { |
| 118 | + listener.onFailure(new ElasticsearchSecurityException( |
| 119 | + "cannot load role for service account [" + accountId.asPrincipal() + "] - no such service account" |
| 120 | + )); |
| 121 | + return; |
| 122 | + } |
| 123 | + listener.onResponse(account.roleDescriptor()); |
| 124 | + } |
| 125 | + |
| 126 | + private Authentication success(ServiceAccount account, ServiceAccountToken token, String nodeName) { |
| 127 | + final User user = account.asUser(); |
| 128 | + final Authentication.RealmRef authenticatedBy = new Authentication.RealmRef(REALM_NAME, REALM_TYPE, nodeName); |
| 129 | + return new Authentication(user, authenticatedBy, null, Version.CURRENT, Authentication.AuthenticationType.TOKEN, |
| 130 | + Map.of("_token_name", token.getTokenName())); |
| 131 | + } |
| 132 | + |
| 133 | + |
| 134 | + |
| 135 | + private static ServiceAccountToken doParseToken(SecureString token) throws IOException { |
| 136 | + final byte[] bytes = CharArrays.toUtf8Bytes(token.getChars()); |
| 137 | + logger.trace("parsing token bytes {}", MessageDigests.toHexString(bytes)); |
| 138 | + try (StreamInput in = new InputStreamStreamInput(Base64.getDecoder().wrap(new ByteArrayInputStream(bytes)), bytes.length)) { |
| 139 | + final Version version = Version.readVersion(in); |
| 140 | + in.setVersion(version); |
| 141 | + if (version.before(VERSION_MINIMUM)) { |
| 142 | + logger.trace("token has version {}, but we need at least {}", version, VERSION_MINIMUM); |
| 143 | + return null; |
| 144 | + } |
| 145 | + final SecurityTokenType tokenType = SecurityTokenType.read(in); |
| 146 | + if (tokenType != SecurityTokenType.SERVICE_ACCOUNT) { |
| 147 | + logger.trace("token is of type {}, but we only handle {}", tokenType, SecurityTokenType.SERVICE_ACCOUNT); |
| 148 | + return null; |
| 149 | + } |
| 150 | + |
| 151 | + final ServiceAccountId account = new ServiceAccountId(in); |
| 152 | + final String tokenName = in.readString(); |
| 153 | + final SecureString secret = in.readSecureString(); |
| 154 | + |
| 155 | + return new ServiceAccountToken(account, tokenName, secret); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | +} |
0 commit comments