Package org.apache.rampart

Examples of org.apache.rampart.RampartException


            // Get the password
            CallbackHandler handler = RampartUtil.getPasswordCB(rmd);

            if (handler == null) {
                // If the callback handler is missing
                throw new RampartException("cbHandlerMissing");
            }

            WSPasswordCallback[] cb = { new WSPasswordCallback(user, WSPasswordCallback.SIGNATURE) };

            try {
                handler.handle(cb);
                if (cb[0].getPassword() != null && !"".equals(cb[0].getPassword())) {
                    password = cb[0].getPassword();
                    if (log.isDebugEnabled()) {
                        log.debug("Password : " + password);
                    }
                } else {
                    // If there's no password then throw an exception
                    throw new RampartException("noPasswordForUser", new String[] { user });
                }
            } catch (IOException e) {
                throw new RampartException("errorInGettingPasswordForUser", new String[] { user },
                        e);
            } catch (UnsupportedCallbackException e) {
                throw new RampartException("errorInGettingPasswordForUser", new String[] { user },
                        e);
            }

        } else {
            log.debug("No user value specified in the configuration");
            throw new RampartException("userMissing");
        }

        sig.setUserInfo(user, password);
        sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getAsymmetricSignature());
        sig.setSigCanonicalization(rpd.getAlgorithmSuite().getInclusiveC14n());

        try {
            sig.prepare(
                    rmd.getDocument(),
                    RampartUtil.getSignatureCrypto(rpd.getRampartConfig(),
                            rmd.getCustomClassLoader()), rmd.getSecHeader());
        } catch (WSSecurityException e) {
            throw new RampartException("errorInSignatureWithX509Token", e);
        }

        return sig;
    }
View Full Code Here


                if (token instanceof IssuedToken && rmd.isInitiator()) {
                    String id = RampartUtil.getIssuedToken(rmd, (IssuedToken) token);
                    try {
                        endSuppTok = rmd.getTokenStorage().getToken(id);
                    } catch (TrustException e) {
                        throw new RampartException("errorInRetrievingTokenId", new String[] { id },
                                e);
                    }

                    if (endSuppTok == null) {
                        throw new RampartException("errorInRetrievingTokenId", new String[] { id });
                    }

                    // Add the token to the header
                    Element siblingElem = RampartUtil.insertSiblingAfter(rmd,
                            this.getInsertionLocation(), (Element) endSuppTok.getToken());
                    this.setInsertionLocation(siblingElem);

                    if (suppTokens.isEncryptedToken()) {
                        this.encryptedTokensIdList.add(endSuppTok.getId());
                    }

                    // Add the extracted token
                    endSuppTokMap.put(token, endSuppTok);

                } else if (token instanceof X509Token) {

                    // We have to use a cert
                    // Prepare X509 signature
                    WSSecSignature sig = this.getSignatureBuilder(rmd, token);
                    Element bstElem = sig.getBinarySecurityTokenElement();
                    if (bstElem != null) {
                        bstElem = RampartUtil.insertSiblingAfter(rmd, this.getInsertionLocation(),
                                bstElem);
                        this.setInsertionLocation(bstElem);

                        SupportingPolicyData supportingPolcy = new SupportingPolicyData();
                        supportingPolcy.build(suppTokens);
                        supportingPolcy.setSignatureToken(token);
                        supportingPolcy.setEncryptionToken(token);
                        rmd.getPolicyData().addSupportingPolicyData(supportingPolcy);

                        if (suppTokens.isEncryptedToken()) {
                            this.encryptedTokensIdList.add(sig.getBSTTokenId());
                        }
                    }
                    endSuppTokMap.put(token, sig);

                } else if (token instanceof UsernameToken) {
                    WSSecUsernameToken utBuilder = addUsernameToken(rmd, (UsernameToken) token);

                    utBuilder.prepare(rmd.getDocument());

                    // Add the UT
                    Element elem = utBuilder.getUsernameTokenElement();
                    elem = RampartUtil.insertSiblingAfter(rmd, this.getInsertionLocation(), elem);

                    encryptedTokensIdList.add(utBuilder.getId());

                    // Move the insert location to the next element
                    this.setInsertionLocation(elem);
                    Date now = new Date();
                    try {
                        org.apache.rahas.Token tempTok = new org.apache.rahas.Token(
                                utBuilder.getId(), (OMElement) elem, now, new Date(
                                        now.getTime() + 300000));
                        endSuppTokMap.put(token, tempTok);
                    } catch (TrustException e) {
                        throw new RampartException("errorCreatingRahasToken", e);
                    }
                }
            }
        }
