org.elasticsearch.ElasticsearchSecurityException Java Examples

The following examples show how to use org.elasticsearch.ElasticsearchSecurityException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractHTTPJwtAuthenticator.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Override
public AuthCredentials extractCredentials(RestRequest request, ThreadContext context)
        throws ElasticsearchSecurityException {
    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;
}
 
Example #2
Source File: HTTPJwtAuthenticator.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Override
public AuthCredentials extractCredentials(RestRequest request, ThreadContext context) throws ElasticsearchSecurityException {
    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;
}
 
Example #3
Source File: OpenshiftAPIService.java    From openshift-elasticsearch-plugin with Apache License 2.0 6 votes vote down vote up
public String userName(final String token) {
    Response response = null;
    try (DefaultOpenShiftClient client = factory.buildClient(token)) {
        Request okRequest = new Request.Builder()
                .url(client.getMasterUrl() + "apis/user.openshift.io/v1/users/~")
                .header("Authorization", "Bearer " + token)
                .header(ACCEPT, APPLICATION_JSON)
                .build();
        response = client.getHttpClient().newCall(okRequest).execute();
        final String body = response.body().string();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response: code '{}' {}", response.code(), body);
        }
        if(response.code() != RestStatus.OK.getStatus()) {
            throw new ElasticsearchSecurityException("Unable to determine username from the token provided", RestStatus.fromCode(response.code()));
        }
        return JsonPath.read(body,"$.metadata.name");
    } catch (IOException e) {
        LOGGER.error("Error retrieving username from token", e);
        throw new ElasticsearchException(e);
    }        
}
 
Example #4
Source File: KerberosAuthenticationFailureHandler.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 6 votes vote down vote up
@Override
public ElasticsearchSecurityException exceptionProcessingRequest(final TransportMessage message, final Exception e) {
    final ElasticsearchSecurityException se = super.exceptionProcessingRequest(message, e);
    String outToken = "";

    if (e instanceof ElasticsearchException) {
        final ElasticsearchException kae = (ElasticsearchException) e;
        if (kae.getHeader("kerberos_out_token") != null) {
            outToken = " " + kae.getHeader("kerberos_out_token").get(0);
        }
    }
    se.addHeader(KrbConstants.WWW_AUTHENTICATE, KrbConstants.NEGOTIATE + outToken);

    if (logger.isDebugEnabled()) {
        logger.debug("exception for transport message: {}", e.toString());
    }

    return se;
}
 
Example #5
Source File: LDAPAuthenticationBackend2.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Override
public User authenticate(final AuthCredentials credentials) throws ElasticsearchSecurityException {
    final SecurityManager sm = System.getSecurityManager();

    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }

    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<User>() {
            @Override
            public User run() throws Exception {
                return authenticate0(credentials);
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getException() instanceof ElasticsearchSecurityException) {
            throw (ElasticsearchSecurityException) e.getException();
        } else if (e.getException() instanceof RuntimeException) {
            throw (RuntimeException) e.getException();
        } else {
            throw new RuntimeException(e.getException());
        }
    }
}
 
Example #6
Source File: KerberosAuthenticationFailureHandler.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 6 votes vote down vote up
@Override
public ElasticsearchSecurityException exceptionProcessingRequest(final RestRequest request, final Exception e) {
    final ElasticsearchSecurityException se = super.exceptionProcessingRequest(request, e);
    String outToken = "";
    if (e instanceof ElasticsearchException) {
        final ElasticsearchException kae = (ElasticsearchException) e;
        if (kae.getHeader("kerberos_out_token") != null) {
            outToken = " " + kae.getHeader("kerberos_out_token").get(0);
        }
    }

    se.addHeader(KrbConstants.WWW_AUTHENTICATE, KrbConstants.NEGOTIATE + outToken);

    if (logger.isDebugEnabled()) {
        logger.debug("exception for rest request: {}", e.toString());
    }

    return se;
}
 
