/** @inheritDoc */
  public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) {

    if (element == null) {
      return false;
    }

    boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE);
    boolean isDSAKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_DSAKEYVALUE);

    if (isKeyValue) {

      this._dsaKeyElement =
          XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);

      if (this._dsaKeyElement != null) {
        return true;
      }
    } else if (isDSAKeyValue) {

      // this trick is needed to allow the RetrievalMethodResolver to eat a
      // ds:DSAKeyValue directly (without KeyValue)
      this._dsaKeyElement = element;

      return true;
    }

    return false;
  }
Exemplo n.º 2
0
 protected void circumventBugIfNeeded(XMLSignatureInput input)
     throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
   if (!input.isNeedsToBeExpanded()) {
     return;
   }
   Document doc = null;
   if (input.getSubNode() != null) {
     doc = XMLUtils.getOwnerDocument(input.getSubNode());
   } else {
     doc = XMLUtils.getOwnerDocument(input.getNodeSet());
   }
   XMLUtils.circumventBug2650(doc);
 }
Exemplo n.º 3
0
  /**
   * Constructor XPath2FilterContainer04
   *
   * @param doc
   * @param xpath2filter
   * @param filterType
   */
  private XPath2FilterContainer04(Document doc, String xpath2filter, String filterType) {

    super(doc);

    this._constructionElement.setAttributeNS(null, XPath2FilterContainer04._ATT_FILTER, filterType);

    if ((xpath2filter.length() > 2) && (!Character.isWhitespace(xpath2filter.charAt(0)))) {
      XMLUtils.addReturnToElement(this._constructionElement);
      this._constructionElement.appendChild(doc.createTextNode(xpath2filter));
      XMLUtils.addReturnToElement(this._constructionElement);
    } else {
      this._constructionElement.appendChild(doc.createTextNode(xpath2filter));
    }
  }
  protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, OutputStream os)
      throws CanonicalizationException {
    try {
      String inclusiveNamespaces = null;

      if (this._transformObject.length(
              InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
              InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES)
          == 1) {
        Element inclusiveElement =
            XMLUtils.selectNode(
                this._transformObject.getElement().getFirstChild(),
                InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
                InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
                0);

        inclusiveNamespaces =
            new InclusiveNamespaces(inclusiveElement, this._transformObject.getBaseURI())
                .getInclusiveNamespaces();
      }

      Canonicalizer20010315ExclOmitComments c14n = new Canonicalizer20010315ExclOmitComments();
      if (os != null) {
        c14n.setWriter(os);
      }
      byte[] result;
      if (input.isOctetStream()) {
        result = c14n.engineCanonicalize(input.get_Bytes());
      } else if (input.isElement()) {
        org.w3c.dom.Node excl = input.getExcludeNode();
        result = c14n.engineCanonicalizeSubTree(input.getSubNode(), inclusiveNamespaces, excl);
      } else {
        result = c14n.engineCanonicalizeXPathNodeSet(input.getNodeSet(), inclusiveNamespaces);
      }
      XMLSignatureInput output = new XMLSignatureInput(result);
      if (os != null) {
        output.setOutputStream(os);
      }
      return output;
    } catch (IOException ex) {
      throw new CanonicalizationException("empty", ex);
    } catch (ParserConfigurationException ex) {
      throw new CanonicalizationException("empty", ex);
    } catch (XMLSecurityException ex) {
      throw new CanonicalizationException("empty", ex);
    } catch (SAXException ex) {
      throw new CanonicalizationException("empty", ex);
    }
  }
  /**
   * Method engineCanResolve
   *
   * @param element
   * @param BaseURI
   * @param storage
   * @return
   */
  public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) {

    cat.debug("Can I resolve " + element.getTagName());

    if (element == null) {
      return false;
    }

    boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE);
    boolean isRSAKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RSAKEYVALUE);

    if (isKeyValue) {
      try {
        Element nscontext =
            XMLUtils.createDSctx(element.getOwnerDocument(), "ds", Constants.SignatureSpecNS);

        this._rsaKeyElement =
            (Element)
                XPathAPI.selectSingleNode(element, "./ds:" + Constants._TAG_RSAKEYVALUE, nscontext);

        if (this._rsaKeyElement != null) {
          return true;
        }
      } catch (TransformerException ex) {
      }
    } else if (isRSAKeyValue) {

      // this trick is needed to allow the RetrievalMethodResolver to eat a
      // ds:RSAKeyValue directly (without KeyValue)
      this._rsaKeyElement = element;

      return true;
    }

    return false;
  }
 /**
  * Method engineCanonicalizeXPathNodeSet
  *
  * @inheritDoc
  * @param xpathNodeSet
  * @throws CanonicalizationException
  */
 public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) throws CanonicalizationException {
   if (xpathNodeSet.size() == 0) {
     return new byte[0];
   }
   this._xpathNodeSet = xpathNodeSet;
   try {
     Node rootNodeOfC14n = XMLUtils.getOwnerDocument(this._xpathNodeSet);
     this.canonicalizeXPathNodeSet(rootNodeOfC14n, new NameSpaceSymbTable());
     this._writer.close();
     if (this._writer instanceof ByteArrayOutputStream) {
       return ((ByteArrayOutputStream) this._writer).toByteArray();
     }
     return null;
   } catch (UnsupportedEncodingException ex) {
     throw new CanonicalizationException("empty", ex);
   } catch (IOException ex) {
     throw new CanonicalizationException("empty", ex);
   }
 }
  /**
   * Method main
   *
   * @param args
   */
  public static void main(String[] args) {

    XMLUtils.spitOutVersions(log);

    boolean useTextUI = true;

    if (useTextUI) {
      junit.textui.TestRunner.run(suite());
    } else {
      String[] testCaseName = {"-noloading", ModuleTest.class.getName()};

      try {
        String lookAndFeelClass = "com.incors.plaf.kunststoff.KunststoffLookAndFeel";
        javax.swing.LookAndFeel lnf =
            (javax.swing.LookAndFeel) Class.forName(lookAndFeelClass).newInstance();

        javax.swing.UIManager.setLookAndFeel(lnf);
      } catch (Exception ex) {
      }

      junit.swingui.TestRunner.main(testCaseName);
    }
  }