View Full Code Here

                if (tempSig.getBSTTokenId() != null) {
                    part = new WSEncryptionPart(tempSig.getBSTTokenId());
                }
            } else {

                throw new RampartException("UnsupportedTokenInSupportingToken");
            }
            sigParts.add(part);
        }

        return sigParts;
View Full Code Here

                    this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd,
                            this.getInsertionLocation(), sig.getSignatureElement()));

                } catch (WSSecurityException e) {
                    throw new RampartException("errorInSignatureWithX509Token", e);
                }
                sigValues.add(sig.getSignatureValue());
            }
        }
View Full Code Here

                }

                return dkSign.getSignatureValue();

            } catch (ConversationException e) {
                throw new RampartException("errorInDerivedKeyTokenSignature", e);
            } catch (WSSecurityException e) {
                throw new RampartException("errorInDerivedKeyTokenSignature", e);
            }
        } else {
            try {
                WSSecSignature sig = new WSSecSignature();
                sig.setWsConfig(rmd.getConfig());

                // If a EncryptedKeyToken is used, set the correct value type to
                // be used in the wsse:Reference in ds:KeyInfo
                if (policyToken instanceof X509Token) {
                    if (rmd.isInitiator()) {
                        sig.setCustomTokenValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
                                + WSConstants.ENC_KEY_VALUE_TYPE);
                        sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                    } else {
                        // the tok has to be an EncryptedKey token
                        sig.setEncrKeySha1value(((EncryptedKeyToken) tok).getSHA1());
                        sig.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                    }

                } else if (policyToken instanceof IssuedToken) {
                    sig.setCustomTokenValueType(WSConstants.WSS_SAML_NS
                            + WSConstants.SAML_ASSERTION_ID);
                    sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                }

                String sigTokId;

                if (policyToken instanceof SecureConversationToken) {
                    sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                    OMElement ref = tok.getAttachedReference();
                    if (ref == null) {
                        ref = tok.getUnattachedReference();
                    }

                    if (ref != null) {
                        sigTokId = SimpleTokenStore.getIdFromSTR(ref);
                    } else {
                        sigTokId = tok.getId();
                    }
                } else {
                    sigTokId = tok.getId();
                }

                // Hack to handle reference id issues
                // TODO Need a better fix
                if (sigTokId.startsWith("#")) {
                    sigTokId = sigTokId.substring(1);
                }

                sig.setCustomTokenId(sigTokId);
                sig.setSecretKey(tok.getSecret());
                sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getAsymmetricSignature());
                sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
                sig.prepare(
                        rmd.getDocument(),
                        RampartUtil.getSignatureCrypto(rpd.getRampartConfig(),
                                rmd.getCustomClassLoader()), rmd.getSecHeader());

                sig.setParts(sigParts);
                sig.addReferencesToSign(sigParts, rmd.getSecHeader());

                // Do signature
                sig.computeSignature();

                if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING)
                        && this.getInsertionLocation() == null) {
                    this.setInsertionLocation(RampartUtil.insertSiblingBefore(rmd,
                            this.mainRefListElement, sig.getSignatureElement()));
                } else {
                    this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd,
                            this.getInsertionLocation(), sig.getSignatureElement()));
                }

                return sig.getSignatureValue();

            } catch (WSSecurityException e) {
                throw new RampartException("errorInSignatureWithACustomToken", e);
            }

        }
    }
View Full Code Here

            throws RampartException {
        org.apache.rahas.Token tok = null;
        try {
            tok = rmd.getTokenStorage().getToken(tokenId);
        } catch (TrustException e) {
            throw new RampartException("errorInRetrievingTokenId", new String[] { tokenId }, e);
        }

        if (tok == null) {
            throw new RampartException("errorInRetrievingTokenId", new String[] { tokenId });
        }
        return tok;
    }
