List of usage examples for org.w3c.dom Node cloneNode
public Node cloneNode(boolean deep);
From source file:org.apache.ws.security.message.ModifiedRequestTest.java
/** * Test that signs a SOAP body element "value". The SOAP request is then modified * so that the signed "value" element is put in the header, and the value of the * original element is changed. The wsu:Id value of the original element is also * changed. Signature verification will pass, so we need to check the wsu:Id's. *//*from w w w. ja v a2 s. c o m*/ @org.junit.Test public void testMovedElementChangedId() throws Exception { WSSecSignature builder = new WSSecSignature(); builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security"); LOG.info("Before Signing...."); Document doc = SOAPUtil.toSOAPPart(SOAPMSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>(); WSEncryptionPart encP = new WSEncryptionPart("value", "http://blah.com", ""); parts.add(encP); builder.setParts(parts); Document signedDoc = builder.build(doc, crypto, secHeader); // // Replace the signed element with a modified element, and move the original // signed element into the SOAP header // org.w3c.dom.Element secHeaderElement = secHeader.getSecurityHeader(); org.w3c.dom.Element envelopeElement = signedDoc.getDocumentElement(); org.w3c.dom.Node valueNode = envelopeElement.getElementsByTagNameNS("http://blah.com", "value").item(0); org.w3c.dom.Node clonedValueNode = valueNode.cloneNode(true); secHeaderElement.appendChild(clonedValueNode); valueNode.getFirstChild().setNodeValue("250"); String savedId = ((org.w3c.dom.Element) valueNode).getAttributeNS(WSConstants.WSU_NS, "Id"); ((org.w3c.dom.Element) valueNode).setAttributeNS(WSConstants.WSU_NS, "wsu:Id", "id-250"); if (LOG.isDebugEnabled()) { LOG.debug("After Signing...."); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } // // Now we check that the wsu:Id of the element we want signed corresponds to the // wsu:Id that was actually signed...again, this should pass // List<WSSecurityEngineResult> results = verify(signedDoc); WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN); WSSecurityUtil.checkSignsAllElements(actionResult, new String[] { savedId }); // // Finally we need to check that the wsu:Id of the element we want signed in the // SOAP request is the same as the wsu:Id that was actually signed // envelopeElement = signedDoc.getDocumentElement(); org.w3c.dom.Node bodyNode = envelopeElement.getElementsByTagNameNS(WSConstants.URI_SOAP11_ENV, "Body") .item(0); valueNode = ((org.w3c.dom.Element) bodyNode).getElementsByTagNameNS("http://blah.com", "value").item(0); String actualId = ((org.w3c.dom.Element) valueNode).getAttributeNS(WSConstants.WSU_NS, "Id"); try { WSSecurityUtil.checkSignsAllElements(actionResult, new String[] { actualId }); fail("Failure expected on bad wsu:Id"); } catch (WSSecurityException ex) { assertTrue(ex.getErrorCode() == 6); assertTrue(ex.getMessage().startsWith("The signature or decryption was invalid")); } }
From source file:org.apache.ws.security.message.TestMessageTransformer.java
public static Element duplicateEncryptedDataInWsseWrapperHeader(Element saaj, boolean moveReferenceList) { if (moveReferenceList) { moveReferenceList(saaj);/*from w w w . j a v a 2 s . co m*/ } Element body = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"), true); Element encData = getFirstChildElement(body, new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), true); Element newEncData = createNewEncryptedData(encData); Element sh = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Header"), true); Element signature = getFirstChildElement(sh, new QName("http://www.w3.org/2000/09/xmldsig#", "Signature"), true); Node wsseHeader = signature.getParentNode(); Node newWsseHeader = wsseHeader.cloneNode(false); Node cur = wsseHeader.getFirstChild(); String newId = newEncData.getAttributeNS(null, "Id"); while (!cur.isSameNode(signature)) { cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId); } Element wrapper = encData.getOwnerDocument().createElementNS(null, "a"); wrapper.appendChild(newEncData); newWsseHeader.appendChild(wrapper); while (cur != null) { cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId); } if (!moveReferenceList) { updateEncryptedKeyRefList(newWsseHeader, newId); } Node parent = wsseHeader.getParentNode(); parent.removeChild(wsseHeader); parent.appendChild(newWsseHeader); print(saaj.getOwnerDocument()); return newEncData; }
From source file:org.apache.ws.security.message.TestMessageTransformer.java
private static Node copyHeadersAndUpdateRefList(Node cur, Node dest, String newId) { Node temp = cur.cloneNode(true); dest.appendChild(temp);/* w ww .j a v a 2 s . c o m*/ if (newId != null && temp.getNodeType() == Node.ELEMENT_NODE) { Element t = (Element) temp; if (t.getLocalName().equals("ReferenceList")) { Element ref = getFirstChildElement(t, new QName("http://www.w3.org/2001/04/xmlenc#", "DataReference"), true); Element newRef = (Element) ref.cloneNode(true); newRef.setAttributeNS(null, "URI", "#" + newId); t.appendChild(newRef); } } return cur.getNextSibling(); }
From source file:org.apache.ws.security.message.UsernameTokenTest.java
/** * A test for sending multiple nonces in the UsernameToken *///from ww w.j a va2 s .co m @org.junit.Test public void testMultipleNonce() throws Exception { WSSecUsernameToken builder = new WSSecUsernameToken(); builder.setPasswordType(WSConstants.PASSWORD_DIGEST); builder.setUserInfo("wernerd", "verySecret"); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); Document utDoc = builder.build(doc, secHeader); // // Manually find the Nonce node and duplicate it // org.w3c.dom.Element elem = builder.getUsernameTokenElement(); org.w3c.dom.NodeList list = elem.getElementsByTagNameNS(WSConstants.WSSE_NS, "Nonce"); org.w3c.dom.Node nonceNode = list.item(0); org.w3c.dom.Node nonceCopy = nonceNode.cloneNode(true); nonceNode.getParentNode().insertBefore(nonceCopy, nonceNode); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(utDoc); LOG.debug(outputString); } WSSecurityEngine newEngine = new WSSecurityEngine(); try { newEngine.processSecurityHeader(doc, null, callbackHandler, null); fail("Expected failure as it is not BSP compliant"); } catch (WSSecurityException ex) { // expected } WSSConfig config = WSSConfig.getNewInstance(); config.setWsiBSPCompliant(false); newEngine.setWssConfig(config); newEngine.processSecurityHeader(doc, null, callbackHandler, null); }
From source file:org.apache.ws.security.message.UsernameTokenTest.java
/** * A test for sending multiple Created elements in the UsernameToken */// w w w . ja va2 s . co m @org.junit.Test public void testMultipleCreated() throws Exception { WSSecUsernameToken builder = new WSSecUsernameToken(); builder.setPasswordType(WSConstants.PASSWORD_DIGEST); builder.setUserInfo("wernerd", "verySecret"); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); Document utDoc = builder.build(doc, secHeader); // // Manually find the Created node and duplicate it // org.w3c.dom.Element elem = builder.getUsernameTokenElement(); org.w3c.dom.NodeList list = elem.getElementsByTagNameNS(WSConstants.WSU_NS, "Created"); org.w3c.dom.Node createdNode = list.item(0); org.w3c.dom.Node createdCopy = createdNode.cloneNode(true); createdNode.getParentNode().insertBefore(createdCopy, createdNode); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(utDoc); LOG.debug(outputString); } WSSecurityEngine newEngine = new WSSecurityEngine(); try { newEngine.processSecurityHeader(doc, null, callbackHandler, null); fail("Expected failure as it is not BSP compliant"); } catch (WSSecurityException ex) { // expected } WSSConfig config = WSSConfig.getNewInstance(); config.setWsiBSPCompliant(false); newEngine.setWssConfig(config); newEngine.processSecurityHeader(doc, null, callbackHandler, null); }
From source file:org.apache.ws.security.message.UsernameTokenTest.java
/** * A test for sending multiple passwords in the UsernameToken *//* w w w.j a va 2 s . c o m*/ @org.junit.Test public void testMultiplePassword() throws Exception { WSSecUsernameToken builder = new WSSecUsernameToken(); builder.setPasswordType(WSConstants.PASSWORD_DIGEST); builder.setUserInfo("wernerd", "verySecret"); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); Document utDoc = builder.build(doc, secHeader); // // Manually find the Nonce node and duplicate it // org.w3c.dom.Element elem = builder.getUsernameTokenElement(); org.w3c.dom.NodeList list = elem.getElementsByTagNameNS(WSConstants.WSSE_NS, "Password"); org.w3c.dom.Node passwordNode = list.item(0); org.w3c.dom.Node passwordCopy = passwordNode.cloneNode(true); passwordNode.getParentNode().insertBefore(passwordCopy, passwordNode); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(utDoc); LOG.debug(outputString); } WSSecurityEngine newEngine = new WSSecurityEngine(); try { newEngine.processSecurityHeader(doc, null, callbackHandler, null); fail("Expected failure as it is not BSP compliant"); } catch (WSSecurityException ex) { // expected } WSSConfig config = WSSConfig.getNewInstance(); config.setWsiBSPCompliant(false); newEngine.setWssConfig(config); newEngine.processSecurityHeader(doc, null, callbackHandler, null); }
From source file:org.apache.ws.security.processor.ReferenceListProcessor.java
/** * Decrypt the EncryptedData argument using a SecretKey. * @param doc The (document) owner of EncryptedData * @param dataRefURI The URI of EncryptedData * @param encData The EncryptedData element * @param symmetricKey The SecretKey with which to decrypt EncryptedData * @param symEncAlgo The symmetric encryption algorithm to use * @throws WSSecurityException/*from w w w . ja va 2 s .c om*/ */ public static WSDataRef decryptEncryptedData(Document doc, String dataRefURI, Element encData, SecretKey symmetricKey, String symEncAlgo) throws WSSecurityException { XMLCipher xmlCipher = null; try { xmlCipher = XMLCipher.getInstance(symEncAlgo); xmlCipher.init(XMLCipher.DECRYPT_MODE, symmetricKey); } catch (XMLEncryptionException ex) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, ex); } WSDataRef dataRef = new WSDataRef(dataRefURI); dataRef.setWsuId(dataRefURI); dataRef.setAlgorithm(symEncAlgo); boolean content = X509Util.isContent(encData); dataRef.setContent(content); Node parent = encData.getParentNode(); Node previousSibling = encData.getPreviousSibling(); if (content) { encData = (Element) encData.getParentNode(); parent = encData.getParentNode(); } try { xmlCipher.doFinal(doc, encData, content); } catch (Exception ex) { throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, ex); } if (parent.getLocalName().equals(WSConstants.ENCRYPTED_HEADER) && parent.getNamespaceURI().equals(WSConstants.WSSE11_NS)) { Node decryptedHeader = parent.getFirstChild(); Element decryptedHeaderClone = (Element) decryptedHeader.cloneNode(true); parent.getParentNode().appendChild(decryptedHeaderClone); parent.getParentNode().removeChild(parent); dataRef.setProtectedElement(decryptedHeaderClone); dataRef.setXpath(getXPath(decryptedHeaderClone)); } else if (content) { dataRef.setProtectedElement(encData); dataRef.setXpath(getXPath(encData)); } else { Node decryptedNode; if (previousSibling == null) { decryptedNode = parent.getFirstChild(); } else { decryptedNode = previousSibling.getNextSibling(); } if (decryptedNode != null && Node.ELEMENT_NODE == decryptedNode.getNodeType()) { dataRef.setProtectedElement((Element) decryptedNode); } dataRef.setXpath(getXPath(decryptedNode)); } return dataRef; }
From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.AttributePreserveInsert.java
@Override public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) { if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) { return null; }/*ww w.j a va 2 s . c om*/ Node node1 = nodeList1.get(0); Node node2 = nodeList2.get(0); NamedNodeMap attributes2 = node2.getAttributes(); Comparator<Object> nameCompare = new Comparator<Object>() { @Override public int compare(Object arg0, Object arg1) { return ((Node) arg0).getNodeName().compareTo(((Node) arg1).getNodeName()); } }; Node[] tempNodes = {}; tempNodes = exhaustedNodes.toArray(tempNodes); Arrays.sort(tempNodes, nameCompare); int length = attributes2.getLength(); for (int j = 0; j < length; j++) { Node temp = attributes2.item(j); int pos = Arrays.binarySearch(tempNodes, temp, nameCompare); if (pos < 0) { Attr clone = (Attr) temp.cloneNode(true); ((Element) node1).setAttributeNode((Attr) node1.getOwnerDocument().importNode(clone, true)); } } return null; }
From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.InsertItems.java
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) { if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) { return null; }// w w w .j ava 2 s .c om List<Node> usedNodes = new ArrayList<Node>(); Node node1Parent = nodeList1.get(0).getParentNode(); for (Node aNodeList2 : nodeList2) { Node tempNode = node1Parent.getOwnerDocument().importNode(aNodeList2.cloneNode(true), true); if (LOG.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("matching node for insertion: "); sb.append(tempNode.getNodeName()); int attrLength = tempNode.getAttributes().getLength(); for (int x = 0; x < attrLength; x++) { sb.append(" : ("); sb.append(tempNode.getAttributes().item(x).getNodeName()); sb.append("/"); sb.append(tempNode.getAttributes().item(x).getNodeValue()); sb.append(")"); } LOG.debug(sb.toString()); } if (LOG.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("inserting into parent: "); sb.append(node1Parent.getNodeName()); int attrLength = node1Parent.getAttributes().getLength(); for (int x = 0; x < attrLength; x++) { sb.append(" : ("); sb.append(node1Parent.getAttributes().item(x).getNodeName()); sb.append("/"); sb.append(node1Parent.getAttributes().item(x).getNodeValue()); sb.append(")"); } LOG.debug(sb.toString()); } node1Parent.appendChild(tempNode); usedNodes.add(tempNode); } Node[] response = { nodeList2.get(0).getParentNode() }; return response; }
From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.NodeReplaceInsert.java
private List<Node> matchNodes(List<Node> exhaustedNodes, Node[] primaryNodes, ArrayList<Node> list) { List<Node> usedNodes = new ArrayList<Node>(20); Iterator<Node> itr = list.iterator(); Node parentNode = primaryNodes[0].getParentNode(); Document ownerDocument = parentNode.getOwnerDocument(); while (itr.hasNext()) { Node node = itr.next(); if (Element.class.isAssignableFrom(node.getClass()) && !exhaustedNodesContains(exhaustedNodes, node)) { if (LOG.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("matching node for replacement: "); sb.append(node.getNodeName()); int attrLength = node.getAttributes().getLength(); for (int j = 0; j < attrLength; j++) { sb.append(" : ("); sb.append(node.getAttributes().item(j).getNodeName()); sb.append("/"); sb.append(node.getAttributes().item(j).getNodeValue()); sb.append(")"); }/* ww w . ja v a 2 s. co m*/ LOG.debug(sb.toString()); } if (!checkNode(usedNodes, primaryNodes, node)) { //simply append the node if all the above fails Node newNode = ownerDocument.importNode(node.cloneNode(true), true); parentNode.appendChild(newNode); usedNodes.add(node); } } } return usedNodes; }