Example #7
Source File: OpenShiftTokenAuthentication.java    From openshift-elasticsearch-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public AuthCredentials extractCredentials(RestRequest request, ThreadContext context)
        throws ElasticsearchSecurityException {
    if (PluginServiceFactory.isReady()) {
        OpenshiftRequestContextFactory contextFactory = PluginServiceFactory.getContextFactory();
        try {
            OpenshiftRequestContext requestContext = contextFactory.create(request);
            context.putTransient(ConfigurationSettings.OPENSHIFT_REQUEST_CONTEXT, requestContext);
            if (requestContext == OpenshiftRequestContext.EMPTY) {
                return null;
            }
            return new AuthCredentials(requestContext.getUser(), requestContext.getBackendRoles()).markComplete();
        } catch (ElasticsearchSecurityException ese) {
            throw ese;
        } catch (Exception e) {
            LOGGER.error("Error handling request", e);
        }
    }
    return null;
}
 
Example #8
Source File: ValidatingDispatcher.java    From deprecated-security-ssl with Apache License 2.0 6 votes vote down vote up
protected void checkRequest(final RestRequest request, final RestChannel channel) {
    
    if(SSLRequestHelper.containsBadHeader(threadContext, "_opendistro_security_ssl_")) {
        final ElasticsearchException exception = ExceptionUtils.createBadHeaderException();
        errorHandler.logError(exception, request, 1);
        throw exception;
    }
    
    try {
        if(SSLRequestHelper.getSSLInfo(settings, configPath, request, null) == null) {
            logger.error("Not an SSL request");
            throw new ElasticsearchSecurityException("Not an SSL request", RestStatus.INTERNAL_SERVER_ERROR);
        }
    } catch (SSLPeerUnverifiedException e) {
        logger.error("No client certificates found but such are needed (Security 8).");
        errorHandler.logError(e, request, 0);
        throw ExceptionsHelper.convertToElastic(e);
    }
}
 
Example #9
Source File: FileAuthenticationBackend.java    From openshift-elasticsearch-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public User authenticate(AuthCredentials credentials) throws ElasticsearchSecurityException {
    if (credentials == null) {
        throw new ElasticsearchSecurityException("Creditials are null while trying to authenticate");
    }
    Settings settings = loadAuthFile();
    if(exists(settings, credentials.getUsername())){
        final String hash = settings.get(credentials.getUsername() + PASSWD);
        if(StringUtils.isNotBlank(hash)) {
            final String saved = new String(DatatypeConverter.parseBase64Binary(hash), StandardCharsets.UTF_8).trim();
            final String presented = new String(credentials.getPassword());
            if(saved.equals(presented)) {
                return new User(credentials.getUsername());
            }
        }
    }
    throw new ElasticsearchSecurityException("Unable to authenticate {}", credentials.getUsername());
}
 
Example #10
Source File: KerberosAuthenticationFailureHandler.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException missingToken(final RestRequest request) {
    final ElasticsearchSecurityException e = super.missingToken(request);
    e.addHeader(KrbConstants.WWW_AUTHENTICATE, KrbConstants.NEGOTIATE);
    if (logger.isDebugEnabled()) {
        logger.debug("missing token for rest request");
    }
    return e;
}
 
Example #11
Source File: ModelsAction.java    From zentity with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve one entity model by its type.
 *
 * @param entityType The entity type.
 * @param client     The client that will communicate with Elasticsearch.
 * @return The response from Elasticsearch.
 * @throws ForbiddenException
 */
public static GetResponse getEntityModel(String entityType, NodeClient client) throws ForbiddenException {
    GetRequestBuilder request = client.prepareGet(INDEX_NAME, "doc", entityType);
    try {
        return request.get();
    } catch (IndexNotFoundException e) {
        try {
            SetupAction.createIndex(client);
        } catch (ElasticsearchSecurityException se) {
            throw new ForbiddenException("The .zentity-models index does not exist and you do not have the 'create_index' privilege. An authorized user must create the index by submitting: POST _zentity/_setup");
        }
        return request.get();
    }
}
 
Example #12
Source File: ModelsAction.java    From zentity with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve all entity models.
 *
 * @param client The client that will communicate with Elasticsearch.
 * @return The response from Elasticsearch.
 * @throws ForbiddenException
 */