View Full Code Here

        RampartPolicyData rpd = rmd.getPolicyData();
        KerberosConfig krbConfig = rpd.getRampartConfig().getKerberosConfig();

        if (krbConfig == null || krbConfig.getProp() == null) {
            throw new RampartException("noKerberosConfigDefined");
        }

        WSSecKerberosToken krb = new WSSecKerberosToken();
        krb.setWsConfig(rmd.getConfig());

        log.debug("Token inclusion: " + token.getInclusion());

        RampartUtil.setKeyIdentifierType(rmd, krb, token);

        String user = null;
        String passwordFromConfig = null;
        String clientPricipal = null;
        String servicePrincipal = null;
        String password = null;
        String service = null;

        clientPricipal = (String) rmd.getMsgContext().getProperty(
                KerberosConfig.CLIENT_PRINCIPLE_NAME);
        servicePrincipal = (String) rmd.getMsgContext().getProperty(
                KerberosConfig.SERVICE_PRINCIPLE_NAME);

        if (clientPricipal == null || servicePrincipal == null) {
            // Get the user from kerberos configuration
            user = krbConfig.getProp().getProperty(KerberosConfig.CLIENT_PRINCIPLE_NAME);
            passwordFromConfig = krbConfig.getProp().getProperty(
                    KerberosConfig.CLIENT_PRINCIPLE_PASSWORD);
            if (passwordFromConfig == null) {
                passwordFromConfig = krbConfig.getProp().getProperty(
                        KerberosConfig.SERVICE_PRINCIPLE_PASSWORD);
            }

            // If kerberos user is not present, use user property as Alias
            if (user == null) {
                user = rpd.getRampartConfig().getUser();
            }

            if (user != null && !"".equals(user)) {
                log.debug("User : " + user);

                // Get the password
                CallbackHandler handler = RampartUtil.getPasswordCB(rmd);

                if (handler != null) {
                    WSPasswordCallback[] cb = { new WSPasswordCallback(user,
                            WSPasswordCallback.KERBEROS_TOKEN) };
                    try {
                        handler.handle(cb);
                        if (cb[0].getPassword() != null && !"".equals(cb[0].getPassword())) {
                            password = cb[0].getPassword();
                            log.debug("Password : " + password);
                        } else {
                            password = passwordFromConfig;
                        }
                    } catch (IOException e) {
                        throw new RampartException("errorInGettingPasswordForUser",
                                new String[] { user }, e);
                    } catch (UnsupportedCallbackException e) {
                        throw new RampartException("errorInGettingPasswordForUser",
                                new String[] { user }, e);
                    }
                } else {
                    password = passwordFromConfig;
                }

            }
            service = krbConfig.getProp().getProperty(KerberosConfig.SERVICE_PRINCIPLE_NAME);
        } else {
            user = clientPricipal;
            service = servicePrincipal;
        }

        krb.setUserInfo(user, password);
        krb.setServicePrincipalName(service);

        if (!rmd.isInitiator()) {
            krb.setReceiver(true);
        }

        try {
            krb.build(rmd.getDocument(), rmd.getSecHeader());
        } catch (WSSecurityException e) {
            throw new RampartException("errorInBuilingKereberosToken", e);
        }

        if (!rmd.isInitiator()) {
            setKerberosToken(rmd, krb);
        }
View Full Code Here

                    BinarySecurity token;
                    try {
                        token = new BinarySecurity(principal.getTokenElement());
                        krbToken.setBSTToken(token);
                    } catch (WSSecurityException e) {
                        throw new RampartException("errorExtractingKereberosToken");
                    }
                }
            }
        }
    }
