Search in sources :

Example 41 with Subject

use of org.apache.shiro.subject.Subject in project ddf by codice.

the class FilterPlugin method processPreUpdate.

@Override
public UpdateRequest processPreUpdate(UpdateRequest input, Map<String, Metacard> metacards) throws StopProcessingException {
    KeyValueCollectionPermission securityPermission = new KeyValueCollectionPermission(CollectionPermission.UPDATE_ACTION);
    List<Map.Entry<Serializable, Metacard>> updates = input.getUpdates();
    Subject subject = getSubject(input);
    Subject systemSubject = getSystemSubject();
    List<String> unknownIds = new ArrayList<>();
    List<String> userNotPermittedIds = new ArrayList<>();
    List<String> systemNotPermittedIds = new ArrayList<>();
    for (Map.Entry<Serializable, Metacard> entry : updates) {
        Metacard newMetacard = entry.getValue();
        Attribute attr = newMetacard.getAttribute(Metacard.SECURITY);
        String id = null;
        if (entry.getKey() != null && !entry.getKey().equals("null")) {
            id = (String) entry.getKey();
        } else if (newMetacard.getId() != null && !newMetacard.getId().equals("null")) {
            id = newMetacard.getId();
        }
        Metacard oldMetacard = metacards.get(id);
        if (oldMetacard == null) {
            unknownIds.add(id);
        } else {
            Attribute oldAttr = oldMetacard.getAttribute(Metacard.SECURITY);
            if (!checkPermissions(attr, securityPermission, subject, CollectionPermission.UPDATE_ACTION) || !checkPermissions(oldAttr, securityPermission, subject, CollectionPermission.UPDATE_ACTION)) {
                userNotPermittedIds.add(newMetacard.getId());
            }
            if (!checkPermissions(attr, securityPermission, systemSubject, CollectionPermission.UPDATE_ACTION)) {
                systemNotPermittedIds.add(newMetacard.getId());
            }
        }
    }
    if (!unknownIds.isEmpty() || !userNotPermittedIds.isEmpty()) {
        throw new StopProcessingException("Update operation not permitted with bad data. Unknown metacards: [ " + listToString(unknownIds) + " ]. Not Permitted metacards: [ " + listToString(userNotPermittedIds) + " ]");
    }
    if (!systemNotPermittedIds.isEmpty()) {
        throw new StopProcessingException("Update operation not permitted for this system metacards: [ " + listToString(systemNotPermittedIds) + " ]");
    }
    return input;
}
Also used : KeyValueCollectionPermission(ddf.security.permission.KeyValueCollectionPermission) Serializable(java.io.Serializable) Attribute(ddf.catalog.data.Attribute) ArrayList(java.util.ArrayList) StopProcessingException(ddf.catalog.plugin.StopProcessingException) Subject(org.apache.shiro.subject.Subject) Metacard(ddf.catalog.data.Metacard) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 42 with Subject

use of org.apache.shiro.subject.Subject in project ddf by codice.

the class SecurityLoggerOutInterceptor method handleMessage.

@Override
public void handleMessage(Message message) throws Fault {
    if (MessageUtils.isRequestor(message)) {
        Subject subject = ThreadContext.getSubject();
        if (subject != null) {
            String username = SubjectUtils.getName(subject);
            SecurityLogger.audit("{} is making an outbound request.", username);
        } else {
            SecurityLogger.audit("No subject associated with outbound request.");
        }
    }
}
Also used : Subject(org.apache.shiro.subject.Subject)

Example 43 with Subject

use of org.apache.shiro.subject.Subject in project ddf by codice.

the class SubjectUtils method getAttribute.

/**
     * Get any attribute from a subject by key.
     *
     * @param subject
     * @param key
     * @return attribute values or an empty list if not found.
     */
public static List<String> getAttribute(@Nullable Subject subject, String key) {
    Validate.notNull(key);
    if (subject == null) {
        LOGGER.debug("Incoming subject was null, cannot look up {}.", key);
        return Collections.emptyList();
    }
    PrincipalCollection principals = subject.getPrincipals();
    if (principals == null) {
        LOGGER.debug("No principals located in the incoming subject, cannot look up {}.", key);
        return Collections.emptyList();
    }
    SecurityAssertion assertion = principals.oneByType(SecurityAssertion.class);
    if (assertion == null) {
        LOGGER.debug("Could not find Security Assertion, cannot look up {}.", key);
        return Collections.emptyList();
    }
    return assertion.getAttributeStatements().stream().flatMap(as -> as.getAttributes().stream()).filter(a -> a.getName().equals(key)).flatMap(a -> a.getAttributeValues().stream()).filter(o -> o instanceof XSString).map(o -> (XSString) o).map(XSString::getValue).collect(Collectors.toList());
}
Also used : Arrays(java.util.Arrays) X500Principal(javax.security.auth.x500.X500Principal) SortedSet(java.util.SortedSet) LoggerFactory(org.slf4j.LoggerFactory) BCStyle(org.bouncycastle.asn1.x500.style.BCStyle) TreeSet(java.util.TreeSet) AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue) X500Name(org.bouncycastle.asn1.x500.X500Name) Attribute(org.opensaml.saml.saml2.core.Attribute) Subject(org.apache.shiro.subject.Subject) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) StringTokenizer(java.util.StringTokenizer) Map(java.util.Map) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) XSString(org.opensaml.core.xml.schema.XSString) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) Nullable(javax.annotation.Nullable) SecurityAssertion(ddf.security.assertion.SecurityAssertion) Logger(org.slf4j.Logger) RDN(org.bouncycastle.asn1.x500.RDN) Predicate(java.util.function.Predicate) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) GuestPrincipal(ddf.security.principal.GuestPrincipal) List(java.util.List) Principal(java.security.Principal) Collections(java.util.Collections) Validate(org.apache.commons.lang.Validate) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) XSString(org.opensaml.core.xml.schema.XSString) SecurityAssertion(ddf.security.assertion.SecurityAssertion)