Exemplo n.º 8
0
  /**
   * Verifies signatures in entity descriptor represented by the <code>Document</code>.
   *
   * @param doc The document.
   * @throws SAML2MetaException if unable to verify the entity descriptor.
   */
  public static void verifySignature(Document doc) throws SAML2MetaException {
    NodeList sigElements = null;
    try {
      Element nscontext =
          org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
      sigElements = XPathAPI.selectNodeList(doc, "//ds:Signature", nscontext);
    } catch (Exception ex) {
      if (debug.messageEnabled()) {
        debug.message("SAML2MetaSecurityUtils.verifySignature:", ex);
        throw new SAML2MetaException(ex.getMessage());
      }
    }
    int numSigs = sigElements.getLength();
    if (debug.messageEnabled()) {
      debug.message("SAML2MetaSecurityUtils.verifySignature:" + " # of signatures = " + numSigs);
    }

    if (numSigs == 0) {
      return;
    }

    // If there are signatures then explicitly identify the ID Attribute, See comments section of
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8017265
    doc.getDocumentElement().setIdAttribute(SAML2Constants.ID, true);

    initializeKeyStore();

    for (int i = 0; i < numSigs; i++) {
      Element sigElement = (Element) sigElements.item(i);
      String sigParentName = sigElement.getParentNode().getLocalName();
      Object[] objs = {sigParentName};
      if (debug.messageEnabled()) {
        debug.message(
            "SAML2MetaSecurityUtils.verifySignature: "
                + "verifying signature under "
                + sigParentName);
      }

      try {
        XMLSignature signature = new XMLSignature(sigElement, "");
        signature.addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
        KeyInfo ki = signature.getKeyInfo();

        X509Certificate x509cert = null;
        if (ki != null && ki.containsX509Data()) {
          if (keyStore != null) {
            StorageResolver sr = new StorageResolver(new KeyStoreResolver(keyStore));
            ki.addStorageResolver(sr);
          }
          x509cert = ki.getX509Certificate();
        }

        if (x509cert == null) {
          if (debug.messageEnabled()) {
            debug.message(
                "SAML2MetaSecurityUtils.verifySignature:" + " try to find cert in KeyDescriptor");
          }
          String xpath =
              "following-sibling::*[local-name()=\""
                  + TAG_KEY_DESCRIPTOR
                  + "\" and namespace-uri()=\""
                  + NS_META
                  + "\"]";
          Node node = XPathAPI.selectSingleNode(sigElement, xpath);

          if (node != null) {
            Element kd = (Element) node;
            String use = kd.getAttributeNS(null, ATTR_USE);
            if ((use.length() == 0) || use.equals("signing")) {
              NodeList nl = kd.getChildNodes();
              for (int j = 0; j < nl.getLength(); j++) {
                Node child = nl.item(j);
                if (child.getNodeType() == Node.ELEMENT_NODE) {
                  String localName = child.getLocalName();
                  String ns = child.getNamespaceURI();
                  if (TAG_KEY_INFO.equals(localName) && NS_XMLSIG.equals(ns)) {

                    ki = new KeyInfo((Element) child, "");
                    if (ki.containsX509Data()) {
                      if (keyStore != null) {
                        KeyStoreResolver ksr = new KeyStoreResolver(keyStore);
                        StorageResolver sr = new StorageResolver(ksr);
                        ki.addStorageResolver(sr);
                      }

                      x509cert = ki.getX509Certificate();
                    }
                  }
                  break;
                }
              }
            }
          }
        }

        if (x509cert == null) {
          throw new SAML2MetaException("verify_no_cert", objs);
        }

        if (checkCert
            && ((keyProvider == null) || (keyProvider.getCertificateAlias(x509cert) == null))) {
          throw new SAML2MetaException("untrusted_cert", objs);
        }

        PublicKey pk = x509cert.getPublicKey();

        if (!signature.checkSignatureValue(pk)) {
          throw new SAML2MetaException("verify_fail", objs);
        }
      } catch (SAML2MetaException sme) {
        throw sme;
      } catch (Exception ex) {
        debug.error("SAML2MetaSecurityUtils.verifySignature: ", ex);
        throw new SAML2MetaException(
            Locale.getString(SAML2MetaUtils.resourceBundle, "verify_fail", objs)
                + "\n"
                + ex.getMessage());
      }
    }
  }