public static SearchResponse getEntityModels(NodeClient client) throws ForbiddenException {
    SearchRequestBuilder request = client.prepareSearch(INDEX_NAME);
    request.setSize(10000);
    try {
        return request.get();
    } catch (IndexNotFoundException e) {
        try {
            SetupAction.createIndex(client);
        } catch (ElasticsearchSecurityException se) {
            throw new ForbiddenException("The .zentity-models index does not exist and you do not have the 'create_index' privilege. An authorized user must create the index by submitting: POST _zentity/_setup");
        }
        return request.get();
    }
}
 
Example #13
Source File: ModelsAction.java    From zentity with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the .zentity-models index exists, and if it doesn't, then create it.
 *
 * @param client The client that will communicate with Elasticsearch.
 * @throws ForbiddenException
 */
public static void ensureIndex(NodeClient client) throws ForbiddenException {
    try {
        IndicesExistsRequestBuilder request = client.admin().indices().prepareExists(INDEX_NAME);
        IndicesExistsResponse response = request.get();
        if (!response.isExists())
            SetupAction.createIndex(client);
    } catch (ElasticsearchSecurityException se) {
        throw new ForbiddenException("The .zentity-models index does not exist and you do not have the 'create_index' privilege. An authorized user must create the index by submitting: POST _zentity/_setup");
    }
}
 
Example #14
Source File: KerberosAuthenticationFailureHandler.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException unsuccessfulAuthentication(final RestRequest request, final AuthenticationToken token) {
    final ElasticsearchSecurityException e = super.unsuccessfulAuthentication(request, token);
    e.addHeader(KrbConstants.WWW_AUTHENTICATE, KrbConstants.NEGOTIATE);
    if (logger.isDebugEnabled()) {
        logger.debug("unsuccessfulAuthentication for rest request and token {}", token);
    }
    return e;
}
 
Example #15
Source File: OpenshiftAPIService.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Execute a LocalSubectAccessReview
 * 
 * @param token             a token to check
 * @param project           the namespace to check against
 * @param verb              the verb (e.g. view)
 * @param resource          the resource (e.g. pods/log)
 * @param resourceAPIGroup  the group of the resource being checked
 * @param scopes            the scopes:
 *                            null  - use token scopes
 *                            empty - remove scopes
 *                            list  - an array of scopes
 *                            
 * @return  true if the SAR is satisfied
 */
public boolean localSubjectAccessReview(final String token, 
        final String project, final String verb, final String resource, final String resourceAPIGroup, final String [] scopes) {
    try (DefaultOpenShiftClient client = factory.buildClient(token)) {
        XContentBuilder payload = XContentFactory.jsonBuilder()
            .startObject()
                .field("kind","SubjectAccessReview")
                .field("apiVersion","authorization.openshift.io/v1")
                .field("verb", verb)
                .array("scopes", scopes);
        if(resource.startsWith("/")) {
            payload.field("isNonResourceURL", Boolean.TRUE)
                .field("path", resource);
        } else {
            payload.field("resourceAPIGroup", resourceAPIGroup)
                .field("resource", resource)
                .field("namespace", project);
        }
        payload.endObject();
        Request request = new Request.Builder()
                .url(String.format("%sapis/authorization.openshift.io/v1/subjectaccessreviews", client.getMasterUrl(), project))
                .header("Authorization", "Bearer " + token)
                .header(CONTENT_TYPE, APPLICATION_JSON)
                .header(ACCEPT, APPLICATION_JSON)
                .post(RequestBody.create(MediaType.parse(APPLICATION_JSON), payload.string()))
                .build();
        log(request);
        Response response = client.getHttpClient().newCall(request).execute();
        final String body = IOUtils.toString(response.body().byteStream());
        log(response, body);
        if(response.code() != RestStatus.CREATED.getStatus()) {
            throw new ElasticsearchSecurityException("Unable to determine user's operations role", RestStatus.fromCode(response.code()));
        }
        return JsonPath.read(body, "$.allowed");
    } catch (IOException e) {
        LOGGER.error("Error determining user's role", e);
    }
    return false;
}
 
Example #16
Source File: KerberosAuthenticationFailureHandler.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException authenticationRequired(final String action) {
    final ElasticsearchSecurityException se = super.authenticationRequired(action);
    se.addHeader(KrbConstants.WWW_AUTHENTICATE, KrbConstants.NEGOTIATE);

    if (logger.isDebugEnabled()) {
        logger.debug("authentication required for action {}", action);
    }
    return se;
}
 
