Search in sources :

Example 21 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project ddf by codice.

the class LoginFilter method handleAuthenticationToken.

private Subject handleAuthenticationToken(HttpServletRequest httpRequest, SAMLAuthenticationToken token) throws ServletException {
    Subject subject;
    try {
        LOGGER.debug("Validating received SAML assertion.");
        boolean wasReference = false;
        boolean firstLogin = true;
        if (token.isReference()) {
            wasReference = true;
            LOGGER.trace("Converting SAML reference to assertion");
            Object sessionToken = httpRequest.getSession(false).getAttribute(SecurityConstants.SAML_ASSERTION);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Http Session assertion - class: {}  loader: {}", sessionToken.getClass().getName(), sessionToken.getClass().getClassLoader());
                LOGGER.trace("SecurityToken class: {}  loader: {}", SecurityToken.class.getName(), SecurityToken.class.getClassLoader());
            }
            SecurityToken savedToken = null;
            try {
                savedToken = ((SecurityTokenHolder) sessionToken).getSecurityToken(token.getRealm());
            } catch (ClassCastException e) {
                httpRequest.getSession(false).invalidate();
            }
            if (savedToken != null) {
                firstLogin = false;
                token.replaceReferenece(savedToken);
            }
            if (token.isReference()) {
                String msg = "Missing or invalid SAML assertion for provided reference.";
                LOGGER.debug(msg);
                throw new InvalidSAMLReceivedException(msg);
            }
        }
        SAMLAuthenticationToken newToken = renewSecurityToken(httpRequest.getSession(false), token);
        SecurityToken securityToken;
        if (newToken != null) {
            firstLogin = false;
            securityToken = (SecurityToken) newToken.getCredentials();
        } else {
            securityToken = (SecurityToken) token.getCredentials();
        }
        if (!wasReference) {
            // wrap the token
            SamlAssertionWrapper assertion = new SamlAssertionWrapper(securityToken.getToken());
            // get the crypto junk
            Crypto crypto = getSignatureCrypto();
            Response samlResponse = createSamlResponse(httpRequest.getRequestURI(), assertion.getIssuerString(), createStatus(SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null));
            BUILDER.get().reset();
            Document doc = BUILDER.get().newDocument();
            Element policyElement = OpenSAMLUtil.toDom(samlResponse, doc);
            doc.appendChild(policyElement);
            Credential credential = new Credential();
            credential.setSamlAssertion(assertion);
            RequestData requestData = new RequestData();
            requestData.setSigVerCrypto(crypto);
            WSSConfig wssConfig = WSSConfig.getNewInstance();
            requestData.setWssConfig(wssConfig);
            X509Certificate[] x509Certs = (X509Certificate[]) httpRequest.getAttribute("javax.servlet.request.X509Certificate");
            requestData.setTlsCerts(x509Certs);
            validateHolderOfKeyConfirmation(assertion, x509Certs);
            if (assertion.isSigned()) {
                // Verify the signature
                WSSSAMLKeyInfoProcessor wsssamlKeyInfoProcessor = new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument()));
                assertion.verifySignature(wsssamlKeyInfoProcessor, crypto);
                assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument())), requestData.getSigVerCrypto(), requestData.getCallbackHandler());
            }
            // Validate the Assertion & verify trust in the signature
            assertionValidator.validate(credential, requestData);
        }
        // if it is all good, then we'll create our subject
        subject = securityManager.getSubject(securityToken);
        if (firstLogin) {
            boolean hasSecurityAuditRole = Arrays.stream(System.getProperty("security.audit.roles").split(",")).filter(subject::hasRole).findFirst().isPresent();
            if (hasSecurityAuditRole) {
                SecurityLogger.audit("Subject has logged in with admin privileges", subject);
            }
        }
        if (!wasReference && firstLogin) {
            addSamlToSession(httpRequest, token.getRealm(), securityToken);
        }
    } catch (SecurityServiceException e) {
        LOGGER.debug("Unable to get subject from SAML request.", e);
        throw new ServletException(e);
    } catch (WSSecurityException e) {
        LOGGER.debug("Unable to read/validate security token from request.", e);
        throw new ServletException(e);
    }
    return subject;
}
Also used : WSDocInfo(org.apache.wss4j.dom.WSDocInfo) Credential(org.apache.wss4j.dom.validate.Credential) SecurityServiceException(ddf.security.service.SecurityServiceException) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException) Document(org.w3c.dom.Document) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject) X509Certificate(java.security.cert.X509Certificate) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Response(org.opensaml.saml.saml2.core.Response) ServletResponse(javax.servlet.ServletResponse) ServletException(javax.servlet.ServletException) Crypto(org.apache.wss4j.common.crypto.Crypto) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) WSSSAMLKeyInfoProcessor(org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor)

