Search in sources :

Example 56 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class FacetedQueryLogicTest method querySetUp.

@Before
public void querySetUp() throws IOException {
    log.debug("---------  querySetUp  ---------");
    // Super call to pick up authSet initialization
    super.querySetUp();
    FacetedQueryLogic facetLogic = new FacetedQueryLogic();
    facetLogic.setFacetedSearchType(FacetedSearchType.FIELD_VALUE_FACETS);
    facetLogic.setFacetTableName(QueryTestTableHelper.FACET_TABLE_NAME);
    facetLogic.setFacetMetadataTableName(QueryTestTableHelper.FACET_METADATA_TABLE_NAME);
    facetLogic.setFacetHashTableName(QueryTestTableHelper.FACET_HASH_TABLE_NAME);
    facetLogic.setMaximumFacetGrouping(200);
    facetLogic.setMinimumFacet(1);
    this.logic = facetLogic;
    QueryTestTableHelper.configureLogicToScanTables(this.logic);
    this.logic.setFullTableScanEnabled(false);
    this.logic.setIncludeDataTypeAsField(true);
    this.logic.setIncludeGroupingContext(true);
    this.logic.setDateIndexHelperFactory(new DateIndexHelperFactory());
    this.logic.setMarkingFunctions(new MarkingFunctions.Default());
    this.logic.setMetadataHelperFactory(new MetadataHelperFactory());
    this.logic.setResponseObjectFactory(new DefaultResponseObjectFactory());
    // init must set auths
    testInit();
    SubjectIssuerDNPair dn = SubjectIssuerDNPair.of("userDn", "issuerDn");
    DatawaveUser user = new DatawaveUser(dn, DatawaveUser.UserType.USER, Sets.newHashSet(this.auths.toString().split(",")), null, null, -1L);
    this.principal = new DatawavePrincipal(Collections.singleton(user));
    this.testHarness = new QueryLogicTestHarness(this);
}
Also used : DefaultResponseObjectFactory(datawave.webservice.query.result.event.DefaultResponseObjectFactory) SubjectIssuerDNPair(datawave.security.authorization.SubjectIssuerDNPair) DatawaveUser(datawave.security.authorization.DatawaveUser) QueryLogicTestHarness(datawave.query.testframework.QueryLogicTestHarness) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) DateIndexHelperFactory(datawave.query.util.DateIndexHelperFactory) MarkingFunctions(datawave.marking.MarkingFunctions) MetadataHelperFactory(datawave.query.util.MetadataHelperFactory) Before(org.junit.Before)

Example 57 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class DatawavePrincipalLoginModule method login.

@Override
public boolean login() throws LoginException {
    try {
        // in the shared state for login, then we're ok. Otherwise, we are going to reject the login.
        if (super.login()) {
            Object username = sharedState.get("javax.security.auth.login.name");
            if (username instanceof Principal) {
                identity = (Principal) username;
                if (trace)
                    log.trace("**** Username is a principle");
            } else {
                if (trace)
                    log.trace("**** Username is not a principle");
                String name = username.toString();
                try {
                    identity = createIdentity(name);
                } catch (Exception e) {
                    log.debug("Failed to create principal", e);
                    throw new LoginException("Failed to create principal: " + e.getMessage());
                }
            }
            Object password = sharedState.get("javax.security.auth.login.password");
            if (password instanceof X509Certificate) {
                if (trace)
                    log.trace("**** Credential is a X509Certificate");
                certificateCredential = (X509Certificate) password;
            } else if (password instanceof X509Certificate[]) {
                if (trace)
                    log.trace("**** Credential is an X509Certificate array");
                certificateCredential = ((X509Certificate[]) password)[0];
            } else if (password instanceof DatawaveCredential) {
                if (trace)
                    log.trace("**** Credential is a DatawaveCredential");
                datawaveCredential = (DatawaveCredential) password;
                certificateCredential = datawaveCredential.getCertificate();
            } else {
                log.warn("Login failed due to unknown password.");
                return false;
            }
        } else {
            DatawaveCredential credential = getDatawaveCredential();
            loginOk = validateCredential(credential);
            if (trace) {
                log.trace("User '" + identity + "' authenticated, loginOk=" + loginOk);
                log.debug("exit: login()");
            }
        }
        if (blacklistUserRole != null && loginOk && identity != null) {
            DatawavePrincipal principal = (DatawavePrincipal) getIdentity();
            if (principal.getProxiedUsers().stream().anyMatch(u -> u.getRoles().contains(blacklistUserRole))) {
                // this is critical as it is what the parent class uses to actually deny login
                loginOk = false;
                String message = "Login denied for " + principal.getUserDN() + " due to membership in the deny-access group " + blacklistUserRole;
                log.debug(message);
                throw new AccountLockedException(message);
            }
        }
    } catch (RuntimeException e) {
        log.warn("Login failed due to exception: " + e.getMessage(), e);
        throw new FailedLoginException(e.getMessage());
    }
    return true;
}
Also used : AccountLockedException(javax.security.auth.login.AccountLockedException) DatawaveCredential(datawave.security.auth.DatawaveCredential) FailedLoginException(javax.security.auth.login.FailedLoginException) LoginException(javax.security.auth.login.LoginException) FailedLoginException(javax.security.auth.login.FailedLoginException) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) Principal(java.security.Principal) SimplePrincipal(org.jboss.security.SimplePrincipal) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) KeyStoreException(java.security.KeyStoreException) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountLockedException(javax.security.auth.login.AccountLockedException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal)

