axis-java-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From d...@apache.org
Subject cvs commit: ws-axis/contrib/wss4j/src/org/apache/ws/security/util AxisUtil.java Loader.java WSSecurityUtil.java
Date Tue, 14 Oct 2003 12:08:19 GMT
dims        2003/10/14 05:08:19

  Added:       contrib/wss4j/src/org/apache/ws/security/util AxisUtil.java
                        Loader.java WSSecurityUtil.java
  Log:
  ******* WORK IN PROGRESS *******
  
  Initial check-in of my sandbox for ws-security related code.
  
  Revision  Changes    Path
  1.1                  ws-axis/contrib/wss4j/src/org/apache/ws/security/util/AxisUtil.java
  
  Index: AxisUtil.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.ws.security.util;
  
  import org.apache.axis.Message;
  import org.apache.xml.security.c14n.Canonicalizer;
  import org.w3c.dom.Document;
  
  import javax.xml.soap.MessageFactory;
  import javax.xml.soap.SOAPEnvelope;
  import javax.xml.soap.SOAPMessage;
  import javax.xml.transform.dom.DOMSource;
  import java.io.ByteArrayInputStream;
  
  /**
   * Axis Utility methods.
   * <p>
   * @author  Davanum Srinivas (dims@yahoo.com).
   */
  public class AxisUtil {
      /**
       * Convert envelope into a DOM Document.
       * <p>
       * @param   env         
       * @return              
       * @throws  Exception  
       */
      public static Document toDocument(SOAPEnvelope env) throws Exception {
          return ((org.apache.axis.message.SOAPEnvelope) env).getAsDocument();
      }
  
      /**
       * Convert a DOM Document into a soap message.
       * <p>
       * @param   doc         
       * @return              
       * @throws  Exception  
       */
      public static SOAPMessage toSOAPMessage(Document doc) throws Exception {
          Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
          byte[] canonicalMessage = c14n.canonicalizeSubtree(doc);
          ByteArrayInputStream in = new ByteArrayInputStream(canonicalMessage);
          MessageFactory factory = MessageFactory.newInstance();
          return factory.createMessage(null, in);
      }
  
      /**
       * Update soap message.
       * <p>
       * @param   doc         
       * @param   message         
       * @return              
       * @throws  Exception  
       */
      public static SOAPMessage updateSOAPMessage(Document doc, Message message) throws Exception
{
          DOMSource domSource = new DOMSource(doc);
          message.getSOAPPart().setContent(domSource);
          return message;
      }
  }
  
  
  1.1                  ws-axis/contrib/wss4j/src/org/apache/ws/security/util/Loader.java
  
  Index: Loader.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.ws.security.util;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  
  import java.lang.reflect.InvocationTargetException;
  import java.net.URL;
  
  /**
   * Load resources (or images) from various sources.
   * <p>
   * @author  Davanum Srinivas (dims@yahoo.com).
   */
  public class Loader {
      private static Log log = LogFactory.getLog(Loader.class.getName());
  
      /**
       * This method will search for <code>resource</code> in different
       * places. The rearch order is as follows:
       * <ol>
       * <p><li>Search for <code>resource</code> using the thread
context
       * class loader under Java2. If that fails, search for
       * <code>resource</code> using the class loader that loaded this
       * class (<code>Loader</code>).
       * <p><li>Try one last time with
       * <code>ClassLoader.getSystemResource(resource)</code>, that is is
       * using the system class loader in JDK 1.2 and virtual machine's
       * built-in class loader in JDK 1.1.
       * </ol>
       * <p>
       * @param   resource   
       * @return             
       */
      static public URL getResource(String resource) {
          ClassLoader classLoader = null;
          URL url = null;
          try {
              // We could not find resource. Ler us now try with the
              // classloader that loaded this class.
              classLoader = Loader.class.getClassLoader();
              if (classLoader != null) {
                  log.debug("Trying to find [" + resource + "] using " + classLoader + " class
loader.");
                  url = classLoader.getResource(resource);
                  if (url != null) {
                      return url;
                  }
              }
          } catch (Throwable t) {
              log.warn("Caught Exception while in Loader.getResource. This may be innocuous.",
t);
          }
      
          // Last ditch attempt: get the resource from the class path. It
          // may be the case that clazz was loaded by the Extentsion class
          // loader which the parent of the system class loader. Hence the
          // code below.
          log.debug("Trying to find [" + resource + "] using ClassLoader.getSystemResource().");
          return ClassLoader.getSystemResource(resource);
      }
  
      /**
       * Get the Thread context class loader.
       * <p>
       * @return                              
       * @throws  IllegalAccessException     
       * @throws  InvocationTargetException  
       */
      private static ClassLoader getTCL() throws IllegalAccessException, InvocationTargetException
{
          return Thread.currentThread().getContextClassLoader();
      }
  
      /**
       * If running under JDK 1.2 load the specified class using the
       * <code>Thread</code> <code>contextClassLoader</code> if that
       * fails try Class.forname.
       * <p>
       * @param   clazz                    
       * @return                           
       * @throws  ClassNotFoundException  
       */
      static public Class loadClass(String clazz) throws ClassNotFoundException {
          try {
              return getTCL().loadClass(clazz);
          } catch (Throwable e) {
              // we reached here because tcl was null or because of a
              // security exception, or because clazz could not be loaded...
              // In any case we now try one more time
              return Class.forName(clazz);
          }
      }
  }
  
  
  1.1                  ws-axis/contrib/wss4j/src/org/apache/ws/security/util/WSSecurityUtil.java
  
  Index: WSSecurityUtil.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.ws.security.util;
  
  import org.apache.axis.utils.XMLUtils;
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.apache.ws.security.WSConstants;
  import org.apache.xml.security.utils.Base64;
  import org.apache.xpath.XPathAPI;
  import org.w3c.dom.*;
  import org.w3c.dom.Node;
  import org.w3c.dom.Text;
  
  import javax.xml.soap.*;
  import javax.xml.transform.TransformerException;
  import java.util.Iterator;
  
  /**
   * WS-Security Utility methods.
   * <p>
   * @author  Davanum Srinivas (dims@yahoo.com).
   */
  public class WSSecurityUtil {
      private static Log log = LogFactory.getLog(WSSecurityUtil.class);
  
      /**
       * Returns first WS-Security header for a given actor.
       * Only one WS-Security header is allowed for an actor.
       * <p>
       * @param   env             
       * @param   actor           
       * @return                  
       * @throws  SOAPException  
       */
      public static SOAPHeaderElement getSecurityHeader(SOAPEnvelope env, String actor) throws
SOAPException {
          SOAPHeader header = env.getHeader();
          if (header == null) {
              return null;
          }
          Iterator headerElements = header.examineHeaderElements(actor);
          while (headerElements.hasNext()) {
              SOAPHeaderElement he = (SOAPHeaderElement) headerElements.next();
              Name nm = he.getElementName();
  
              // find ws-security header
              if (nm.getLocalName().equalsIgnoreCase(WSConstants.WSSE_LN) && nm.getURI().equalsIgnoreCase(WSConstants.WSSE_NS))
{
                  return he;
              }
          }
          return null;
      }
  
      /**
       * Returns the first WS-Security header element for a given actor
       * Only one WS-Security header is allowed for an actor.
       * <p>
       * @param   doc     
       * @param   actor   
       * @return          
       */
      public static Element getSecurityHeader(Document doc, String actor) {
          Element soapHeaderElement = (Element) getDirectChild(doc.getFirstChild(), "Header",
WSConstants.SOAP_NS);
          NodeList list = soapHeaderElement.getElementsByTagNameNS(WSConstants.WSSE_NS, WSConstants.WSSE_LN);
          int len = list.getLength();
          Element elem;
          Attr attr;
          String hActor;
          for (int i = 0; i < len; i++) {
              elem = (Element) list.item(i);
              attr = elem.getAttributeNodeNS(WSConstants.SOAP_NS, "actor");
              hActor = (attr != null) ? attr.getValue() : null;
              if ((((hActor == null) || (hActor.length() == 0)) && ((actor == null)
|| (actor.length() == 0))) || ((hActor != null) && (actor != null) && hActor.equalsIgnoreCase(actor)))
{
                  return elem;
              }
          }
          return null;
      }
  
      /**
       * get the child with specified localname and namespace.
       * <p>
       * @param   fNode       
       * @param   localName   
       * @param   namespace   
       * @return              
       */
      public static Node getDirectChild(Node fNode, String localName, String namespace) {
          for (Node currentChild = fNode.getFirstChild(); currentChild != null; currentChild
= currentChild.getNextSibling()) {
              if (namespace.equalsIgnoreCase(currentChild.getNamespaceURI()) && localName.equalsIgnoreCase(currentChild.getLocalName()))
{
                  return currentChild;
              }
          }
          return null;
      }
  
      /**
       * return the first soap "Body" element.
       * <p>
       * @param   doc   
       * @return        
       */
      public static Element findBodyElement(Document doc) {
          Element soapBodyElement = (Element) WSSecurityUtil.getDirectChild(doc.getFirstChild(),
"Body", WSConstants.SOAP_NS);
          return soapBodyElement;
      }
  
      /**
       * set the namespace if it is not set already.
       * <p>
       * @param   element     
       * @param   namespace   
       * @param   prefix      
       * @return              
       */
      public static String setNamespace(Element element, String namespace, String prefix)
{
          String pre = XMLUtils.getPrefix(namespace, element);
          if (pre != null) {
              return pre;
          }
          element.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + prefix, namespace);
          return prefix;
      }
  
      /**
       * Search for an element given its id.
       * <p>
       * @param   doc   
       * @param   id    
       * @return        
       */
      public static Element getElementById(Document doc, String id) {
          if (id == null) {
              return null;
          }
          id = id.trim();
          if ((id.length() == 0) || (id.charAt(0) != '#')) {
              return null;
          }
          id = id.substring(1);
          try {
              Element nscontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc,
"wsu", WSConstants.WSU_NS);
              Element element = (Element) XPathAPI.selectSingleNode(doc, "//*[@wsu:Id='" +
id + "']", nscontext);
              return element;
          } catch (TransformerException ex) {
              log.error(ex);
          }
          return null;
      }
  
      /**
       * Create a BinarySecurityToken element
       * <p>
       * @param   doc        
       * @param   wsuIdVal   
       * @return             
       */
      public static Element createBinarySecurityToken(Document doc, String wsuIdVal) {
          Element retVal = doc.createElementNS(WSConstants.WSSE_NS, "wsse:BinarySecurityToken");
          retVal.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsu", WSConstants.WSU_NS);
          retVal.setAttributeNS(WSConstants.WSU_NS, "wsu:Id", wsuIdVal);
          retVal.setAttributeNS(null, "ValueType", "wsse:X509v3");
          retVal.setAttributeNS(null, "EncodingType", "wsse:Base64Binary");
          return retVal;
      }
  
      /**
       * create a new element in the same namespace
       * <p>
       * @param   parent      
       * @param   localName   
       * @return              
       */
      private static Element createElementInSameNamespace(Element parent, String localName)
{
          String prefix = parent.getPrefix();
          if (prefix == null) {
              prefix = "";
          }
          String qName = prefix + ":" + localName;
          String nsUri = parent.getNamespaceURI();
          return parent.getOwnerDocument().createElementNS(nsUri, qName);
      }
  
      /**
       * find a child element with given namespace and local name
       * <p>
       * @param   parent         
       * @param   namespaceUri   
       * @param   localName      
       * @return                 
       */
      private static Element findChildElement(Element parent, String namespaceUri, String
localName) {
          NodeList children = parent.getChildNodes();
          int len = children.getLength();
          for (int i = 0; i < len; i++) {
              Node child = children.item(i);
              if (child.getNodeType() == 1) {
                  Element elementChild = (Element) child;
                  if (namespaceUri.equals(elementChild.getNamespaceURI()) && localName.equals(elementChild.getLocalName()))
{
                      return elementChild;
                  }
              }
          }
          return null;
      }
  
      /**
       * append a child element
       * <p>
       * @param   doc      
       * @param   parent   
       * @param   child    
       * @return           
       */
      public static Element appendChildElement(Document doc, Element parent, Element child)
{
          Node whitespaceText = doc.createTextNode("\n");
          parent.appendChild(whitespaceText);
          parent.appendChild(child);
          return child;
      }
  
      /**
       * prepend a child element
       * <p>
       * @param   doc             
       * @param   parent          
       * @param   child           
       * @param   addWhitespace   
       * @return                  
       */
      public static Element prependChildElement(Document doc, Element parent, Element child,
boolean addWhitespace) {
          Node firstChild = parent.getFirstChild();
          if (firstChild == null) {
              parent.appendChild(child);
          } else {
              parent.insertBefore(child, firstChild);
          }
          if (addWhitespace) {
              Node whitespaceText = doc.createTextNode("\n");
              parent.insertBefore(whitespaceText, child);
          }
          return child;
      }
  
      /**
       * find the ws-security header block
       * <p>
       * @param   doc             
       * @param   envelope        
       * @param   doCreate        
       * @return                  
       */
      public static Element findWsseSecurityHeaderBlock(Document doc, Element envelope, boolean
doCreate) {
          Element header = findChildElement(envelope, WSConstants.SOAP_NS, "Header");
          if (header == null) {
              if (doCreate) {
                  header = createElementInSameNamespace(envelope, "Header");
                  header = prependChildElement(doc, envelope, header, true);
              }
          }
  
          Element wsseSecurity = findChildElement(header, WSConstants.WSSE_NS, "Security");
          if (wsseSecurity != null) {
              return wsseSecurity;
          }
          if (doCreate) {
              wsseSecurity = header.getOwnerDocument().createElementNS(WSConstants.WSSE_NS,
"wsse:Security");
              wsseSecurity.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
              return prependChildElement(doc, header, wsseSecurity, true);
          }
          return null;
      }
  
      /**
       * create a base64 test node
       * <p>
       * @param   doc    
       * @param   data   
       * @return         
       */
      public static Text createBase64EncodedTextNode(Document doc, byte data[]) {
          return doc.createTextNode("\n" + Base64.encode(data) + "\n");
      }
  
      /**
       * use xpath to find a node
       * <p>
       * @param   contextNode   
       * @param   xpath         
       * @param   nsContext     
       * @return                
       * @throws  Exception    
       */
      public static Node selectSingleNode(Node contextNode, String xpath, Element nsContext)
throws Exception {
          try {
              return XPathAPI.selectSingleNode(contextNode, xpath, nsContext);
          } catch (TransformerException e) {
              throw new Exception("Unable to resolve XPath", e);
          }
      }
  
      /**
       * Create a namespace context with namespaces of interest
       * @param doc
       * @return 
       */
      public static Element createNamespaceContext(Document doc) {
          Element nsContext = doc.createElementNS(null, "namespaceContext");
          nsContext.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:env", WSConstants.SOAP_NS);
          nsContext.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
          nsContext.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsu", WSConstants.WSU_NS);
          nsContext.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:ds", WSConstants.SIG_NS);
          nsContext.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:xenc", WSConstants.ENC_NS);
          return nsContext;
      }
  }
  
  

Mime
View raw message