Example #17
Source File: LdapBackendTestNewStyleConfig2.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Test(expected = ElasticsearchSecurityException.class)
public void testChainedLdapAuthenticationDuplicate() throws Exception {

    final Settings settings = createBaseSettings()
            .putList(ConfigConstants.LDAP_HOSTS, "localhost:" + ldapPort)
            .put(ConfigConstants.LDAP_SEARCH_ALL_BASES, true).put("users.u1.search", "(uid={0})")
            .put("users.u1.base", "ou=people,o=TEST").put("users.u2.search", "(uid={0})")
            .put("users.u2.base", "ou=people2,o=TEST").build();

    new LDAPAuthenticationBackend2(settings, null)
            .authenticate(new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)));

    // Fails with ElasticsearchSecurityException because two possible instances are
    // found
}
 
Example #18
Source File: LdapBackendTestOldStyleConfig2.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Test(expected = ElasticsearchSecurityException.class)
public void testLdapAuthenticationFakeLogin() throws Exception {

    final Settings settings = createBaseSettings()
            .putList(ConfigConstants.LDAP_HOSTS, "localhost:" + ldapPort)
            .put(ConfigConstants.LDAP_AUTHC_USERSEARCH, "(uid={0})")
            .put(ConfigConstants.LDAP_FAKE_LOGIN_ENABLED, true).build();

    new LDAPAuthenticationBackend2(settings, null)
            .authenticate(new AuthCredentials("unknown", "unknown".getBytes(StandardCharsets.UTF_8)));
}
 
Example #19
Source File: ModelsAction.java    From zentity with Apache License 2.0 5 votes vote down vote up
/**
 * Delete one entity model by its type.
 *
 * @param entityType The entity type.
 * @param client     The client that will communicate with Elasticsearch.
 * @return The response from Elasticsearch.
 * @throws ForbiddenException
 */
private static DeleteResponse deleteEntityModel(String entityType, NodeClient client) throws ForbiddenException {
    DeleteRequestBuilder request = client.prepareDelete(INDEX_NAME, "doc", entityType);
    request.setRefreshPolicy("wait_for");
    try {
        return request.get();
    } catch (IndexNotFoundException e) {
        try {
            SetupAction.createIndex(client);
        } catch (ElasticsearchSecurityException se) {
            throw new ForbiddenException("The .zentity-models index does not exist and you do not have the 'create_index' privilege. An authorized user must create the index by submitting: POST _zentity/_setup");
        }
        return request.get();
    }
}
 
Example #20
Source File: LdapBackendTest.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Test(expected=ElasticsearchSecurityException.class)
public void testLdapAuthenticationWrongBindDn() throws Exception {


    final Settings settings = Settings.builder()
            .putList(ConfigConstants.LDAP_HOSTS,  "localhost:" + ldapPort)
            .put(ConfigConstants.LDAP_AUTHC_USERSEARCH, "(uid={0})")
            .put(ConfigConstants.LDAP_AUTHC_USERBASE, "ou=people,o=TEST")
            .put(ConfigConstants.LDAP_BIND_DN, "cn=Captain Spock,ou=people,o=TEST")
            .put(ConfigConstants.LDAP_PASSWORD, "wrong")
            .build();

    new LDAPAuthenticationBackend(settings, null).authenticate(new AuthCredentials("jacksonm", "secret"
            .getBytes(StandardCharsets.UTF_8)));
}
 
Example #21
Source File: OpenShiftTokenAuthentication.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public User authenticate(AuthCredentials credentials) throws ElasticsearchSecurityException {
    if (PluginServiceFactory.isReady() && PluginServiceFactory.getThreadContext() != null) {
        OpenshiftRequestContext context = PluginServiceFactory.getThreadContext().getTransient(ConfigurationSettings.OPENSHIFT_REQUEST_CONTEXT);
        if(context == null || context == OpenshiftRequestContext.EMPTY) {
            return null;
        }
        User user = new User(context.getUser(), context.getBackendRoles());
        addGeneralRoles(user, credentials, context);
        return user;
    }
    return null;
}
 