Example 58 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class DatawavePrincipalLoginModule method validateCredential.

@SuppressWarnings("unchecked")
protected boolean validateCredential(DatawaveCredential credential) throws LoginException {
    if (trace)
        log.trace("enter: validateCredential");
    datawaveCredential = credential;
    String alias = credential.getUserName();
    if (trace)
        log.trace("alias = " + alias);
    if (StringUtil.isNullOrEmpty(alias)) {
        identity = unauthenticatedIdentity;
        log.trace("Authenticating as unauthenticatedIdentity=" + identity);
    }
    if (trace)
        log.trace("identity = " + identity);
    if (identity == null) {
        if (credential.getCertificate() != null || (!trustedHeaderLogin && !jwtHeaderLogin)) {
            if (!validateCertificateCredential(credential)) {
                log.debug("Bad credential for alias=" + credential.getUserName());
                throw new FailedLoginException("Supplied Credential did not match existing credential for " + credential.getUserName());
            }
        }
        if (!jwtHeaderLogin || credential.getJwtToken() == null) {
            try {
                identity = new DatawavePrincipal(datawaveUserService.lookup(credential.getEntities()));
            } catch (Exception e) {
                log.debug("Failing login due to datawave user service exception " + e.getMessage(), e);
                throw new FailedLoginException("Unable to authenticate: " + e.getMessage());
            }
        } else {
            try {
                identity = new DatawavePrincipal(jwtTokenHandler.createUsersFromToken(credential.getJwtToken()));
            } catch (Exception e) {
                log.debug("Failing login due to JWT token exception " + e.getMessage(), e);
                throw new FailedLoginException("Unable to authenticate: " + e.getMessage());
            }
        }
    }
    if (getUseFirstPass()) {
        sharedState.put("javax.security.auth.login.name", alias);
        sharedState.put("javax.security.auth.login.password", credential.getCertificate());
    }
    if (trace)
        log.trace("exit: validateCredential");
    return true;
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) KeyStoreException(java.security.KeyStoreException) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountLockedException(javax.security.auth.login.AccountLockedException) IOException(java.io.IOException)

Example 59 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class DatawavePrincipalLoginModule method getRoleSets.