View Full Code Here

        Vector encrParts = RampartUtil.getEncryptedParts(rmd);

        Vector sigParts = RampartUtil.getSignedParts(rmd);

        if (encryptionToken == null && encrParts.size() > 0) {
            throw new RampartException("encryptionTokenMissing");
        }

        if (encryptionToken != null && encrParts.size() > 0) {
            // The encryption token can be an IssuedToken or a
            // SecureConversationToken
            String tokenId = null;
            org.apache.rahas.Token tok = null;

            if (encryptionToken instanceof IssuedToken) {
                tokenId = rmd.getIssuedEncryptionTokenId();
                if (log.isDebugEnabled()) {
                    log.debug("Issued EncryptionToken Id : " + tokenId);
                }
            } else if (encryptionToken instanceof SecureConversationToken) {
                tokenId = rmd.getSecConvTokenId();
                if (log.isDebugEnabled()) {
                    log.debug("SCT Id : " + tokenId);
                }
            } else if (encryptionToken instanceof X509Token) {
                if (rmd.isInitiator()) {
                    tokenId = setupEncryptedKey(rmd, encryptionToken);
                } else {
                    tokenId = getEncryptedKey(rmd);
                }
            } // TODO SAMLToken

            if (tokenId == null || tokenId.length() == 0) {
                throw new RampartException("noSecurityToken");
            }

            // Hack to handle reference id issues
            // TODO Need a better fix
            if (tokenId.startsWith("#")) {
                tokenId = tokenId.substring(1);
            }

            /*
             * Get hold of the token from the token storage
             */
            tok = this.getToken(rmd, tokenId);

            /*
             * Attach the token into the message based on token inclusion values
             */
            boolean attached = false;
            Element encrTokenElement = null;
            Element refList = null;
            WSSecDKEncrypt dkEncr = null;
            WSSecEncrypt encr = null;
            Element encrDKTokenElem = null;

            if (SPConstants.INCLUDE_TOEKN_ALWAYS == encryptionToken.getInclusion()
                    || SPConstants.INCLUDE_TOKEN_ONCE == encryptionToken.getInclusion()
                    || (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == encryptionToken
                            .getInclusion())) {
                encrTokenElement = RampartUtil.appendChildToSecHeader(rmd, tok.getToken());
                attached = true;
            } else if (encryptionToken instanceof X509Token && rmd.isInitiator()) {
                encrTokenElement = RampartUtil.appendChildToSecHeader(rmd, tok.getToken());
            }

            Document doc = rmd.getDocument();

            AlgorithmSuite algorithmSuite = rpd.getAlgorithmSuite();
            if (encryptionToken.isDerivedKeys()) {
                log.debug("Use drived keys");

                dkEncr = new WSSecDKEncrypt();

                if (attached && tok.getAttachedReference() != null) {

                    dkEncr.setExternalKey(tok.getSecret(),
                            (Element) doc.importNode((Element) tok.getAttachedReference(), true));

                } else if (tok.getUnattachedReference() != null) {
                    dkEncr.setExternalKey(tok.getSecret(),
                            (Element) doc.importNode((Element) tok.getUnattachedReference(), true));
                } else {
                    dkEncr.setExternalKey(tok.getSecret(), tok.getId());
                }
                try {
                    dkEncr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
                    dkEncr.setDerivedKeyLength(algorithmSuite.getEncryptionDerivedKeyLength() / 8);
                    dkEncr.prepare(doc);
                    encrDKTokenElem = dkEncr.getdktElement();
                    RampartUtil.appendChildToSecHeader(rmd, encrDKTokenElem);

                    refList = dkEncr.encryptForExternalRef(null, encrParts);

                } catch (WSSecurityException e) {
                    throw new RampartException("errorInDKEncr");
                } catch (ConversationException e) {
                    throw new RampartException("errorInDKEncr");
                }
            } else {
                log.debug("NO derived keys, use the shared secret");
                encr = new WSSecEncrypt();

                encr.setWsConfig(rmd.getConfig());
                encr.setEncKeyId(tokenId);
                RampartUtil.setEncryptionUser(rmd, encr);
                encr.setEphemeralKey(tok.getSecret());
                encr.setDocument(doc);
                encr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
                // SymmKey is already encrypted, no need to do it again
                encr.setEncryptSymmKey(false);
                if (!rmd.isInitiator() && tok instanceof EncryptedKeyToken) {
                    encr.setUseKeyIdentifier(true);
                    encr.setCustomReferenceValue(((EncryptedKeyToken) tok).getSHA1());
                    encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                }

                try {

                    encr.prepare(
                            doc,
                            RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(),
                                    rmd.getCustomClassLoader()));
                    // Encrypt, get hold of the ref list and add it
                    refList = encr.encryptForExternalRef(null, encrParts);
                } catch (WSSecurityException e) {
                    throw new RampartException("errorInEncryption", e);
                }
            }

            this.mainRefListElement = RampartUtil.appendChildToSecHeader(rmd, refList);

            if (tlog.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }

            // Sometimes encryption token is not included in the the message
            if (encrTokenElement != null) {
                this.setInsertionLocation(encrTokenElement);
            } else if (timestampElement != null) {
                this.setInsertionLocation(timestampElement);
            }

            RampartUtil.handleEncryptedSignedHeaders(encrParts, sigParts, doc);

            HashMap sigSuppTokMap = null;
            HashMap endSuppTokMap = null;
            HashMap sgndEndSuppTokMap = null;
            HashMap sgndEncSuppTokMap = null;
            HashMap endEncSuppTokMap = null;
            HashMap sgndEndEncSuppTokMap = null;

            if (this.timestampElement != null) {
                sigParts.add(new WSEncryptionPart(RampartUtil
                        .addWsuIdToElement((OMElement) this.timestampElement)));
            }

            if (rmd.isInitiator()) {

                // Now add the supporting tokens
                SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
                sigSuppTokMap = this.handleSupportingTokens(rmd, sgndSuppTokens);

                SupportingToken endSuppTokens = rpd.getEndorsingSupportingTokens();
                endSuppTokMap = this.handleSupportingTokens(rmd, endSuppTokens);

                SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();
                sgndEndSuppTokMap = this.handleSupportingTokens(rmd, sgndEndSuppTokens);

                SupportingToken sgndEncryptedSuppTokens = rpd.getSignedEncryptedSupportingTokens();
                sgndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEncryptedSuppTokens);

                SupportingToken endorsingEncryptedSuppTokens = rpd
                        .getEndorsingEncryptedSupportingTokens();
                endEncSuppTokMap = this.handleSupportingTokens(rmd, endorsingEncryptedSuppTokens);

                SupportingToken sgndEndEncSuppTokens = rpd
                        .getSignedEndorsingEncryptedSupportingTokens();
                sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);

                Vector supportingToks = rpd.getSupportingTokensList();
                for (int i = 0; i < supportingToks.size(); i++) {
                    this.handleSupportingTokens(rmd, (SupportingToken) supportingToks.get(i));
                }

                SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
                this.handleSupportingTokens(rmd, encryptedSupportingToks);

                // Setup signature parts
                sigParts = addSignatureParts(sigSuppTokMap, sigParts);
                sigParts = addSignatureParts(sgndEncSuppTokMap, sigParts);
                sigParts = addSignatureParts(sgndEndSuppTokMap, sigParts);
                sigParts = addSignatureParts(sgndEndEncSuppTokMap, sigParts);

            } else {
                addSignatureConfirmation(rmd, sigParts);
            }

            // Sign the message
            // We should use the same key in the case of EncryptBeforeSig
            if (sigParts.size() > 0) {
                signatureValues.add(this.doSymmSignature(rmd, encryptionToken, tok, sigParts));
                this.mainSigId = RampartUtil.addWsuIdToElement((OMElement) this
                        .getInsertionLocation());
            }

            if (rmd.isInitiator()) {

                endSuppTokMap.putAll(endEncSuppTokMap);
                // Do endorsed signatures
                Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);
                for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
                    signatureValues.add(iter.next());
                }

                sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
                // Do signed endorsing signatures
                Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
                for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
                    signatureValues.add(iter.next());
                }
            }

            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
                tlog.debug("Encryption took :" + (t1 - t0) + ", Signature tool :" + (t2 - t1));
            }

            // Check for signature protection and encryption of UsernameToken
            if (rpd.isSignatureProtection() && this.mainSigId != null
                    || encryptedTokensIdList.size() > 0 && rmd.isInitiator()) {
                long t3 = 0, t4 = 0;
                if (tlog.isDebugEnabled()) {
                    t3 = System.currentTimeMillis();
                }
                log.debug("Signature protection");
                Vector secondEncrParts = new Vector();

                // Now encrypt the signature using the above token
                if (rpd.isSignatureProtection()) {
                    secondEncrParts.add(new WSEncryptionPart(this.mainSigId, "Element"));
                }

                if (rmd.isInitiator()) {
                    for (int i = 0; i < encryptedTokensIdList.size(); i++) {
                        secondEncrParts.add(new WSEncryptionPart((String) encryptedTokensIdList
                                .get(i), "Element"));
                    }
                }

                Element secondRefList = null;

                if (encryptionToken.isDerivedKeys()) {
                    try {
                        secondRefList = dkEncr.encryptForExternalRef(null, secondEncrParts);
                        RampartUtil.insertSiblingAfter(rmd, encrDKTokenElem, secondRefList);
                    } catch (WSSecurityException e) {
                        throw new RampartException("errorInDKEncr");
                    }
                } else {
                    try {
                        // Encrypt, get hold of the ref list and add it
                        secondRefList = encr.encryptForExternalRef(null, encrParts);
                        RampartUtil.insertSiblingAfter(rmd, encrTokenElement, secondRefList);
                    } catch (WSSecurityException e) {
                        throw new RampartException("errorInEncryption", e);
                    }
                }
                if (tlog.isDebugEnabled()) {
                    t4 = System.currentTimeMillis();
                    tlog.debug("Signature protection took :" + (t4 - t3));
                }
            }

        } else {
            throw new RampartException("encryptionTokenMissing");
        }
    }