Example #22
Source File: FileAuthenticationBackend.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public AuthCredentials extractCredentials(RestRequest request, ThreadContext context) throws ElasticsearchSecurityException {
    final String authorizationHeader = request.header("Authorization");
    if (authorizationHeader != null) {
        if (authorizationHeader.trim().toLowerCase().startsWith("basic ")) {
            final String decoded = new String(DatatypeConverter.parseBase64Binary(authorizationHeader.split(" ")[1]),
                    StandardCharsets.UTF_8);

            //username:password
            //Assume password is all chars from the last : to the end
            //this is the only way to send service accounts
           
            final int delimiter = decoded.lastIndexOf(':');

            String username = null;
            String password = null;

            if (delimiter > 0) {
                username = decoded.substring(0, delimiter);
                
                if(decoded.length() - 1 != delimiter) {
                    password = decoded.substring(delimiter + 1).trim();
                }
            }
            if (username != null && StringUtils.isNotEmpty(password)) {
                return new AuthCredentials(username, password.getBytes(StandardCharsets.UTF_8)).markComplete();
            }
        }
    }
    return null;
}
 
Example #23
Source File: OpenShiftTokenAuthenticationTest.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test(expected = ElasticsearchSecurityException.class)
public void testExtractCredentialsThrowsSecurityException() throws Exception {
    when(contextFactory.create(any(RestRequest.class))).thenThrow(ElasticsearchSecurityException.class);
    PluginServiceFactory.setContextFactory(contextFactory);
    
    backend.extractCredentials(request, null);
}
 
Example #24
Source File: CustomAuthenticationFailureHandler.java    From shield-custom-realm-example with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException authenticationRequired(String action, ThreadContext context) {
    ElasticsearchSecurityException se = super.authenticationRequired(action, context);
    // set a custom header
    se.addHeader("WWW-Authenticate", "custom-challenge");
    return se;
}
 
Example #25
Source File: CustomAuthenticationFailureHandler.java    From shield-custom-realm-example with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException exceptionProcessingRequest(TransportMessage message, String action, Exception e,
                                                                 ThreadContext context) {
    ElasticsearchSecurityException se = super.exceptionProcessingRequest(message, action, e, context);
    // set a custom header
    se.addHeader("WWW-Authenticate", "custom-challenge");
    return se;
}
 
Example #26
Source File: CustomAuthenticationFailureHandler.java    From shield-custom-realm-example with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException failedAuthentication(RestRequest request, AuthenticationToken token, ThreadContext context) {
    ElasticsearchSecurityException e = super.failedAuthentication(request, token, context);
    // set a custom header
    e.addHeader("WWW-Authenticate", "custom-challenge");
    return e;
}
 
Example #27
Source File: CustomAuthenticationFailureHandler.java    From shield-custom-realm-example with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException failedAuthentication(TransportMessage message, AuthenticationToken token, String action,
                                                           ThreadContext context) {
    ElasticsearchSecurityException e = super.failedAuthentication(message, token, action, context);
    // set a custom header
    e.addHeader("WWW-Authenticate", "custom-challenge");
    return e;
}
 
Example #28
Source File: CustomAuthenticationFailureHandler.java    From shield-custom-realm-example with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException missingToken(RestRequest request, ThreadContext context) {
    ElasticsearchSecurityException e = super.missingToken(request, context);
    // set a custom header
    e.addHeader("WWW-Authenticate", "custom-challenge");
    return e;
}
 
Example #29
Source File: CustomAuthenticationFailureHandler.java    From shield-custom-realm-example with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException missingToken(TransportMessage message, String action, ThreadContext context) {
    ElasticsearchSecurityException e = super.missingToken(message, action, context);
    // set a custom header
    e.addHeader("WWW-Authenticate", "custom-challenge");
    return e;
}
 
Example #30
Source File: CustomAuthenticationFailureHandler.java    From shield-custom-realm-example with Apache License 2.0 5 votes vote down vote up
@Override
public ElasticsearchSecurityException exceptionProcessingRequest(RestRequest request, Exception e, ThreadContext context) {
    ElasticsearchSecurityException se = super.exceptionProcessingRequest(request, e, context);
    // set a custom header
    se.addHeader("WWW-Authenticate", "custom-challenge");
    return se;
}