Exemplo n.º 9
0
  /**
   * Builds a SOAPEnvelope from DOM Document.
   *
   * @param doc - The dom document that contains a SOAP message
   * @param useDoom
   * @return
   * @throws WSSecurityException
   */
  public static SOAPEnvelope getSOAPEnvelopeFromDOMDocument(Document doc, boolean useDoom)
      throws WSSecurityException {

    if (useDoom) {
      try {
        // Get processed headers
        SOAPEnvelope env = (SOAPEnvelope) doc.getDocumentElement();
        ArrayList processedHeaderQNames = new ArrayList();
        SOAPHeader soapHeader = env.getHeader();

        if (soapHeader != null) {
          Iterator headerBlocs = soapHeader.getChildElements();
          while (headerBlocs.hasNext()) {

            OMElement element = (OMElement) headerBlocs.next();
            SOAPHeaderBlock header = null;

            if (element instanceof SOAPHeaderBlock) {
              header = (SOAPHeaderBlock) element;

              // If a header block is not an instance of SOAPHeaderBlock, it means that
              // it is a header we have added in rampart eg. EncryptedHeader and should
              // be converted to SOAPHeaderBlock for processing
            } else {
              header = soapHeader.addHeaderBlock(element.getLocalName(), element.getNamespace());
              Iterator attrIter = element.getAllAttributes();
              while (attrIter.hasNext()) {
                OMAttribute attr = (OMAttribute) attrIter.next();
                header.addAttribute(
                    attr.getLocalName(), attr.getAttributeValue(), attr.getNamespace());
              }
              Iterator nsIter = element.getAllDeclaredNamespaces();
              while (nsIter.hasNext()) {
                OMNamespace ns = (OMNamespace) nsIter.next();
                header.declareNamespace(ns);
              }
              // retrieve all child nodes (including any text nodes)
              // and re-attach to header block
              Iterator children = element.getChildren();
              while (children.hasNext()) {
                OMNode child = (OMNode) children.next();
                child.detach();
                header.addChild(child);
              }

              element.detach();

              soapHeader.build();

              header.setProcessed();
            }

            if (header.isProcessed()) {
              processedHeaderQNames.add(element.getQName());
            }
          }
        }
        XMLStreamReader reader = ((OMElement) doc.getDocumentElement()).getXMLStreamReader();
        StAXSOAPModelBuilder stAXSOAPModelBuilder = new StAXSOAPModelBuilder(reader, null);
        SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope();

        // Set the processed flag of the processed headers
        SOAPHeader header = envelope.getHeader();
        for (Iterator iter = processedHeaderQNames.iterator(); iter.hasNext(); ) {
          QName name = (QName) iter.next();
          Iterator omKids = header.getChildrenWithName(name);
          if (omKids.hasNext()) {
            ((SOAPHeaderBlock) omKids.next()).setProcessed();
          }
        }

        envelope.build();

        return envelope;

      } catch (FactoryConfigurationError e) {
        throw new WSSecurityException(e.getMessage());
      }
    } else {
      try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XMLUtils.outputDOM(doc.getDocumentElement(), os, true);
        ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());

        StAXSOAPModelBuilder stAXSOAPModelBuilder =
            new StAXSOAPModelBuilder(
                XMLInputFactory.newInstance().createXMLStreamReader(bais), null);
        return stAXSOAPModelBuilder.getSOAPEnvelope();
      } catch (Exception e) {
        throw new WSSecurityException(e.getMessage());
      }
    }
  }