View Full Code Here

                }
                sigTok = new EncryptedKeyToken(sigTokId, created, expires);
                sigTok.setSecret(krbToken.getSessionKey().getEncoded());
            }
        } else {
            throw new RampartException("signatureTokenMissing");
        }

        if (sigTokId == null || sigTokId.length() == 0) {
            throw new RampartException("noSecurityToken");
        }

        if (!(sigToken instanceof KerberosToken)) {

            sigTok = this.getToken(rmd, sigTokId);

            if (SPConstants.INCLUDE_TOEKN_ALWAYS == sigToken.getInclusion()
                    || SPConstants.INCLUDE_TOKEN_ONCE == sigToken.getInclusion()
                    || (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == sigToken
                            .getInclusion())) {
                sigTokElem = RampartUtil.appendChildToSecHeader(rmd, sigTok.getToken());
            } else if ((rmd.isInitiator() && sigToken instanceof X509Token)
                    || sigToken instanceof SecureConversationToken) {
                sigTokElem = RampartUtil.appendChildToSecHeader(rmd, sigTok.getToken());
            }
        }

        if (sigTokElem != null) {
            // Set the insertion location
            this.setInsertionLocation(sigTokElem);
        }

        HashMap sigSuppTokMap = null;
        HashMap endSuppTokMap = null;
        HashMap sgndEndSuppTokMap = null;
        HashMap sgndEncSuppTokMap = null;
        HashMap endEncSuppTokMap = null;
        HashMap sgndEndEncSuppTokMap = null;

        Vector sigParts = RampartUtil.getSignedParts(rmd);

        if (this.timestampElement != null) {
            sigParts.add(new WSEncryptionPart(RampartUtil
                    .addWsuIdToElement((OMElement) this.timestampElement)));
        }

        if (rmd.isInitiator()) {
            // Now add the supporting tokens
            SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
            sigSuppTokMap = this.handleSupportingTokens(rmd, sgndSuppTokens);

            SupportingToken endSuppTokens = rpd.getEndorsingSupportingTokens();
            endSuppTokMap = this.handleSupportingTokens(rmd, endSuppTokens);

            SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();
            sgndEndSuppTokMap = this.handleSupportingTokens(rmd, sgndEndSuppTokens);

            SupportingToken sgndEncryptedSuppTokens = rpd.getSignedEncryptedSupportingTokens();
            sgndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEncryptedSuppTokens);

            SupportingToken endorsingEncryptedSuppTokens = rpd
                    .getEndorsingEncryptedSupportingTokens();
            endEncSuppTokMap = this.handleSupportingTokens(rmd, endorsingEncryptedSuppTokens);

            SupportingToken sgndEndEncSuppTokens = rpd
                    .getSignedEndorsingEncryptedSupportingTokens();
            sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);

            Vector supportingToks = rpd.getSupportingTokensList();
            for (int i = 0; i < supportingToks.size(); i++) {
                this.handleSupportingTokens(rmd, (SupportingToken) supportingToks.get(i));
            }

            SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
            this.handleSupportingTokens(rmd, encryptedSupportingToks);

            // Setup signature parts
            sigParts = addSignatureParts(sigSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEncSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEndSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEndEncSuppTokMap, sigParts);

        } else {
            addSignatureConfirmation(rmd, sigParts);
        }

        if (sigParts.size() > 0) {
            if (sigToken instanceof KerberosToken) {
                krbToken.setParts(sigParts);
                try {
                    krbToken.signMessage();
                } catch (WSSecurityException e) {
                    throw new RampartException("errorInSignatureWithKerberosToken");
                }
                this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd,
                        this.getInsertionLocation(), krbToken.getSignatureElement()));
                signatureValues.add(krbToken.getSignatureValue());
            } else {
                // Sign the message
                signatureValues.add(this.doSymmSignature(rmd, sigToken, sigTok, sigParts));
            }

            this.mainSigId = RampartUtil.addWsuIdToElement((OMElement) this.getInsertionLocation());

        }

        if (rmd.isInitiator()) {
            // Adding the endorsing encrypted supporting tokens to endorsing supporting tokens
            endSuppTokMap.putAll(endEncSuppTokMap);
            // Do endorsed signatures
            Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);

            for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
                signatureValues.add(iter.next());
            }

            // Adding the signed endorsed encrypted tokens to signed endorsed supporting tokens
            sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
            // Do signed endorsing signatures
            Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
            for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
                signatureValues.add(iter.next());
            }
        }

        if (tlog.isDebugEnabled()) {
            t1 = System.currentTimeMillis();
        }

        // Encryption
        Token encrToken = rpd.getEncryptionToken();
        boolean isIssuedToken = false;
        if (encrToken instanceof IssuedToken) {
            isIssuedToken = true;
        }
        Element encrTokElem = null;
        if (sigToken.equals(encrToken)) {
            // Use the same token
            encrTokId = sigTokId;
            encrTok = sigTok;
            encrTokElem = sigTokElem;
        } else {
            encrTokId = rmd.getIssuedEncryptionTokenId();
            encrTok = this.getToken(rmd, encrTokId);

            if (SPConstants.INCLUDE_TOEKN_ALWAYS == encrToken.getInclusion()
                    || SPConstants.INCLUDE_TOKEN_ONCE == encrToken.getInclusion()
                    || (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == encrToken
                            .getInclusion())) {
                encrTokElem = (Element) encrTok.getToken();

                // Add the encrToken element before the sigToken element
                RampartUtil.insertSiblingBefore(rmd, sigTokElem, encrTokElem);
            }

        }

        Vector encrParts = RampartUtil.getEncryptedParts(rmd);

        // Check for signature protection
        if (rpd.isSignatureProtection() && this.mainSigId != null) {
            // Now encrypt the signature using the above token
            encrParts.add(new WSEncryptionPart(this.mainSigId, "Element"));
        }

        if (rmd.isInitiator()) {
            for (int i = 0; i < encryptedTokensIdList.size(); i++) {
                encrParts
                        .add(new WSEncryptionPart((String) encryptedTokensIdList.get(i), "Element"));
            }
        }

        Element refList = null;
        if (encrParts.size() > 0) {
            // The sec conv token can be used without derived keys
            if (encrToken.isDerivedKeys()) {

                try {
                    WSSecDKEncrypt dkEncr = new WSSecDKEncrypt();

                    // Check whether it is security policy 1.2 and use the secure conversation
                    // accordingly
                    if (SPConstants.SP_V12 == encrToken.getVersion()) {
                        dkEncr.setWscVersion(ConversationConstants.VERSION_05_12);
                    }

                    if (encrTokElem != null && encrTok.getAttachedReference() != null) {

                        dkEncr.setExternalKey(encrTok.getSecret(), (Element) doc.importNode(
                                (Element) encrTok.getAttachedReference(), true));
                    } else if (encrTok.getUnattachedReference() != null) {
                        dkEncr.setExternalKey(encrTok.getSecret(), (Element) doc.importNode(
                                (Element) encrTok.getUnattachedReference(), true));
                    } else if (!rmd.isInitiator() && encrToken.isDerivedKeys()) {

                        // If the Encrypted key used to create the derived key is not
                        // attached use key identifier as defined in WSS1.1 section
                        // 7.7 Encrypted Key reference
                        SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
                        if (encrTok instanceof EncryptedKeyToken) {
                            tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken) encrTok)
                                    .getSHA1());
                        }
                        dkEncr.setExternalKey(encrTok.getSecret(), tokenRef.getElement());

                    } else {
                        dkEncr.setExternalKey(encrTok.getSecret(), encrTok.getId());
                    }

                    if (encrTok instanceof EncryptedKeyToken) {
                        dkEncr.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
                                + WSConstants.ENC_KEY_VALUE_TYPE);
                    }

                    dkEncr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                    dkEncr.setDerivedKeyLength(rpd.getAlgorithmSuite()
                            .getEncryptionDerivedKeyLength() / 8);
                    dkEncr.prepare(doc);
                    Element encrDKTokenElem = null;
                    encrDKTokenElem = dkEncr.getdktElement();
                    if (encrTokElem != null) {
                        RampartUtil.insertSiblingAfter(rmd, encrTokElem, encrDKTokenElem);
                    } else if (timestampElement != null) {
                        RampartUtil.insertSiblingAfter(rmd, this.timestampElement, encrDKTokenElem);
                    } else {
                        RampartUtil.insertSiblingBefore(rmd, this.getInsertionLocation(),
                                encrDKTokenElem);
                    }

                    refList = dkEncr.encryptForExternalRef(null, encrParts);

                    RampartUtil.insertSiblingAfter(rmd, encrDKTokenElem, refList);

                } catch (WSSecurityException e) {
                    throw new RampartException("errorInDKEncr");
                } catch (ConversationException e) {
                    throw new RampartException("errorInDKEncr");
                }
            } else {
                try {

                    WSSecEncrypt encr = new WSSecEncrypt();

                    encr.setWsConfig(rmd.getConfig());
                    // Hack to handle reference id issues
                    // TODO Need a better fix
                    if (encrTokId.startsWith("#")) {
                        encrTokId = encrTokId.substring(1);
                    }
                    encr.setEncKeyId(encrTokId);

                    if (krbToken == null) {
                        encr.setEphemeralKey(encrTok.getSecret());
                        RampartUtil.setEncryptionUser(rmd, encr);
                        encr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                    } else {
                        if (encrTok != null) {
                            byte[] secret = encrTok.getSecret();
                            int factor = 0;
                            if (rmd.getPolicyData().getRampartConfig() != null) {
                                KerberosConfig config = null;
                                String fac = null;
                                config = rmd.getPolicyData().getRampartConfig().getKerberosConfig();
                                if ((fac = config.getProp().getProperty(
                                        KerberosConfig.KDC_DES_AES_FACTOR)) != null) {
                                    try {
                                        factor = Integer.parseInt(fac);
                                    } catch (Exception e) {
                                        factor = 0;
                                    }
                                }
                            }

                            if (factor > 1) {
                                byte[] newSecret = new byte[secret.length * 4];
                                int j = 0;
                                for (int i = 0; i < newSecret.length; i++) {
                                    newSecret[i] = secret[j++];
                                    if (j == secret.length)
                                        j = 0;
                                }
                                encr.setEphemeralKey(newSecret);
                                encrTok.setSecret(newSecret);
                            } else {
                                encr.setEphemeralKey(secret);
                                encrTok.setSecret(secret);
                            }
                            ((EncryptedKeyToken) encrTok).setSHA1(krbToken.getKrbSession()
                                    .getThumbPrintEncoded());
                            try {
                                rmd.getTokenStorage().add(sigTok);
                            } catch (TrustException e) {
                                throw new RampartException("errorAddingKerbTokenToStore");
                            }
                        }
                    }

                    encr.setDocument(doc);
                    encr.setEncryptSymmKey(false);

                    // Use key identifier in the KeyInfo in server side
                    if (!rmd.isInitiator()) {
                        if (krbToken != null) {
                            encr.setUseKeyIdentifier(true);
                            encr.setKeyIdentifierType(WSConstants.KERBEROS_KEY_IDENTIFIER);
                        } else if (encrTok instanceof EncryptedKeyToken) {
                            encr.setUseKeyIdentifier(true);
                            encr.setCustomReferenceValue(((EncryptedKeyToken) encrTok).getSHA1());
                            encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                        } else if (isIssuedToken) {
                            encr.setUseKeyIdentifier(true);
                            encr.setCustomReferenceValue(encrTokId);
                            encr.setKeyIdentifierType(WSConstants.SAML_ASSERTION_IDENTIFIER);
                            try {
                                // RampartUtil.insertSiblingAfter(rmd,this.timestampElement,getLLOMfromOM(encrTok.getToken()));
                            } catch (Exception e) {
                                log.debug("error while converting SAML issued token to a dom element");
                            }
                        }
                    }
                    encr.prepare(
                            doc,
                            RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(),
                                    rmd.getCustomClassLoader()));

                    // Encrypt, get hold of the ref list and add it
                    refList = encr.encryptForExternalRef(null, encrParts);

                    if (encrTokElem != null) {
                        RampartUtil.insertSiblingAfter(rmd, encrTokElem, refList);
                    } else {
                        RampartUtil.insertSiblingBeforeOrPrepend(rmd, this.getInsertionLocation(),
                                refList);
                    }

                } catch (WSSecurityException e) {
                    throw new RampartException("errorInEncryption", e);
                }
            }
        }

        if (tlog.isDebugEnabled()) {
View Full Code Here

TOP

Related Classes of org.apache.rampart.RampartException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.