Java Code Examples for org.apache.cxf.helpers.CastUtils#cast()

The following examples show how to use org.apache.cxf.helpers.CastUtils#cast() . 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: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Return true if the Timestamp is signed by one of the token results
 * @param tokenResults A list of WSSecurityEngineResults corresponding to tokens
 * @return true if the Timestamp is signed
 */
private boolean checkTimestampIsSigned(List<WSSecurityEngineResult> tokenResults) {
    for (WSSecurityEngineResult signedResult : signedResults) {
        List<WSDataRef> sl =
            CastUtils.cast((List<?>)signedResult.get(
                WSSecurityEngineResult.TAG_DATA_REF_URIS
            ));
        if (sl != null) {
            for (WSDataRef dataRef : sl) {
                if (timestamp == dataRef.getProtectedElement()
                    && checkSignatureOrEncryptionResult(signedResult, tokenResults)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 2
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Return true if the Timestamp is signed by one of the token results
 * @param tokenResults A list of WSSecurityEngineResults corresponding to tokens
 * @return true if the Timestamp is signed
 */
private boolean checkTimestampIsSigned(List<WSSecurityEngineResult> tokenResults) {
    for (WSSecurityEngineResult signedResult : signedResults) {
        List<WSDataRef> sl =
            CastUtils.cast((List<?>)signedResult.get(
                WSSecurityEngineResult.TAG_DATA_REF_URIS
            ));
        if (sl != null) {
            for (WSDataRef dataRef : sl) {
                if (timestamp == dataRef.getProtectedElement()
                    && checkSignatureOrEncryptionResult(signedResult, tokenResults)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 3
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Return true if the Signature is itself signed by one of the token results
 * @param tokenResults A list of WSSecurityEngineResults corresponding to tokens
 * @return true if the Signature is itself signed
 */
private boolean checkSignatureIsSigned(List<WSSecurityEngineResult> tokenResults) {
    for (WSSecurityEngineResult signedResult : signedResults) {
        List<WSDataRef> sl =
            CastUtils.cast((List<?>)signedResult.get(
                WSSecurityEngineResult.TAG_DATA_REF_URIS
            ));
        if (sl != null && sl.size() == 1) {
            for (WSDataRef dataRef : sl) {
                QName signedQName = dataRef.getName();
                if (WSSecurityEngine.SIGNATURE.equals(signedQName)
                    && checkSignatureOrEncryptionResult(signedResult, tokenResults)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 4
Source File: IssuedTokenInterceptorProvider.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.ISSUED_TOKEN);
        if (ais == null) {
            return;
        }
        if (!isRequestor(message)) {
            List<WSHandlerResult> results = 
                CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));
            if (results != null && results.size() > 0) {
                parseHandlerResults(results.get(0), message, aim);
            }
        } else {
            //client side should be checked on the way out
            for (AssertionInfo ai : ais) {
                ai.setAsserted(true);
            }                    
        }
    }
}
 
Example 5
Source File: AbstractBindingPolicyValidator.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Check to see if encryption was applied before signature.
 * Note that results are stored in the reverse order.
 */
private boolean isEncryptedBeforeSigned(List<WSSecurityEngineResult> results) {
    boolean encrypted = false;
    for (WSSecurityEngineResult result : results) {
        Integer actInt = (Integer)result.get(WSSecurityEngineResult.TAG_ACTION);
        List<WSDataRef> el = 
            CastUtils.cast((List<?>)result.get(WSSecurityEngineResult.TAG_DATA_REF_URIS));
        
        if (actInt.intValue() == WSConstants.ENCR && el != null) {
            encrypted = true;
        }
        // Don't count an endorsing signature
        if (actInt.intValue() == WSConstants.SIGN && el != null
            && !(el.size() == 1 && el.get(0).getName().equals(SIG_QNAME))) {
            if (encrypted) {
                return true;
            }
            return false;
        }
    }
    return false;
}
 
Example 6
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Check that an Element is signed or encrypted by one of the token results
 */
private boolean checkProtectionResult(
    Element elementToProtect,
    boolean content,
    List<WSSecurityEngineResult> protResults,
    List<WSSecurityEngineResult> tokenResults
) {
    for (WSSecurityEngineResult result : protResults) {
        List<WSDataRef> dataRefs = 
            CastUtils.cast((List<?>)result.get(WSSecurityEngineResult.TAG_DATA_REF_URIS));
        if (dataRefs != null) {
            for (WSDataRef dataRef : dataRefs) {
                if (elementToProtect == dataRef.getProtectedElement()
                    && content == dataRef.isContent()
                    && checkSignatureOrEncryptionResult(result, tokenResults)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 7
Source File: AbstractPolicySecurityTest.java    From steady with Apache License 2.0 6 votes vote down vote up
protected void verifyWss4jEncResults(SoapMessage inmsg) {
    //
    // There should be exactly 1 (WSS4J) HandlerResult
    //
    final List<WSHandlerResult> handlerResults = 
        CastUtils.cast((List<?>)inmsg.get(WSHandlerConstants.RECV_RESULTS));
    assertNotNull(handlerResults);
    assertSame(handlerResults.size(), 1);

    List<WSSecurityEngineResult> protectionResults = new Vector<WSSecurityEngineResult>();
    WSSecurityUtil.fetchAllActionResults(handlerResults.get(0).getResults(),
            WSConstants.ENCR, protectionResults);
    assertNotNull(protectionResults);
    
    //
    // This result should contain a reference to the decrypted element
    //
    final Map<String, Object> result = protectionResults
            .get(0);
    final List<WSDataRef> protectedElements = 
        CastUtils.cast((List<?>)result.get(WSSecurityEngineResult.TAG_DATA_REF_URIS));
    assertNotNull(protectedElements);
}
 
Example 8
Source File: AbstractSupportingTokenPolicyValidator.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Check that an Element is signed or encrypted by one of the token results
 */
private boolean checkProtectionResult(
    Element elementToProtect,
    boolean content,
    List<WSSecurityEngineResult> protResults,
    List<WSSecurityEngineResult> tokenResults
) {
    for (WSSecurityEngineResult result : protResults) {
        List<WSDataRef> dataRefs = 
            CastUtils.cast((List<?>)result.get(WSSecurityEngineResult.TAG_DATA_REF_URIS));
        if (dataRefs != null) {
            for (WSDataRef dataRef : dataRefs) {
                if (elementToProtect == dataRef.getProtectedElement()
                    && content == dataRef.isContent()
                    && checkSignatureOrEncryptionResult(result, tokenResults)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 9
Source File: AbstractBindingPolicyValidator.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Check to see if encryption was applied before signature.
 * Note that results are stored in the reverse order.
 */
private boolean isEncryptedBeforeSigned(List<WSSecurityEngineResult> results) {
    boolean encrypted = false;
    for (WSSecurityEngineResult result : results) {
        Integer actInt = (Integer)result.get(WSSecurityEngineResult.TAG_ACTION);
        List<WSDataRef> el = 
            CastUtils.cast((List<?>)result.get(WSSecurityEngineResult.TAG_DATA_REF_URIS));
        
        if (actInt.intValue() == WSConstants.ENCR && el != null) {
            encrypted = true;
        }
        // Don't count an endorsing signature
        if (actInt.intValue() == WSConstants.SIGN && el != null
            && !(el.size() == 1 && el.get(0).getName().equals(SIG_QNAME))) {
            if (encrypted) {
                return true;
            }
            return false;
        }
    }
    return false;
}
 
Example 10
Source File: HttpsTokenInterceptorProvider.java    From steady with Apache License 2.0 5 votes vote down vote up
private static Map<String, List<String>> getSetProtocolHeaders(Message message) {
    Map<String, List<String>> headers =
        CastUtils.cast((Map<?, ?>)message.get(Message.PROTOCOL_HEADERS));        
    if (null == headers) {
        headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
        message.put(Message.PROTOCOL_HEADERS, headers);
    }
    return headers;
}
 
Example 11
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 5 votes vote down vote up
protected void setPolicyInternal(Policy newPolicy) {
    this.policy = newPolicy;
    if (algorithmSuite == null) {
        Iterator<?> i = policy.getAlternatives();
        while (i.hasNext() && algorithmSuite == null) {
            List<PolicyComponent> p = CastUtils.cast((List<?>)i.next());
            for (PolicyComponent p2 : p) {
                if (p2 instanceof Binding) {
                    algorithmSuite = ((Binding)p2).getAlgorithmSuite();
                }
            }
        }
    }
}
 
Example 12
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 5 votes vote down vote up
protected final Map<Object, Crypto> getCryptoCache() {
    EndpointInfo info = message.getExchange().get(Endpoint.class).getEndpointInfo();
    synchronized (info) {
        Map<Object, Crypto> o = 
            CastUtils.cast((Map<?, ?>)message.getContextualProperty(CRYPTO_CACHE));
        if (o == null) {
            o = new ConcurrentHashMap<Object, Crypto>();
            info.setProperty(CRYPTO_CACHE, o);
        }
        return o;
    }
}
 
Example 13
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 5 votes vote down vote up
protected final Map<Object, Crypto> getCryptoCache() {
    EndpointInfo info = message.getExchange().get(Endpoint.class).getEndpointInfo();
    synchronized (info) {
        Map<Object, Crypto> o = 
            CastUtils.cast((Map<?, ?>)message.getContextualProperty(CRYPTO_CACHE));
        if (o == null) {
            o = new ConcurrentHashMap<Object, Crypto>();
            info.setProperty(CRYPTO_CACHE, o);
        }
        return o;
    }
}
 
Example 14
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 5 votes vote down vote up
public String setEncryptionUser(WSSecEncryptedKey encrKeyBuilder, TokenWrapper token,
                              boolean sign, Crypto crypto) {
    String encrUser = (String)message.getContextualProperty(sign 
                                                            ? SecurityConstants.SIGNATURE_USERNAME
                                                            : SecurityConstants.ENCRYPT_USERNAME);
    if (crypto != null && encrUser == null) {
        try {
            encrUser = crypto.getDefaultX509Identifier();
        } catch (WSSecurityException e1) {
            throw new Fault(e1);
        }
    } else if (encrUser == null || "".equals(encrUser)) {
        policyNotAsserted(token, "No " + (sign ? "signature" : "encryption") + " crypto object found.");
    }
    if (encrUser == null || "".equals(encrUser)) {
        policyNotAsserted(token, "A " + (sign ? "signature" : "encryption") + " username needs to be declared.");
    }
    if (WSHandlerConstants.USE_REQ_SIG_CERT.equals(encrUser)) {
        List<WSHandlerResult> results = 
            CastUtils.cast((List<?>)
                message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));
        if (results != null) {
            encrKeyBuilder.setUseThisCert(getReqSigCert(results));
             
            //TODO This is a hack, this should not come under USE_REQ_SIG_CERT
            if (encrKeyBuilder.isCertSet()) {
                encrKeyBuilder.setUserInfo(getUsername(results));
            }
        } else {
            policyNotAsserted(token, "No security results in incoming message");
        }
    } else {
        encrKeyBuilder.setUserInfo(encrUser);
    }
    
    return encrUser;
}
 
Example 15
Source File: SymmetricBindingHandler.java    From steady with Apache License 2.0 5 votes vote down vote up
private String getEncryptedKey() {
    
    List<WSHandlerResult> results = CastUtils.cast((List<?>)message.getExchange().getInMessage()
        .get(WSHandlerConstants.RECV_RESULTS));
    
    for (WSHandlerResult rResult : results) {
        List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults();
        
        for (WSSecurityEngineResult wser : wsSecEngineResults) {
            Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION);
            String encryptedKeyID = (String)wser.get(WSSecurityEngineResult.TAG_ID);
            if (actInt.intValue() == WSConstants.ENCR
                && encryptedKeyID != null
                && encryptedKeyID.length() != 0) {
                Date created = new Date();
                Date expires = new Date();
                expires.setTime(created.getTime() + 300000);
                SecurityToken tempTok = new SecurityToken(encryptedKeyID, created, expires);
                tempTok.setSecret((byte[])wser.get(WSSecurityEngineResult.TAG_SECRET));
                tempTok.setSHA1(getSHA1((byte[])wser
                                        .get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY)));
                tokenStore.add(tempTok);
                
                return encryptedKeyID;
            }
        }
    }
    return null;
}
 
Example 16
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 5 votes vote down vote up
public String setEncryptionUser(WSSecEncryptedKey encrKeyBuilder, TokenWrapper token,
                              boolean sign, Crypto crypto) {
    String encrUser = (String)message.getContextualProperty(sign 
                                                            ? SecurityConstants.SIGNATURE_USERNAME
                                                            : SecurityConstants.ENCRYPT_USERNAME);
    if (crypto != null && encrUser == null) {
        try {
            encrUser = crypto.getDefaultX509Identifier();
        } catch (WSSecurityException e1) {
            throw new Fault(e1);
        }
    } else if (encrUser == null || "".equals(encrUser)) {
        policyNotAsserted(token, "No " + (sign ? "signature" : "encryption") + " crypto object found.");
    }
    if (encrUser == null || "".equals(encrUser)) {
        policyNotAsserted(token, "A " + (sign ? "signature" : "encryption") + " username needs to be declared.");
    }
    if (WSHandlerConstants.USE_REQ_SIG_CERT.equals(encrUser)) {
        List<WSHandlerResult> results = 
            CastUtils.cast((List<?>)
                message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));
        if (results != null) {
            encrKeyBuilder.setUseThisCert(getReqSigCert(results));
             
            //TODO This is a hack, this should not come under USE_REQ_SIG_CERT
            if (encrKeyBuilder.isCertSet()) {
                encrKeyBuilder.setUserInfo(getUsername(results));
            }
        } else {
            policyNotAsserted(token, "No security results in incoming message");
        }
    } else {
        encrKeyBuilder.setUserInfo(encrUser);
    }
    
    return encrUser;
}
 
Example 17
Source File: WSS4JInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
protected void doResults(
    SoapMessage msg, 
    String actor,
    Element soapHeader,
    Element soapBody,
    List<WSSecurityEngineResult> wsResult, 
    boolean utWithCallbacks
) throws SOAPException, XMLStreamException, WSSecurityException {
    /*
     * All ok up to this point. Now construct and setup the security result
     * structure. The service may fetch this and check it.
     */
    List<WSHandlerResult> results = CastUtils.cast((List<?>)msg.get(WSHandlerConstants.RECV_RESULTS));
    if (results == null) {
        results = new ArrayList<WSHandlerResult>();
        msg.put(WSHandlerConstants.RECV_RESULTS, results);
    }
    WSHandlerResult rResult = new WSHandlerResult(actor, wsResult);
    results.add(0, rResult);

    for (WSSecurityEngineResult o : wsResult) {
        final Principal p = (Principal)o.get(WSSecurityEngineResult.TAG_PRINCIPAL);
        if (p != null && isSecurityContextPrincipal(p, wsResult)) {
            msg.put(PRINCIPAL_RESULT, p);
            if (!utWithCallbacks) {
                WSS4JTokenConverter.convertToken(msg, p);
            }
            Object receivedAssertion = null;
            
            List<String> roles = null;
            if (o.get(WSSecurityEngineResult.TAG_SAML_ASSERTION) != null) {
                String roleAttributeName = (String)msg.getContextualProperty(
                        SecurityConstants.SAML_ROLE_ATTRIBUTENAME);
                if (roleAttributeName == null || roleAttributeName.length() == 0) {
                    roleAttributeName = SAML_ROLE_ATTRIBUTENAME_DEFAULT;
                }
                receivedAssertion = o.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
                roles = SAMLUtils.parseRolesInAssertion(receivedAssertion, roleAttributeName);
                SAMLSecurityContext context = createSecurityContext(p, roles);
                context.setIssuer(SAMLUtils.getIssuer(receivedAssertion));
                context.setAssertionElement(SAMLUtils.getAssertionElement(receivedAssertion));
                msg.put(SecurityContext.class, context);
            } else {
                msg.put(SecurityContext.class, createSecurityContext(p));
            }
        }
    }
}
 
Example 18
Source File: WSS4JInOutTest.java    From steady with Apache License 2.0 4 votes vote down vote up
@Test
public void testEncryption() throws Exception {
    Map<String, String> outProperties = new HashMap<String, String>();
    outProperties.put(WSHandlerConstants.ACTION, WSHandlerConstants.ENCRYPT);
    outProperties.put(WSHandlerConstants.ENC_PROP_FILE, "outsecurity.properties");
    outProperties.put(WSHandlerConstants.USER, "myalias");
    outProperties.put("password", "myAliasPassword");
    
    Map<String, String> inProperties = new HashMap<String, String>();
    inProperties.put(WSHandlerConstants.ACTION, WSHandlerConstants.ENCRYPT);
    inProperties.put(WSHandlerConstants.DEC_PROP_FILE, "insecurity.properties");
    inProperties.put(
        WSHandlerConstants.PW_CALLBACK_CLASS, 
        "org.apache.cxf.ws.security.wss4j.TestPwdCallback"
    );
    
    List<String> xpaths = new ArrayList<String>();
    xpaths.add("//wsse:Security");
    xpaths.add("//s:Body/xenc:EncryptedData");

    List<WSHandlerResult> handlerResults = 
        getResults(makeInvocation(outProperties, xpaths, inProperties));

    assertNotNull(handlerResults);
    assertSame(handlerResults.size(), 1);
    //
    // This should contain exactly 1 protection result
    //
    final java.util.List<WSSecurityEngineResult> protectionResults =
        handlerResults.get(0).getResults();
    assertNotNull(protectionResults);
    assertSame(protectionResults.size(), 1);
    //
    // This result should contain a reference to the decrypted element,
    // which should contain the soap:Body Qname
    //
    final java.util.Map<String, Object> result =
        protectionResults.get(0);
    final java.util.List<WSDataRef> protectedElements =
        CastUtils.cast((List<?>)result.get(WSSecurityEngineResult.TAG_DATA_REF_URIS));
    assertNotNull(protectedElements);
    assertSame(protectedElements.size(), 1);
    assertEquals(
        protectedElements.get(0).getName(),
        new javax.xml.namespace.QName(
            "http://schemas.xmlsoap.org/soap/envelope/",
            "Body"
        )
    );
}
 
Example 19
Source File: SignatureConfirmationTest.java    From steady with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSignatureConfirmationRequest() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    
    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
    msg.put(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, "true");
    msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(WSHandlerConstants.USER, "myalias");
    msg.put("password", "myAliasPassword");
    //
    // This is necessary to convince the WSS4JOutInterceptor that we're
    // functioning as a requestor
    //
    msg.put(org.apache.cxf.message.Message.REQUESTOR_ROLE, true);

    handler.handleMessage(msg);
    doc = part;
    
    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/ds:Signature", doc);

    byte[] docbytes = getMessageBytes(doc);
    //
    // Save the signature for future confirmation
    //
    List<WSHandlerResult> sigv = CastUtils.cast((List<?>)msg.get(WSHandlerConstants.SEND_SIGV));
    assertNotNull(sigv);
    assertTrue(sigv.size() != 0);
    
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);
    inHandler.setProperty(WSHandlerConstants.SIG_PROP_FILE, "insecurity.properties");
    inHandler.setProperty(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, "true");

    inHandler.handleMessage(inmsg);
    
    //
    // Check that the inbound signature result was saved
    //
    WSSecurityEngineResult result = 
        (WSSecurityEngineResult) inmsg.get(WSS4JInInterceptor.SIGNATURE_RESULT);
    assertNotNull(result);
    
    List<WSHandlerResult> sigReceived = 
        CastUtils.cast((List<?>)inmsg.get(WSHandlerConstants.RECV_RESULTS));
    assertNotNull(sigReceived);
    assertTrue(sigReceived.size() != 0);
    
    testSignatureConfirmationResponse(sigv, sigReceived);
}
 
Example 20
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
public void setFeatures(List<? extends Feature> f) {
    features = CastUtils.cast(f);
}