/** * Sets the offset * * @param offset The offset value as an integer */ public void setOffset(int offset) throws WSSecurityException { //This element MUST NOT be used if the <Generation> element is specified if (elementGeneration == null) { elementOffset = element.getOwnerDocument().createElementNS( ns, ConversationConstants.WSC_PREFIX + ":" + ConversationConstants.OFFSET_LN ); elementOffset.appendChild( element.getOwnerDocument().createTextNode(Integer.toString(offset)) ); element.appendChild(elementOffset); } else { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "offsetError"); } }
/** * Creates and adds a Nonce element to this UsernameToken */ public void addNonce(Document doc) { if (elementNonce != null) { return; } byte[] nonceValue = null; try { nonceValue = WSSecurityUtil.generateNonce(16); } catch (WSSecurityException ex) { LOG.debug(ex.getMessage(), ex); return; } elementNonce = doc.createElementNS(WSConstants.WSSE_NS, "wsse:" + WSConstants.NONCE_LN); elementNonce.appendChild(doc.createTextNode(org.apache.xml.security.utils.XMLUtils.encodeToString(nonceValue))); elementNonce.setAttributeNS(null, "EncodingType", BASE64_ENCODING); element.appendChild(elementNonce); }
private Element createKeyInfoElement(Document encryptedDataDoc, X509Certificate remoteCert) throws Exception { Element keyInfoElement = encryptedDataDoc.createElementNS(SIG_NS, SIG_PREFIX + ":KeyInfo"); byte[] data = null; try { data = remoteCert.getEncoded(); } catch (CertificateEncodingException e) { throw new WSSecurityException( WSSecurityException.ErrorCode.SECURITY_TOKEN_UNAVAILABLE, e, "encodeError" ); Text text = encryptedDataDoc.createTextNode(org.apache.xml.security.utils.XMLUtils.encodeToString(data)); Element cert = encryptedDataDoc.createElementNS(SIG_NS, SIG_PREFIX + ":X509Certificate"); cert.appendChild(text); Element x509Data = encryptedDataDoc.createElementNS(SIG_NS, SIG_PREFIX + ":X509Data"); x509Data.appendChild(cert); keyIdentifierNode = x509Data; } else if (keyIdType.equals(RSSecurityUtils.X509_ISSUER_SERIAL)) { String issuer = remoteCert.getIssuerDN().getName(); java.math.BigInteger serialNumber = remoteCert.getSerialNumber(); DOMX509IssuerSerial domIssuerSerial = new DOMX509IssuerSerial( keyInfoElement.appendChild(keyIdentifierNode);
public static Element createBSTX509(Document doc, X509Certificate cert, Element secRefE, String secRefEncType) throws WSSecurityException { byte[] data; try { data = cert.getEncoded(); } catch (CertificateEncodingException e) { throw new WSSecurityException( WSSecurityException.ErrorCode.SECURITY_TOKEN_UNAVAILABLE, e, "encodeError" ); } String prefix = XMLUtils.getPrefixNS(WSConstants.WSSE_NS, secRefE); if (prefix == null) { prefix = WSConstants.WSSE_PREFIX; } Element elem = doc.createElementNS(WSConstants.WSSE_NS, prefix + ":BinarySecurityToken"); XMLUtils.setNamespace(elem, WSConstants.WSSE_NS, prefix); // elem.setAttributeNS(WSConstants.XMLNS_NS, "xmlns", ""); elem.setAttributeNS(null, "ValueType", X509Security.X509_V3_TYPE); if (secRefEncType != null) { elem.setAttributeNS(null, "EncodingType", secRefEncType); } Text certText = doc.createTextNode(org.apache.xml.security.utils.XMLUtils.encodeToString(data)); // no line wrap elem.appendChild(certText); return elem; }
public static void storeBytesInAttachment( Element parentElement, Document doc, String attachmentId, byte[] bytes, CallbackHandler attachmentCallbackHandler ) throws WSSecurityException { parentElement.setAttributeNS(XMLUtils.XMLNS_NS, "xmlns:xop", WSConstants.XOP_NS); Element xopInclude = doc.createElementNS(WSConstants.XOP_NS, "xop:Include"); xopInclude.setAttributeNS(null, "href", "cid:" + attachmentId); parentElement.appendChild(xopInclude); Attachment resultAttachment = new Attachment(); resultAttachment.setId(attachmentId); resultAttachment.setMimeType("application/ciphervalue"); resultAttachment.setSourceStream(new ByteArrayInputStream(bytes)); AttachmentResultCallback attachmentResultCallback = new AttachmentResultCallback(); attachmentResultCallback.setAttachmentId(attachmentId); attachmentResultCallback.setAttachment(resultAttachment); try { attachmentCallbackHandler.handle(new Callback[]{attachmentResultCallback}); } catch (Exception e) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, e); } }
/** * Returns whether the security header is empty * * @return true if empty or if there is no security header * false if non empty security header */ public boolean isEmpty() throws WSSecurityException { if (doc == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "empty", new Object[] {"The Document of WSSecHeader is null"}); } if (securityHeader == null) { securityHeader = WSSecurityUtil.findWsseSecurityHeaderBlock( doc, doc.getDocumentElement(), actor, false ); } if (securityHeader == null || securityHeader.getFirstChild() == null) { return true; } return false; }
public void removeSecurityHeader() throws WSSecurityException { if (securityHeader == null) { if (doc == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "empty", new Object[] {"The Document of WSSecHeader is null"}); } securityHeader = WSSecurityUtil.findWsseSecurityHeaderBlock( doc, doc.getDocumentElement(), actor, false ); } if (securityHeader != null) { Node parent = securityHeader.getParentNode(); parent.removeChild(securityHeader); } }
private String getEncodingMethodAlgorithm(Element parent) throws WSSecurityException { Element encMethod = getNode(parent, WSS4JConstants.ENC_NS, "EncryptionMethod", 0); if (encMethod == null) { LOG.fine("EncryptionMethod element is not available"); throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity"); } return encMethod.getAttribute("Algorithm"); }
for (Node currentChild = elem.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling() @SuppressWarnings("unchecked") List<WSDataRef> dataRefs = (List<WSDataRef>)r.get(WSSecurityEngineResult.TAG_DATA_REF_URIS); if (dataRefs != null) { for (WSDataRef dataRef : dataRefs) { QName el = new QName(decryptedElem.getNamespaceURI(), decryptedElem.getLocalName()); Processor proc = request.getWssConfig().getProcessor(el); if (proc != null) { LOG.debug("Processing decrypted element with: {}", proc.getClass().getName()); String typeStr = encryptedDataElement.getAttributeNS(null, "Type"); if (typeStr != null && !(WSConstants.ENC_NS + "Element").equals(typeStr)) { throw new WSSecurityException( WSSecurityException.ErrorCode.INVALID_SECURITY, "badElement", new Object[] {"Element", typeStr} new QName(encryptedDataElement.getNamespaceURI(), encryptedDataElement.getLocalName()); Processor proc = request.getWssConfig().getProcessor(el); if (proc != null) { LOG.debug("Processing decrypted element with: {}", proc.getClass().getName());
String keyIdentifierValue = secRef.getKeyIdentifierValue(); String type = secRef.getKeyIdentifierValueType(); WSSecurityEngineResult result = request.getWsDocInfo().getResult(keyIdentifierValue); if (result != null) { samlAssertion = (SamlAssertionWrapper)result.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); return samlAssertion; } else { token = findProcessedTokenElement( strElement.getOwnerDocument(), request.getWsDocInfo(), request.getCallbackHandler(), keyIdentifierValue, type ); if (token != null) { if (!"Assertion".equals(token.getLocalName())) { throw new WSSecurityException( WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity" ); strElement.getOwnerDocument(), request.getWsDocInfo(), request.getCallbackHandler(), keyIdentifierValue, type ); throw new WSSecurityException( WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity" );
protected void addToken(SoapMessage message) { WSSConfig.init(); SamlToken tok = (SamlToken)assertTokens(message); Header h = findSecurityHeader(message, true); try { SamlAssertionWrapper wrapper = addSamlToken(tok, message); if (wrapper == null) { AssertionInfoMap aim = message.get(AssertionInfoMap.class); Collection<AssertionInfo> ais = PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.SAML_TOKEN); for (AssertionInfo ai : ais) { if (ai.isAsserted()) { ai.setAsserted(false); } } return; } Element el = (Element)h.getObject(); el = (Element)DOMUtils.getDomElement(el); el.appendChild(wrapper.toDOM(el.getOwnerDocument())); } catch (WSSecurityException ex) { policyNotAsserted(tok, ex.getMessage(), message); } }
/** * Sets the KeyIdentifier Element as a X509 certificate. * Takes a X509 certificate, converts its data into base 64 and inserts * it into a <code>wsse:KeyIdentifier</code> element, which is placed * in the <code>wsse:SecurityTokenReference</code> element. * * @param cert is the X509 certificate to be inserted as key identifier */ public void setKeyIdentifier(X509Certificate cert) throws WSSecurityException { Document doc = element.getOwnerDocument(); byte[] data = null; try { data = cert.getEncoded(); } catch (CertificateEncodingException e) { throw new WSSecurityException( WSSecurityException.ErrorCode.SECURITY_TOKEN_UNAVAILABLE, e, "encodeError" ); } Text text = doc.createTextNode(org.apache.xml.security.utils.XMLUtils.encodeToString(data)); createKeyIdentifier(doc, X509_V3_TYPE, text, true); }
public void execute(WSHandler handler, SecurityActionToken actionToken, RequestData reqData) throws WSSecurityException { CallbackHandler callbackHandler = reqData.getCallbackHandler(); if (callbackHandler == null) { callbackHandler = handler.getPasswordCallbackHandler(reqData); throw new WSSecurityException( WSSecurityException.ErrorCode.FAILURE, "noCallback" ); new WSPasswordCallback(reqData.getUsername(), WSPasswordCallback.CUSTOM_TOKEN); throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, e, "empty", new Object[] {"WSHandler: password callback failed"}); throw new WSSecurityException( WSSecurityException.ErrorCode.FAILURE, "resourceNotFound", new Object[] {"CustomToken"} ); Element securityHeader = reqData.getSecHeader().getSecurityHeaderElement(); securityHeader.appendChild(securityHeader.getOwnerDocument().adoptNode(customToken));
/** * Return the computed KeyInfo value as a DOM Element * Call this method after <code>prepare()</code> */ public Element getKeyInfoElement() throws WSSecurityException { Element parent = getDocument().createElement("temp"); DOMCryptoContext cryptoContext = new DOMCryptoContext() { }; cryptoContext.putNamespacePrefix(WSConstants.SIG_NS, WSConstants.SIG_PREFIX); try { keyInfo.marshal(new DOMStructure(parent), cryptoContext); } catch (MarshalException ex) { LOG.error(ex.getMessage(), ex); throw new WSSecurityException( WSSecurityException.ErrorCode.FAILED_SIGNATURE, ex ); } return (Element)parent.getFirstChild(); }
&& "EncryptedKey".equals(((Element)entropyObject).getLocalName())) { EncryptedKeyProcessor processor = new EncryptedKeyProcessor(); Element entropyElement = (Element)entropyObject; RequestData requestData = new RequestData(); requestData.setDecCrypto(stsProperties.getSignatureCrypto()); requestData.setCallbackHandler(stsProperties.getCallbackHandler()); requestData.setWssConfig(WSSConfig.getNewInstance()); requestData.setWsDocInfo(new WSDocInfo(entropyElement.getOwnerDocument())); try { List<WSSecurityEngineResult> results = processor.handleToken(entropyElement, requestData); Entropy entropy = new Entropy(); entropy.setDecryptedKey((byte[])results.get(0).get(WSSecurityEngineResult.TAG_SECRET)); return entropy; } catch (WSSecurityException e) { LOG.log(Level.WARNING, "", e); throw new STSException(e.getMessage(), e, STSException.INVALID_REQUEST);
/** * Sets the KeyIdentifier Element as a X509 Subject-Key-Identifier (SKI). * Takes a X509 certificate, gets the SKI data, converts it into base 64 and * inserts it into a <code>wsse:KeyIdentifier</code> element, which is placed * in the <code>wsse:SecurityTokenReference</code> element. * * @param cert is the X509 certificate to get the SKI * @param crypto is the Crypto implementation. Used to read SKI info bytes from certificate */ public void setKeyIdentifierSKI(X509Certificate cert, Crypto crypto) throws WSSecurityException { // // As per the 1.1 specification, SKI can only be used for a V3 certificate // if (cert.getVersion() != 3) { throw new WSSecurityException( WSSecurityException.ErrorCode.UNSUPPORTED_SECURITY_TOKEN, "invalidCertForSKI", new Object[] {cert.getVersion()}); } Document doc = element.getOwnerDocument(); // Fall back to Merlin if crypto parameter is null Crypto skiCrypto = crypto; if (skiCrypto == null) { skiCrypto = new Merlin(); } byte[] data = skiCrypto.getSKIBytesFromCert(cert); Text text = doc.createTextNode(org.apache.xml.security.utils.XMLUtils.encodeToString(data)); createKeyIdentifier(doc, SKI_URI, text, true); }
) throws WSSecurityException { if (WSConstants.SIG_NS.equals(keyInfoChildElement.getNamespaceURI()) && WSConstants.X509_DATA_LN.equals(keyInfoChildElement.getLocalName())) { data.getBSPEnforcer().handleBSPRule(BSPRule.R5426); if (x509Child != null && WSConstants.SIG_NS.equals(x509Child.getNamespaceURI())) { if (WSConstants.X509_ISSUER_SERIAL_LN.equals(x509Child.getLocalName())) { DOMX509IssuerSerial issuerSerial = new DOMX509IssuerSerial(x509Child); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ISSUER_SERIAL); cryptoType.setIssuerSerial(issuerSerial.getIssuer(), issuerSerial.getSerialNumber()); return data.getDecCrypto().getX509Certificates(cryptoType); } else if (WSConstants.X509_CERT_LN.equals(x509Child.getLocalName())) { byte[] token = EncryptionUtils.getDecodedBase64EncodedData(x509Child); if (token == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidCertData", new Object[] {"0"}); X509Certificate cert = data.getDecCrypto().loadCertificate(in); if (cert != null) { return new X509Certificate[]{cert}; throw new WSSecurityException( WSSecurityException.ErrorCode.SECURITY_TOKEN_UNAVAILABLE, e, "parseError" );
data.getValidator(new QName(elem.getNamespaceURI(), elem.getLocalName())); Element foundElement = data.getWsDocInfo().getTokenElement(id); if (elem.equals(foundElement)) { WSSecurityEngineResult result = data.getWsDocInfo().getResult(id); return java.util.Collections.singletonList(result); } else if (foundElement != null) { throw new WSSecurityException( WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "duplicateError" ); WSSecurityEngineResult result = null; if (samlAssertion.isSigned()) { result = new WSSecurityEngineResult(WSConstants.ST_SIGNED, samlAssertion); result.put(WSSecurityEngineResult.TAG_DATA_REF_URIS, dataRefs); } else { result = new WSSecurityEngineResult(WSConstants.ST_UNSIGNED, samlAssertion);
/** * Get the default certificates from the KeyStore * @param crypto The Crypto object containing the default alias * @return The default certificates * @throws WSSecurityException */ private X509Certificate[] getDefaultCerts( Crypto crypto ) throws WSSecurityException { if (crypto == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noSigCryptoFile"); } if (crypto.getDefaultX509Identifier() != null) { CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(crypto.getDefaultX509Identifier()); return crypto.getX509Certificates(cryptoType); } else { throw new WSSecurityException( WSSecurityException.ErrorCode.INVALID_SECURITY, "unsupportedKeyInfo" ); } }
private List<WSSecurityEngineResult> processToken(Element tokenElement, final SoapMessage message) throws WSSecurityException { RequestData data = new CXFRequestData(); Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message); try { data.setCallbackHandler(SecurityUtils.getCallbackHandler(o)); } catch (Exception ex) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex); } data.setMsgContext(message); data.setWssConfig(WSSConfig.getNewInstance()); WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument()); data.setWsDocInfo(wsDocInfo); BinarySecurityTokenProcessor p = new BinarySecurityTokenProcessor(); return p.handleToken(tokenElement, data); }