Example 22 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project ddf by codice.

the class LoginFilter method renewSecurityToken.

private SAMLAuthenticationToken renewSecurityToken(HttpSession session, SAMLAuthenticationToken savedToken) throws ServletException, WSSecurityException {
    if (session != null) {
        SecurityAssertion savedAssertion = new SecurityAssertionImpl(((SecurityToken) savedToken.getCredentials()));
        if (savedAssertion.getIssuer() != null && !savedAssertion.getIssuer().equals(SystemBaseUrl.getHost())) {
            return null;
        }
        if (savedAssertion.getNotOnOrAfter() == null) {
            return null;
        }
        long afterMil = savedAssertion.getNotOnOrAfter().getTime();
        long timeoutMillis = (afterMil - System.currentTimeMillis());
        if (timeoutMillis <= 0) {
            throw new InvalidSAMLReceivedException("SAML assertion has expired.");
        }
        if (timeoutMillis <= 60000) {
            // within 60 seconds
            try {
                LOGGER.debug("Attempting to refresh user's SAML assertion.");
                Subject subject = securityManager.getSubject(savedToken);
                LOGGER.debug("Refresh of user assertion successful");
                for (Object principal : subject.getPrincipals()) {
                    if (principal instanceof SecurityAssertion) {
                        SecurityToken token = ((SecurityAssertion) principal).getSecurityToken();
                        SAMLAuthenticationToken samlAuthenticationToken = new SAMLAuthenticationToken((java.security.Principal) savedToken.getPrincipal(), token, savedToken.getRealm());
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("Setting session token - class: {}  classloader: {}", token.getClass().getName(), token.getClass().getClassLoader());
                        }
                        ((SecurityTokenHolder) session.getAttribute(SecurityConstants.SAML_ASSERTION)).addSecurityToken(savedToken.getRealm(), token);
                        LOGGER.debug("Saved new user assertion to session.");
                        return samlAuthenticationToken;
                    }
                }
            } catch (SecurityServiceException e) {
                LOGGER.debug("Unable to refresh user's SAML assertion. User will log out prematurely.", e);
                session.invalidate();
            } catch (Exception e) {
                LOGGER.info("Unhandled exception occurred.", e);
                session.invalidate();
            }
        }
    }
    return null;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityTokenHolder(ddf.security.common.SecurityTokenHolder) SecurityServiceException(ddf.security.service.SecurityServiceException) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException) SecurityAssertion(ddf.security.assertion.SecurityAssertion) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject) ServletException(javax.servlet.ServletException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SecurityServiceException(ddf.security.service.SecurityServiceException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) InvalidSAMLReceivedException(org.codice.ddf.security.handler.api.InvalidSAMLReceivedException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) NoSuchProviderException(java.security.NoSuchProviderException) SecurityAssertionImpl(ddf.security.assertion.impl.SecurityAssertionImpl)

Example 23 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project ddf by codice.

the class ZipValidator method validateZipFile.

/**
     * Validates a Zip file with the specified path.  If the Zip file does not have a manifest,
     * is not signed, or does not match a certificate in the DDF KeyStore, the validation fails.
     *
     * @param filePath - the path to the zip file to validate
     * @return true when the zip file is valid (signed by a trusted entity).
     */
public boolean validateZipFile(String filePath) throws ZipValidationException {
    try (JarFile jarFile = new JarFile(filePath)) {
        Manifest man = jarFile.getManifest();
        if (man == null) {
            throw new ZipValidationException("Zip validation failed, missing manifest file.");
        }
        Vector entriesVec = new Vector<>();
        byte[] buffer = new byte[ZipDecompression.BUFFER_SIZE];
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry je = (JarEntry) entries.nextElement();
            if (je.isDirectory()) {
                continue;
            }
            entriesVec.addElement(je);
            try (InputStream is = jarFile.getInputStream(je)) {
                while (is.read(buffer, 0, buffer.length) != -1) {
                // Read JarFile
                }
                is.close();
            } catch (IOException e) {
                throw new ZipValidationException(String.format("Zip validation failed, unable to get input stream for entry %s", je.getName()));
            }
        }
        Enumeration e = entriesVec.elements();
        while (e.hasMoreElements()) {
            JarEntry je = (JarEntry) e.nextElement();
            Certificate[] certs = je.getCertificates();
            if ((certs == null) || (certs.length == 0)) {
                if (!je.getName().startsWith("META-INF")) {
                    throw new ZipValidationException(String.format("Zip validation failed, unable to get certificates for entry %s", je.getName()));
                }
            } else {
                int startIndex = 0;
                X509Certificate[] certChain;
                while ((certChain = getAChain(certs, startIndex)) != null) {
                    try {
                        merlin.verifyTrust(certChain[0].getPublicKey());
                    } catch (WSSecurityException e1) {
                        throw new ZipValidationException(String.format("Zip validation failed, untrusted certificates for entry %s", je.getName()));
                    }
                    startIndex += certChain.length;
                }
            }
        }
    } catch (IOException e) {
        throw new ZipValidationException(String.format("Zip validation failed for file : %s", filePath));
    }
    return true;
}
Also used : Enumeration(java.util.Enumeration) InputStream(java.io.InputStream) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry) X509Certificate(java.security.cert.X509Certificate) Vector(java.util.Vector) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 24 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project ddf by codice.