@Override
protected Group[] getRoleSets() throws LoginException {
    Group[] groups;
    try {
        Set<String> roles = new TreeSet<>();
        String targetUser = getUsername();
        DatawavePrincipal principal = (DatawavePrincipal) getIdentity();
        Collection<String> cpRoleSets = principal.getPrimaryUser().getRoles();
        if (cpRoleSets != null) {
            roles.addAll(cpRoleSets);
            // If any entity has none of them, then exclude all of the required roles from the computed final set.
            if (principal.getProxiedUsers().stream().anyMatch(u -> Collections.disjoint(u.getRoles(), requiredRoles))) {
                roles.removeAll(requiredRoles);
            }
        }
        StringBuilder buf = new StringBuilder("[" + roles.size() + "] Groups for " + targetUser + " {");
        if (!roles.isEmpty()) {
            Group group = new SimpleGroup("Roles");
            boolean first = true;
            for (String r : roles) try {
                if (!first) {
                    buf.append(":");
                }
                first = false;
                group.addMember(new SimplePrincipal(r));
                buf.append(" ").append(r).append(" ");
            } catch (Exception e) {
                log.debug("Failed to create principal for: " + r, e);
            }
            groups = new Group[2];
            groups[0] = group;
            groups[1] = new SimpleGroup("CallerPrincipal");
            groups[1].addMember(getIdentity());
        } else {
            groups = new Group[0];
        }
        buf.append("}");
        log.debug(buf.toString());
    } catch (RuntimeException e) {
        groups = new Group[0];
        log.warn("Exception in getRoleSets: " + e.getMessage(), e);
        abort();
    }
    return groups;
}
Also used : SimpleGroup(org.jboss.security.SimpleGroup) Group(java.security.acl.Group) SimpleGroup(org.jboss.security.SimpleGroup) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) KeyStoreException(java.security.KeyStoreException) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountLockedException(javax.security.auth.login.AccountLockedException) IOException(java.io.IOException) TreeSet(java.util.TreeSet) SimplePrincipal(org.jboss.security.SimplePrincipal)

Example 60 with DatawavePrincipal

use of datawave.security.authorization.DatawavePrincipal in project datawave by NationalSecurityAgency.

the class UserOperationsBean method flushCachedCredentials.

/**
 * Clears any cached credentials for the calling user. The end result is that future calls to other methods on this application will require outside contact
 * with the authentication provider.
 *
 * If the credentials are for a single user with no proxy involved, these are the only credentials flushed. Otherwise, if there is a proxy chain, this will
 * flush the DN for the user in the proxy (assumes there is never more than one user in the proxy chain).
 */
@GET
@Path("/flushCachedCredentials")
@Produces({ "application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf", "application/x-protostuff" })
@PermitAll
public GenericResponse<String> flushCachedCredentials() {
    GenericResponse<String> response = new GenericResponse<>();
    Principal callerPrincipal = context.getCallerPrincipal();
    log.info("Flushing credentials for " + callerPrincipal + " from the cache.");
    if (callerPrincipal instanceof DatawavePrincipal) {
        DatawavePrincipal dp = (DatawavePrincipal) callerPrincipal;
        response.setResult(credentialsCache.evict(dp.getUserDN().subjectDN()));
    } else {
        log.warn(callerPrincipal + " is not a DatawavePrincipal.  Cannot flush credentials.");
        response.addMessage("Unable to determine calling user name.  Values were not flushed!");
        throw new DatawaveWebApplicationException(new IllegalStateException("Unable to flush credentials.  Unknown principal type."), response);
    }
    return response;
}
Also used : GenericResponse(datawave.webservice.result.GenericResponse) DatawaveWebApplicationException(datawave.webservice.common.exception.DatawaveWebApplicationException) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) Principal(java.security.Principal) DatawavePrincipal(datawave.security.authorization.DatawavePrincipal) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) PermitAll(javax.annotation.security.PermitAll)

Aggregations

DatawavePrincipal (datawave.security.authorization.DatawavePrincipal)93 DatawaveUser (datawave.security.authorization.DatawaveUser)41 Principal (java.security.Principal)37 HashSet (java.util.HashSet)33 Test (org.junit.Test)29 QueryException (datawave.webservice.query.exception.QueryException)24 Connector (org.apache.accumulo.core.client.Connector)23 IOException (java.io.IOException)19 DatawaveWebApplicationException (datawave.webservice.common.exception.DatawaveWebApplicationException)18 NotFoundQueryException (datawave.webservice.query.exception.NotFoundQueryException)18 Authorizations (org.apache.accumulo.core.security.Authorizations)17 Query (datawave.webservice.query.Query)16 UnauthorizedQueryException (datawave.webservice.query.exception.UnauthorizedQueryException)15 NoResultsException (datawave.webservice.common.exception.NoResultsException)13 ArrayList (java.util.ArrayList)13 Path (javax.ws.rs.Path)13 Produces (javax.ws.rs.Produces)13 SubjectIssuerDNPair (datawave.security.authorization.SubjectIssuerDNPair)12 WebApplicationException (javax.ws.rs.WebApplicationException)12 BadRequestException (datawave.webservice.common.exception.BadRequestException)11