Example 44 with Subject

use of org.apache.shiro.subject.Subject in project ddf by codice.

the class LocalLogoutServlet method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("text/html");
    URIBuilder redirectUrlBuilder = null;
    List<NameValuePair> params = new ArrayList<>();
    try {
        redirectUrlBuilder = new URIBuilder("/logout/logout-response.html");
        HttpSession session = request.getSession();
        if (session != null) {
            SecurityTokenHolder savedToken = (SecurityTokenHolder) session.getAttribute(SecurityConstants.SAML_ASSERTION);
            if (savedToken != null) {
                Subject subject = ThreadContext.getSubject();
                boolean hasSecurityAuditRole = Arrays.stream(System.getProperty("security.audit.roles").split(",")).anyMatch(subject::hasRole);
                if (hasSecurityAuditRole) {
                    SecurityLogger.audit("Subject with admin privileges has logged out", subject);
                }
                savedToken.removeAll();
            }
            session.invalidate();
            deleteJSessionId(response);
        }
        //Check for pki
        if (request.getAttribute("javax.servlet.request.X509Certificate") != null && ((X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate")).length > 0) {
            params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
        }
        //Check for basic
        Enumeration authHeaders = request.getHeaders(javax.ws.rs.core.HttpHeaders.AUTHORIZATION);
        while (authHeaders.hasMoreElements()) {
            if (((String) authHeaders.nextElement()).contains("Basic")) {
                params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
                break;
            }
        }
        redirectUrlBuilder.addParameters(params);
        response.sendRedirect(redirectUrlBuilder.build().toString());
    } catch (URISyntaxException e) {
        LOGGER.debug("Invalid URI", e);
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) Enumeration(java.util.Enumeration) HttpSession(javax.servlet.http.HttpSession) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) Subject(org.apache.shiro.subject.Subject) URIBuilder(org.apache.http.client.utils.URIBuilder) SecurityTokenHolder(ddf.security.common.SecurityTokenHolder) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 45 with Subject

use of org.apache.shiro.subject.Subject in project ddf by codice.

the class LogoutService method getActionProviders.

@GET
@Path("/actions")
public Response getActionProviders(@Context HttpServletRequest request) throws SecurityServiceException {
    HttpSession session = httpSessionFactory.getOrCreateSession(request);
    Map<String, SecurityToken> realmTokenMap = ((SecurityTokenHolder) session.getAttribute(SecurityConstants.SAML_ASSERTION)).getRealmTokenMap();
    Map<String, Subject> realmSubjectMap = new HashMap<>();
    for (Map.Entry<String, SecurityToken> entry : realmTokenMap.entrySet()) {
        realmSubjectMap.put(entry.getKey(), securityManager.getSubject(entry.getValue()));
    }
    List<Map<String, String>> realmToPropMaps = new ArrayList<>();
    for (ActionProvider actionProvider : logoutActionProviders) {
        Action action = actionProvider.getAction(realmSubjectMap);
        if (action != null) {
            String realm = StringUtils.substringAfterLast(action.getId(), ".");
            //if the user is logged in and isn't a guest, add them
            if (realmTokenMap.get(realm) != null) {
                Map<String, String> actionProperties = new HashMap<>();
                String displayName = SubjectUtils.getName(realmSubjectMap.get(realm), "", true);
                if (displayName != null && !displayName.equals(SubjectUtils.GUEST_DISPLAY_NAME)) {
                    actionProperties.put("title", action.getTitle());
                    actionProperties.put("realm", realm);
                    actionProperties.put("auth", displayName);
                    actionProperties.put("description", action.getDescription());
                    actionProperties.put("url", action.getUrl().toString());
                    realmToPropMaps.add(actionProperties);
                }
            }
        }
    }
    return Response.ok(new ByteArrayInputStream(toJson(realmToPropMaps).getBytes(StandardCharsets.UTF_8))).build();
}
Also used : ActionProvider(ddf.action.ActionProvider) Action(ddf.action.Action) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) ArrayList(java.util.ArrayList) Subject(org.apache.shiro.subject.Subject) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityTokenHolder(ddf.security.common.SecurityTokenHolder) ByteArrayInputStream(java.io.ByteArrayInputStream) HashMap(java.util.HashMap) Map(java.util.Map) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Aggregations

Subject (org.apache.shiro.subject.Subject)78 UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)11 Test (org.junit.Test)9 IOException (java.io.IOException)8 Map (java.util.Map)8 Path (javax.ws.rs.Path)8 StopProcessingException (ddf.catalog.plugin.StopProcessingException)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 AccountVO (com.netsteadfast.greenstep.vo.AccountVO)5 Attribute (ddf.catalog.data.Attribute)5 KeyValueCollectionPermission (ddf.security.permission.KeyValueCollectionPermission)5 GET (javax.ws.rs.GET)5 AuthenticationException (org.apache.shiro.authc.AuthenticationException)5 ServiceException (com.netsteadfast.greenstep.base.exception.ServiceException)4 Metacard (ddf.catalog.data.Metacard)4 ApiOperation (io.swagger.annotations.ApiOperation)4 POST (javax.ws.rs.POST)4 PersistenceException (org.codice.ddf.persistence.PersistenceException)4