the class WebSSOTokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     */
@Override
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.debug("Validating SSO Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    LOGGER.debug("Setting validate state to invalid before check.");
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isBinarySecurityToken()) {
        LOGGER.debug("Validate target is not a binary security token, returning invalid response.");
        return response;
    }
    LOGGER.debug("Getting binary security token from validate target");
    BinarySecurityTokenType binarySecurityToken = (BinarySecurityTokenType) validateTarget.getToken();
    //
    // Decode the token
    //
    LOGGER.debug("Decoding binary security token.");
    String base64Token = binarySecurityToken.getValue();
    String ticket = null;
    String service = null;
    try {
        byte[] token = Base64.getDecoder().decode(base64Token);
        if (token == null || token.length == 0) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null.");
        }
        String decodedToken = new String(token, Charset.forName("UTF-8"));
        if (StringUtils.isNotBlank(decodedToken)) {
            LOGGER.debug("Binary security token successfully decoded: {}", decodedToken);
            // Token is in the format ticket|service
            String[] parts = StringUtils.split(decodedToken, CAS_BST_SEP);
            if (parts.length == 2) {
                ticket = parts[0];
                service = parts[1];
            } else {
                throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Was not able to parse out BST propertly. Should be in ticket|service format.");
            }
        } else {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null.");
        }
    } catch (WSSecurityException wsse) {
        String msg = "Unable to decode BST into ticket and service for validation to CAS.";
        LOGGER.info(msg, wsse);
        return response;
    }
    //
    try {
        LOGGER.debug("Validating ticket [{}] for service [{}].", ticket, service);
        // validate either returns an assertion or throws an exception
        Assertion assertion = validate(ticket, service);
        AttributePrincipal principal = assertion.getPrincipal();
        LOGGER.debug("User name retrieved from CAS: {}", principal.getName());
        response.setPrincipal(principal);
        LOGGER.debug("CAS ticket successfully validated, setting state to valid.");
        validateTarget.setState(STATE.VALID);
    } catch (TicketValidationException e) {
        LOGGER.debug("Unable to validate CAS token.", e);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Assertion(org.jasig.cas.client.validation.Assertion) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) RequestData(org.apache.wss4j.dom.handler.RequestData) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal) TicketValidationException(org.jasig.cas.client.validation.TicketValidationException)

Example 25 with WSSecurityException

use of org.apache.wss4j.common.ext.WSSecurityException in project ddf by codice.

the class MetadataConfigurationParser method readEntityDescriptor.

private EntityDescriptor readEntityDescriptor(Reader reader) {
    Document entityDoc;
    try {
        entityDoc = StaxUtils.read(reader);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Unable to read SAMLRequest as XML.");
    }
    XMLObject entityXmlObj;
    try {
        entityXmlObj = OpenSAMLUtil.fromDom(entityDoc.getDocumentElement());
    } catch (WSSecurityException ex) {
        throw new IllegalArgumentException("Unable to convert EntityDescriptor document to XMLObject.");
    }
    return (EntityDescriptor) entityXmlObj;
}
Also used : EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) XMLObject(org.opensaml.core.xml.XMLObject) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) NoSuchFileException(java.nio.file.NoSuchFileException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException)

Aggregations

WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)44 IOException (java.io.IOException)16 X509Certificate (java.security.cert.X509Certificate)13 RequestData (org.apache.wss4j.dom.handler.RequestData)13 Credential (org.apache.wss4j.dom.validate.Credential)12 Document (org.w3c.dom.Document)12 BinarySecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType)11 Crypto (org.apache.wss4j.common.crypto.Crypto)11 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)10 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)10 TokenValidatorResponse (org.apache.cxf.sts.token.validator.TokenValidatorResponse)10 XMLObject (org.opensaml.core.xml.XMLObject)7 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)7 Element (org.w3c.dom.Element)7 X500Principal (javax.security.auth.x500.X500Principal)6 XMLStreamException (javax.xml.stream.XMLStreamException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 CallbackHandler (javax.security.auth.callback.CallbackHandler)5 TokenValidatorParameters (org.apache.cxf.sts.token.validator.TokenValidatorParameters)5 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)5