提交 eae7e7bf 编写于 作者: M mullan

6741606: Integrate Apache Santuario

Reviewed-by: vinnie, hawtin
上级 35d4f061
...@@ -2,38 +2,43 @@ ...@@ -2,38 +2,43 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /**
* Copyright 1999-2004 The Apache Software Foundation. * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* http://www.apache.org/licenses/LICENSE-2.0 * with the License. You may obtain a copy of the License at
* *
* Unless required by applicable law or agreed to in writing, software * http://www.apache.org/licenses/LICENSE-2.0
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package com.sun.org.apache.xml.internal.security; package com.sun.org.apache.xml.internal.security;
import java.io.InputStream; import java.io.InputStream;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm; import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver;
import com.sun.org.apache.xml.internal.security.transforms.Transform; import com.sun.org.apache.xml.internal.security.transforms.Transform;
import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
import com.sun.org.apache.xml.internal.security.utils.I18n; import com.sun.org.apache.xml.internal.security.utils.I18n;
//import com.sun.org.apache.xml.internal.security.utils.PRNG;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
...@@ -47,367 +52,317 @@ import org.w3c.dom.Node; ...@@ -47,367 +52,317 @@ import org.w3c.dom.Node;
* the mapping of Canonicalization and Transform algorithms. Initialization is * the mapping of Canonicalization and Transform algorithms. Initialization is
* done by calling {@link Init#init} which should be done in any static block * done by calling {@link Init#init} which should be done in any static block
* of the files of this library. We ensure that this call is only executed once. * of the files of this library. We ensure that this call is only executed once.
*
* @author $Author: mullan $
*/ */
public final class Init { public class Init {
/** {@link java.util.logging} logging facility */ /** The namespace for CONF file **/
static java.util.logging.Logger log = public static final String CONF_NS = "http://www.xmlsecurity.org/NS/#configuration";
java.util.logging.Logger.getLogger(Init.class.getName());
/** Field _initialized */ /** {@link org.apache.commons.logging} logging facility */
private static boolean _alreadyInitialized = false; private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(Init.class.getName());
/** The namespace for CONF file **/
public static final String CONF_NS="http://www.xmlsecurity.org/NS/#configuration";
/**
* Method isInitialized
* @return true if the librairy is already initialized.
*
*/
public static final boolean isInitialized() {
return Init._alreadyInitialized;
}
/**
* Method init
*
*/
public synchronized static void init() {
if (_alreadyInitialized) {
return;
}
long XX_configure_i18n_end=0;
long XX_configure_reg_c14n_start=0;
long XX_configure_reg_c14n_end=0;
long XX_configure_reg_jcemapper_end=0;
long XX_configure_reg_keyInfo_start=0;
long XX_configure_reg_keyResolver_end=0;
long XX_configure_reg_prefixes_start=0;
long XX_configure_reg_resourceresolver_start=0;
long XX_configure_reg_sigalgos_end=0;
long XX_configure_reg_transforms_end=0;
long XX_configure_reg_keyInfo_end=0;
long XX_configure_reg_keyResolver_start=0;
_alreadyInitialized = true;
try {
long XX_init_start = System.currentTimeMillis();
long XX_prng_start = System.currentTimeMillis();
//PRNG.init(new java.security.SecureRandom());
long XX_prng_end = System.currentTimeMillis();
/** Field alreadyInitialized */
private static boolean alreadyInitialized = false;
/**
* Method isInitialized
* @return true if the library is already initialized.
*/
public static synchronized final boolean isInitialized() {
return Init.alreadyInitialized;
}
/**
* Method init
*
*/
public static synchronized void init() {
if (alreadyInitialized) {
return;
}
InputStream is =
AccessController.doPrivileged(
new PrivilegedAction<InputStream>() {
public InputStream run() {
String cfile =
System.getProperty("com.sun.org.apache.xml.internal.security.resource.config");
if (cfile == null) {
return null;
}
return getClass().getResourceAsStream(cfile);
}
});
if (is == null) {
dynamicInit();
} else {
fileInit(is);
}
alreadyInitialized = true;
}
/**
* Dynamically initialise the library by registering the default algorithms/implementations
*/
private static void dynamicInit() {
//
// Load the Resource Bundle - the default is the English resource bundle.
// To load another resource bundle, call I18n.init(...) before calling this
// method.
//
I18n.init("en", "US");
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Registering default algorithms");
}
try {
//
// Bind the default prefixes
//
ElementProxy.registerDefaultPrefixes();
//
// Set the default Transforms
//
Transform.registerDefaultAlgorithms();
//
// Set the default signature algorithms
//
SignatureAlgorithm.registerDefaultAlgorithms();
//
// Set the default JCE algorithms
//
JCEMapper.registerDefaultAlgorithms();
//
// Set the default c14n algorithms
//
Canonicalizer.registerDefaultAlgorithms();
//
// Register the default resolvers
//
ResourceResolver.registerDefaultResolvers();
//
// Register the default key resolvers
//
KeyResolver.registerDefaultResolvers();
} catch (Exception ex) {
log.log(java.util.logging.Level.SEVERE, ex.getMessage(), ex);
ex.printStackTrace();
}
}
/**
* Initialise the library from a configuration file
*/
private static void fileInit(InputStream is) {
try {
/* read library configuration file */ /* read library configuration file */
long XX_parsing_start = System.currentTimeMillis();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
dbf.setNamespaceAware(true); dbf.setNamespaceAware(true);
dbf.setValidating(false); dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder(); DocumentBuilder db = dbf.newDocumentBuilder();
// We don't allow users to override the Apache XML Security
// configuration in the JRE. Users should use the standard security
// provider mechanism instead if implementing their own
// transform or canonicalization algorithms.
// InputStream is = Class.forName("com.sun.org.apache.xml.internal.security.Init").getResourceAsStream("resource/config.xml");
InputStream is = AccessController.doPrivileged(
new PrivilegedAction<InputStream>() {
public InputStream run() {
// String cfile = System.getProperty
// ("com.sun.org.apache.xml.internal.security.resource.config");
return getClass().getResourceAsStream
// (cfile != null ? cfile : "resource/config.xml");
("resource/config.xml");
}
});
Document doc = db.parse(is); Document doc = db.parse(is);
long XX_parsing_end = System.currentTimeMillis(); Node config = doc.getFirstChild();
long XX_configure_i18n_start = 0; for (; config != null; config = config.getNextSibling()) {
{
XX_configure_reg_keyInfo_start = System.currentTimeMillis();
try {
KeyInfo.init();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
XX_configure_reg_keyInfo_end = System.currentTimeMillis();
}
long XX_configure_reg_transforms_start=0;
long XX_configure_reg_jcemapper_start=0;
long XX_configure_reg_sigalgos_start=0;
long XX_configure_reg_resourceresolver_end=0;
long XX_configure_reg_prefixes_end=0;
Node config=doc.getFirstChild();
for (;config!=null;config=config.getNextSibling()) {
if ("Configuration".equals(config.getLocalName())) { if ("Configuration".equals(config.getLocalName())) {
break; break;
} }
} }
for (Node el=config.getFirstChild();el!=null;el=el.getNextSibling()) { if (config == null) {
if (el.getNodeType() != Node.ELEMENT_NODE) { log.log(java.util.logging.Level.SEVERE, "Error in reading configuration file - Configuration element not found");
continue; return;
}
String tag=el.getLocalName();
//
// Commented out: not supported in the JDK. We use the default locale.
//
// if (tag.equals("ResourceBundles")){
// XX_configure_i18n_start = System.currentTimeMillis();
// Element resource=(Element)el;
// /* configure internationalization */
// Attr langAttr = resource.getAttributeNode("defaultLanguageCode");
// Attr countryAttr = resource.getAttributeNode("defaultCountryCode");
// String languageCode = (langAttr == null)
// ? null
// : langAttr.getNodeValue();
// String countryCode = (countryAttr == null)
// ? null
// : countryAttr.getNodeValue();
//
// I18n.init(languageCode, countryCode);
// XX_configure_i18n_end = System.currentTimeMillis();
// }
if (tag.equals("CanonicalizationMethods")){
XX_configure_reg_c14n_start = System.currentTimeMillis();
Canonicalizer.init();
Element[] list=XMLUtils.selectNodes(el.getFirstChild(),CONF_NS,"CanonicalizationMethod");
for (int i = 0; i < list.length; i++) {
String URI = list[i].getAttributeNS(null,
"URI");
String JAVACLASS =
list[i].getAttributeNS(null,
"JAVACLASS");
try {
Class.forName(JAVACLASS);
/* Method methods[] = c.getMethods();
for (int j = 0; j < methods.length; j++) {
Method currMeth = methods[j];
if (currMeth.getDeclaringClass().getName()
.equals(JAVACLASS)) {
log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString());
}
}*/
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + URI + ", "
+ JAVACLASS + ")");
Canonicalizer.register(URI, JAVACLASS);
} catch (ClassNotFoundException e) {
Object exArgs[] = { URI, JAVACLASS };
log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist",
exArgs));
}
}
XX_configure_reg_c14n_end = System.currentTimeMillis();
}
if (tag.equals("TransformAlgorithms")){
XX_configure_reg_transforms_start = System.currentTimeMillis();
Transform.init();
Element[] tranElem = XMLUtils.selectNodes(el.getFirstChild(),CONF_NS,"TransformAlgorithm");
for (int i = 0; i < tranElem.length; i++) {
String URI = tranElem[i].getAttributeNS(null,
"URI");
String JAVACLASS =
tranElem[i].getAttributeNS(null,
"JAVACLASS");
try {
Class.forName(JAVACLASS);
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Transform.register(" + URI + ", " + JAVACLASS + ")");
Transform.register(URI, JAVACLASS);
} catch (ClassNotFoundException e) {
Object exArgs[] = { URI, JAVACLASS };
log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist",
exArgs));
} catch (NoClassDefFoundError ex) {
log.log(java.util.logging.Level.WARNING, "Not able to found dependecies for algorithm, I'm keep working.");
}
}
XX_configure_reg_transforms_end = System.currentTimeMillis();
} }
for (Node el = config.getFirstChild(); el != null; el = el.getNextSibling()) {
if (Node.ELEMENT_NODE != el.getNodeType()) {
continue;
}
String tag = el.getLocalName();
if (tag.equals("ResourceBundles")) {
Element resource = (Element)el;
/* configure internationalization */
Attr langAttr = resource.getAttributeNode("defaultLanguageCode");
Attr countryAttr = resource.getAttributeNode("defaultCountryCode");
String languageCode =
(langAttr == null) ? null : langAttr.getNodeValue();
String countryCode =
(countryAttr == null) ? null : countryAttr.getNodeValue();
I18n.init(languageCode, countryCode);
}
if (tag.equals("CanonicalizationMethods")) {
Element[] list =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod");
for (int i = 0; i < list.length; i++) {
String uri = list[i].getAttributeNS(null, "URI");
String javaClass =
list[i].getAttributeNS(null, "JAVACLASS");
try {
Canonicalizer.register(uri, javaClass);
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + uri + ", " + javaClass + ")");
}
} catch (ClassNotFoundException e) {
Object exArgs[] = { uri, javaClass };
log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist", exArgs));
}
}
}
if ("JCEAlgorithmMappings".equals(tag)){ if (tag.equals("TransformAlgorithms")) {
XX_configure_reg_jcemapper_start = System.currentTimeMillis(); Element[] tranElem =
JCEMapper.init((Element)el); XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "TransformAlgorithm");
XX_configure_reg_jcemapper_end = System.currentTimeMillis();
} for (int i = 0; i < tranElem.length; i++) {
String uri = tranElem[i].getAttributeNS(null, "URI");
String javaClass =
tranElem[i].getAttributeNS(null, "JAVACLASS");
if (tag.equals("SignatureAlgorithms")){ try {
XX_configure_reg_sigalgos_start = System.currentTimeMillis(); Transform.register(uri, javaClass);
SignatureAlgorithm.providerInit(); if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Transform.register(" + uri + ", " + javaClass + ")");
Element[] sigElems = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, }
"SignatureAlgorithm"); } catch (ClassNotFoundException e) {
Object exArgs[] = { uri, javaClass };
for (int i = 0; i < sigElems.length; i++) {
String URI = sigElems[i].getAttributeNS(null, log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist", exArgs));
"URI"); } catch (NoClassDefFoundError ex) {
String JAVACLASS = log.log(java.util.logging.Level.WARNING, "Not able to found dependencies for algorithm, I'll keep working.");
sigElems[i].getAttributeNS(null, }
"JAVACLASS"); }
}
/** $todo$ handle registering */
try {
Class.forName(JAVACLASS);
// Method methods[] = c.getMethods();
// for (int j = 0; j < methods.length; j++) {
// Method currMeth = methods[j];
//
// if (currMeth.getDeclaringClass().getName()
// .equals(JAVACLASS)) {
// log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString());
// }
// }
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + URI + ", " + JAVACLASS + ")");
SignatureAlgorithm.register(URI, JAVACLASS);
} catch (ClassNotFoundException e) {
Object exArgs[] = { URI, JAVACLASS };
log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist",
exArgs));
}
}
XX_configure_reg_sigalgos_end = System.currentTimeMillis();
}
if (tag.equals("ResourceResolvers")){
XX_configure_reg_resourceresolver_start = System.currentTimeMillis();
ResourceResolver.init();
Element[]resolverElem = XMLUtils.selectNodes(el.getFirstChild(),CONF_NS,
"Resolver");
for (int i = 0; i < resolverElem.length; i++) {
String JAVACLASS =
resolverElem[i].getAttributeNS(null,
"JAVACLASS");
String Description =
resolverElem[i].getAttributeNS(null,
"DESCRIPTION");
if ((Description != null) && (Description.length() > 0)) {
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description);
} else {
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes");
}
try {
ResourceResolver.register(JAVACLASS);
} catch (Throwable e) {
log.log(java.util.logging.Level.WARNING, "Cannot register:"+JAVACLASS+" perhaps some needed jars are not installed",e);
}
XX_configure_reg_resourceresolver_end =
System.currentTimeMillis();
}
}
if ("JCEAlgorithmMappings".equals(tag)) {
Node algorithmsNode = ((Element)el).getElementsByTagName("Algorithms").item(0);
if (algorithmsNode != null) {
Element[] algorithms =
XMLUtils.selectNodes(algorithmsNode.getFirstChild(), CONF_NS, "Algorithm");
for (int i = 0; i < algorithms.length; i++) {
Element element = algorithms[i];
String id = element.getAttribute("URI");
JCEMapper.register(id, new JCEMapper.Algorithm(element));
}
}
}
if (tag.equals("SignatureAlgorithms")) {
Element[] sigElems =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "SignatureAlgorithm");
for (int i = 0; i < sigElems.length; i++) {
String uri = sigElems[i].getAttributeNS(null, "URI");
String javaClass =
sigElems[i].getAttributeNS(null, "JAVACLASS");
/** $todo$ handle registering */
if (tag.equals("KeyResolver")){ try {
XX_configure_reg_keyResolver_start =System.currentTimeMillis(); SignatureAlgorithm.register(uri, javaClass);
KeyResolver.init(); if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + uri + ", "
+ javaClass + ")");
}
} catch (ClassNotFoundException e) {
Object exArgs[] = { uri, javaClass };
Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS,"Resolver"); log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist", exArgs));
}
}
}
for (int i = 0; i < resolverElem.length; i++) { if (tag.equals("ResourceResolvers")) {
String JAVACLASS = Element[]resolverElem =
resolverElem[i].getAttributeNS(null, XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
"JAVACLASS");
String Description = for (int i = 0; i < resolverElem.length; i++) {
resolverElem[i].getAttributeNS(null, String javaClass =
"DESCRIPTION"); resolverElem[i].getAttributeNS(null, "JAVACLASS");
String description =
resolverElem[i].getAttributeNS(null, "DESCRIPTION");
if ((description != null) && (description.length() > 0)) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass + ": "
+ description);
}
} else {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass
+ ": For unknown purposes");
}
}
try {
ResourceResolver.register(javaClass);
} catch (Throwable e) {
log.log(java.util.logging.Level.WARNING,
"Cannot register:" + javaClass
+ " perhaps some needed jars are not installed",
e
);
}
}
}
if ((Description != null) && (Description.length() > 0)) { if (tag.equals("KeyResolver")){
if (log.isLoggable(java.util.logging.Level.FINE)) Element[] resolverElem =
log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description); XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
} else { List<String> classNames = new ArrayList<String>(resolverElem.length);
if (log.isLoggable(java.util.logging.Level.FINE)) for (int i = 0; i < resolverElem.length; i++) {
log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes"); String javaClass =
} resolverElem[i].getAttributeNS(null, "JAVACLASS");
String description =
resolverElem[i].getAttributeNS(null, "DESCRIPTION");
if ((description != null) && (description.length() > 0)) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass + ": "
+ description);
}
} else {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass
+ ": For unknown purposes");
}
}
classNames.add(javaClass);
}
KeyResolver.registerClassNames(classNames);
}
KeyResolver.register(JAVACLASS);
}
XX_configure_reg_keyResolver_end = System.currentTimeMillis();
}
if (tag.equals("PrefixMappings")){
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:");
}
if (tag.equals("PrefixMappings")){ Element[] nl =
XX_configure_reg_prefixes_start = System.currentTimeMillis(); XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "PrefixMapping");
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:");
Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS,"PrefixMapping");
for (int i = 0; i < nl.length; i++) {
String namespace = nl[i].getAttributeNS(null,
"namespace");
String prefix = nl[i].getAttributeNS(null,
"prefix");
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace);
com.sun.org.apache.xml.internal.security.utils.ElementProxy
.setDefaultPrefix(namespace, prefix);
}
XX_configure_reg_prefixes_end = System.currentTimeMillis();
}
}
long XX_init_end = System.currentTimeMillis(); for (int i = 0; i < nl.length; i++) {
String namespace = nl[i].getAttributeNS(null, "namespace");
//J- String prefix = nl[i].getAttributeNS(null, "prefix");
if (log.isLoggable(java.util.logging.Level.FINE)) { if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "XX_init " + ((int)(XX_init_end - XX_init_start)) + " ms"); log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace);
log.log(java.util.logging.Level.FINE, " XX_prng " + ((int)(XX_prng_end - XX_prng_start)) + " ms"); }
log.log(java.util.logging.Level.FINE, " XX_parsing " + ((int)(XX_parsing_end - XX_parsing_start)) + " ms"); ElementProxy.setDefaultPrefix(namespace, prefix);
log.log(java.util.logging.Level.FINE, " XX_configure_i18n " + ((int)(XX_configure_i18n_end- XX_configure_i18n_start)) + " ms"); }
log.log(java.util.logging.Level.FINE, " XX_configure_reg_c14n " + ((int)(XX_configure_reg_c14n_end- XX_configure_reg_c14n_start)) + " ms"); }
log.log(java.util.logging.Level.FINE, " XX_configure_reg_jcemapper " + ((int)(XX_configure_reg_jcemapper_end- XX_configure_reg_jcemapper_start)) + " ms");
log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyInfo " + ((int)(XX_configure_reg_keyInfo_end- XX_configure_reg_keyInfo_start)) + " ms");
log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyResolver " + ((int)(XX_configure_reg_keyResolver_end- XX_configure_reg_keyResolver_start)) + " ms");
log.log(java.util.logging.Level.FINE, " XX_configure_reg_prefixes " + ((int)(XX_configure_reg_prefixes_end- XX_configure_reg_prefixes_start)) + " ms");
log.log(java.util.logging.Level.FINE, " XX_configure_reg_resourceresolver " + ((int)(XX_configure_reg_resourceresolver_end- XX_configure_reg_resourceresolver_start)) + " ms");
log.log(java.util.logging.Level.FINE, " XX_configure_reg_sigalgos " + ((int)(XX_configure_reg_sigalgos_end- XX_configure_reg_sigalgos_start)) + " ms");
log.log(java.util.logging.Level.FINE, " XX_configure_reg_transforms " + ((int)(XX_configure_reg_transforms_end- XX_configure_reg_transforms_start)) + " ms");
} }
} catch (Exception e) { } catch (Exception e) {
log.log(java.util.logging.Level.SEVERE, "Bad: ", e); log.log(java.util.logging.Level.SEVERE, "Bad: ", e);
e.printStackTrace(); e.printStackTrace();
} }
}
}
} }
...@@ -2,167 +2,316 @@ ...@@ -2,167 +2,316 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /**
* Copyright 1999-2004 The Apache Software Foundation. * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* http://www.apache.org/licenses/LICENSE-2.0 * with the License. You may obtain a copy of the License at
* *
* Unless required by applicable law or agreed to in writing, software * http://www.apache.org/licenses/LICENSE-2.0
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package com.sun.org.apache.xml.internal.security.algorithms; package com.sun.org.apache.xml.internal.security.algorithms;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
import com.sun.org.apache.xml.internal.security.Init; import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element; import org.w3c.dom.Element;
/** /**
* This class maps algorithm identifier URIs to JAVA JCE class names. * This class maps algorithm identifier URIs to JAVA JCE class names.
*
* @author $Author: mullan $
*/ */
public class JCEMapper { public class JCEMapper {
/** {@link java.util.logging} logging facility */ /** {@link org.apache.commons.logging} logging facility */
static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(JCEMapper.class.getName()); java.util.logging.Logger.getLogger(JCEMapper.class.getName());
private static Map<String, Algorithm> algorithmsMap =
new ConcurrentHashMap<String, Algorithm>();
private static String providerName = null;
/**
* Method register
*
* @param id
* @param algorithm
*/
public static void register(String id, Algorithm algorithm) {
algorithmsMap.put(id, algorithm);
}
/**
* This method registers the default algorithms.
*/
public static void registerDefaultAlgorithms() {
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5,
new Algorithm("", "MD5", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160,
new Algorithm("", "RIPEMD160", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1,
new Algorithm("", "SHA-1", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256,
new Algorithm("", "SHA-256", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA384,
new Algorithm("", "SHA-384", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512,
new Algorithm("", "SHA-512", "MessageDigest")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_DSA,
new Algorithm("", "SHA1withDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
new Algorithm("", "MD5withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160,
new Algorithm("", "RIPEMD160withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1,
new Algorithm("", "SHA1withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256,
new Algorithm("", "SHA256withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384,
new Algorithm("", "SHA384withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
new Algorithm("", "SHA512withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1,
new Algorithm("", "SHA1withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5,
new Algorithm("", "HmacMD5", "Mac")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160,
new Algorithm("", "HMACRIPEMD160", "Mac")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
new Algorithm("", "HmacSHA1", "Mac")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA256,
new Algorithm("", "HmacSHA256", "Mac")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA384,
new Algorithm("", "HmacSHA384", "Mac")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA512,
new Algorithm("", "HmacSHA512", "Mac")
);
algorithmsMap.put(
XMLCipher.TRIPLEDES,
new Algorithm("DESede", "DESede/CBC/ISO10126Padding", "BlockEncryption", 192)
);
algorithmsMap.put(
XMLCipher.AES_128,
new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 128)
);
algorithmsMap.put(
XMLCipher.AES_192,
new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 192)
);
algorithmsMap.put(
XMLCipher.AES_256,
new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 256)
);
algorithmsMap.put(
XMLCipher.RSA_v1dot5,
new Algorithm("RSA", "RSA/ECB/PKCS1Padding", "KeyTransport")
);
algorithmsMap.put(
XMLCipher.RSA_OAEP,
new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
);
algorithmsMap.put(
XMLCipher.DIFFIE_HELLMAN,
new Algorithm("", "", "KeyAgreement")
);
algorithmsMap.put(
XMLCipher.TRIPLEDES_KeyWrap,
new Algorithm("DESede", "DESedeWrap", "SymmetricKeyWrap", 192)
);
algorithmsMap.put(
XMLCipher.AES_128_KeyWrap,
new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 128)
);
algorithmsMap.put(
XMLCipher.AES_192_KeyWrap,
new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 192)
);
algorithmsMap.put(
XMLCipher.AES_256_KeyWrap,
new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 256)
);
}
/**
* Method translateURItoJCEID
*
* @param algorithmURI
* @return the JCE standard name corresponding to the given URI
*/
public static String translateURItoJCEID(String algorithmURI) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
}
Algorithm algorithm = algorithmsMap.get(algorithmURI);
if (algorithm != null) {
return algorithm.jceName;
}
return null;
}
/**
* Method getAlgorithmClassFromURI
* @param algorithmURI
* @return the class name that implements this algorithm
*/
public static String getAlgorithmClassFromURI(String algorithmURI) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
}
Algorithm algorithm = algorithmsMap.get(algorithmURI);
if (algorithm != null) {
return algorithm.algorithmClass;
}
return null;
}
/**
* Returns the keylength in bits for a particular algorithm.
*
* @param algorithmURI
* @return The length of the key used in the algorithm
*/
public static int getKeyLengthFromURI(String algorithmURI) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
}
Algorithm algorithm = algorithmsMap.get(algorithmURI);
if (algorithm != null) {
return algorithm.keyLength;
}
return 0;
}
/**
* Method getJCEKeyAlgorithmFromURI
*
* @param algorithmURI
* @return The KeyAlgorithm for the given URI.
*/
public static String getJCEKeyAlgorithmFromURI(String algorithmURI) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
}
Algorithm algorithm = algorithmsMap.get(algorithmURI);
if (algorithm != null) {
return algorithm.requiredKey;
}
return null;
}
/**
* Gets the default Provider for obtaining the security algorithms
* @return the default providerId.
*/
public static String getProviderId() {
return providerName;
}
/**
* Sets the default Provider for obtaining the security algorithms
* @param provider the default providerId.
*/
public static void setProviderId(String provider) {
providerName = provider;
}
/**
* Represents the Algorithm xml element
*/
public static class Algorithm {
final String requiredKey;
final String jceName;
final String algorithmClass;
final int keyLength;
private static Map<String, String> uriToJCEName;
private static Map<String, Algorithm> algorithmsMap;
private static String providerName = null;
/**
* Method init
*
* @param mappingElement
* @throws Exception
*/
public static void init(Element mappingElement) throws Exception {
loadAlgorithms((Element)mappingElement.getElementsByTagName("Algorithms").item(0));
}
static void loadAlgorithms( Element algorithmsEl) {
Element[] algorithms = XMLUtils.selectNodes(algorithmsEl.getFirstChild(),Init.CONF_NS,"Algorithm");
uriToJCEName = new HashMap<String, String>( algorithms.length * 2);
algorithmsMap = new HashMap<String, Algorithm>( algorithms.length * 2);
for (int i = 0 ;i < algorithms.length ;i ++) {
Element el = algorithms[i];
String id = el.getAttribute("URI");
String jceName = el.getAttribute("JCEName");
uriToJCEName.put(id, jceName);
algorithmsMap.put(id, new Algorithm(el));
}
}
static Algorithm getAlgorithmMapping(String algoURI) {
return algorithmsMap.get(algoURI);
}
/**
* Method translateURItoJCEID
*
* @param AlgorithmURI
* @return the JCE standard name corresponding to the given URI
*
*/
public static String translateURItoJCEID(String AlgorithmURI) {
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
String jceName = uriToJCEName.get(AlgorithmURI);
return jceName;
}
/**
* Method getAlgorithmClassFromURI
* NOTE(Raul Benito) It seems a buggy function the loop doesn't do
* anything??
* @param AlgorithmURI
* @return the class name that implements this algorithm
*
*/
public static String getAlgorithmClassFromURI(String AlgorithmURI) {
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
return (algorithmsMap.get(AlgorithmURI)).algorithmClass;
}
/**
* Returns the keylength in bit for a particular algorithm.
*
* @param AlgorithmURI
* @return The length of the key used in the alogrithm
*/
public static int getKeyLengthFromURI(String AlgorithmURI) {
return Integer.parseInt((algorithmsMap.get(AlgorithmURI)).keyLength);
}
/**
* Method getJCEKeyAlgorithmFromURI
*
* @param AlgorithmURI
* @return The KeyAlgorithm for the given URI.
*
*/
public static String getJCEKeyAlgorithmFromURI(String AlgorithmURI) {
return (algorithmsMap.get(AlgorithmURI)).requiredKey;
}
/**
* Gets the default Provider for obtaining the security algorithms
* @return the default providerId.
*/
public static String getProviderId() {
return providerName;
}
/**
* Sets the default Provider for obtaining the security algorithms
* @param provider the default providerId.
*/
public static void setProviderId(String provider) {
providerName=provider;
}
/**
* Represents the Algorithm xml element
*/
public static class Algorithm {
String algorithmClass;
String keyLength;
String requiredKey;
/** /**
* Gets data from element * Gets data from element
* @param el * @param el
*/ */
public Algorithm(Element el) { public Algorithm(Element el) {
algorithmClass=el.getAttribute("AlgorithmClass"); requiredKey = el.getAttribute("RequiredKey");
keyLength=el.getAttribute("KeyLength"); jceName = el.getAttribute("JCEName");
requiredKey=el.getAttribute("RequiredKey"); algorithmClass = el.getAttribute("AlgorithmClass");
if (el.hasAttribute("KeyLength")) {
keyLength = Integer.parseInt(el.getAttribute("KeyLength"));
} else {
keyLength = 0;
}
} }
}
public Algorithm(String requiredKey, String jceName) {
this(requiredKey, jceName, null, 0);
}
public Algorithm(String requiredKey, String jceName, String algorithmClass) {
this(requiredKey, jceName, algorithmClass, 0);
}
public Algorithm(String requiredKey, String jceName, int keyLength) {
this(requiredKey, jceName, null, keyLength);
}
public Algorithm(String requiredKey, String jceName, String algorithmClass, int keyLength) {
this.requiredKey = requiredKey;
this.jceName = jceName;
this.algorithmClass = algorithmClass;
this.keyLength = keyLength;
}
}
} }
...@@ -2,460 +2,446 @@ ...@@ -2,460 +2,446 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /**
* Copyright 1999-2004 The Apache Software Foundation. * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* http://www.apache.org/licenses/LICENSE-2.0 * with the License. You may obtain a copy of the License at
* *
* Unless required by applicable law or agreed to in writing, software * http://www.apache.org/licenses/LICENSE-2.0
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package com.sun.org.apache.xml.internal.security.algorithms; package com.sun.org.apache.xml.internal.security.algorithms;
import java.security.Key; import java.security.Key;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac; import com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureDSA;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA;
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException; import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.ClassLoaderUtils;
import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.Constants;
import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
/** /**
* Allows selection of digital signature's algorithm, private keys, other security parameters, and algorithm's ID. * Allows selection of digital signature's algorithm, private keys, other
* security parameters, and algorithm's ID.
* *
* @author Christian Geuer-Pollmann * @author Christian Geuer-Pollmann
*/ */
public class SignatureAlgorithm extends Algorithm { public class SignatureAlgorithm extends Algorithm {
/** {@link java.util.logging} logging facility */ /** {@link org.apache.commons.logging} logging facility */
static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(SignatureAlgorithm.class.getName()); java.util.logging.Logger.getLogger(SignatureAlgorithm.class.getName());
/** Field _alreadyInitialized */ /** All available algorithm classes are registered here */
static boolean _alreadyInitialized = false; private static Map<String, Class<? extends SignatureAlgorithmSpi>> algorithmHash =
new ConcurrentHashMap<String, Class<? extends SignatureAlgorithmSpi>>();
/** All available algorithm classes are registered here */
static Map<String, Class<? extends SignatureAlgorithmSpi>> _algorithmHash = null; /** Field signatureAlgorithm */
private final SignatureAlgorithmSpi signatureAlgorithm;
static ThreadLocal<Map<String, SignatureAlgorithmSpi>> instancesSigning=new ThreadLocal<Map<String, SignatureAlgorithmSpi>>() {
protected Map<String, SignatureAlgorithmSpi> initialValue() { private final String algorithmURI;
return new HashMap<String, SignatureAlgorithmSpi>();
}; /**
}; * Constructor SignatureAlgorithm
*
static ThreadLocal<Map<String, SignatureAlgorithmSpi>> instancesVerify=new ThreadLocal<Map<String, SignatureAlgorithmSpi>>() { * @param doc
protected Map<String, SignatureAlgorithmSpi> initialValue() { * @param algorithmURI
return new HashMap<String, SignatureAlgorithmSpi>(); * @throws XMLSecurityException
}; */
}; public SignatureAlgorithm(Document doc, String algorithmURI) throws XMLSecurityException {
super(doc, algorithmURI);
static ThreadLocal<Map<String, Key>> keysSigning=new ThreadLocal<Map<String, Key>>() { this.algorithmURI = algorithmURI;
protected Map<String, Key> initialValue() {
return new HashMap<String, Key>(); signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
}; signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
}; }
static ThreadLocal<Map<String, Key>> keysVerify=new ThreadLocal<Map<String, Key>>() {
protected Map<String, Key> initialValue() { /**
return new HashMap<String, Key>(); * Constructor SignatureAlgorithm
}; *
}; * @param doc
// boolean isForSigning=false; * @param algorithmURI
* @param hmacOutputLength
/** Field _signatureAlgorithm */ * @throws XMLSecurityException
protected SignatureAlgorithmSpi _signatureAlgorithm = null; */
public SignatureAlgorithm(
private String algorithmURI; Document doc, String algorithmURI, int hmacOutputLength
) throws XMLSecurityException {
/** super(doc, algorithmURI);
* Constructor SignatureAlgorithm this.algorithmURI = algorithmURI;
*
* @param doc signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
* @param algorithmURI signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
* @throws XMLSecurityException
*/ signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength);
public SignatureAlgorithm(Document doc, String algorithmURI) ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(_constructionElement);
throws XMLSecurityException { }
super(doc, algorithmURI);
this.algorithmURI = algorithmURI; /**
} * Constructor SignatureAlgorithm
*
* @param element
private void initializeAlgorithm(boolean isForSigning) throws XMLSignatureException { * @param baseURI
if (_signatureAlgorithm!=null) { * @throws XMLSecurityException
return; */
} public SignatureAlgorithm(Element element, String baseURI) throws XMLSecurityException {
_signatureAlgorithm=isForSigning ? getInstanceForSigning(algorithmURI) : getInstanceForVerify(algorithmURI); this(element, baseURI, false);
this._signatureAlgorithm }
.engineGetContextFromElement(this._constructionElement);
} /**
private static SignatureAlgorithmSpi getInstanceForSigning(String algorithmURI) throws XMLSignatureException { * Constructor SignatureAlgorithm
SignatureAlgorithmSpi result= instancesSigning.get().get(algorithmURI); *
if (result!=null) { * @param element
result.reset(); * @param baseURI
return result; * @param secureValidation
} * @throws XMLSecurityException
result=buildSigner(algorithmURI, result); */
instancesSigning.get().put(algorithmURI,result); public SignatureAlgorithm(
return result; Element element, String baseURI, boolean secureValidation
} ) throws XMLSecurityException {
private static SignatureAlgorithmSpi getInstanceForVerify(String algorithmURI) throws XMLSignatureException { super(element, baseURI);
SignatureAlgorithmSpi result= instancesVerify.get().get(algorithmURI); algorithmURI = this.getURI();
if (result!=null) {
result.reset(); Attr attr = element.getAttributeNodeNS(null, "Id");
return result; if (attr != null) {
} element.setIdAttributeNode(attr, true);
result=buildSigner(algorithmURI, result); }
instancesVerify.get().put(algorithmURI,result);
return result; if (secureValidation && (XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(algorithmURI)
} || XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(algorithmURI))) {
Object exArgs[] = { algorithmURI };
private static SignatureAlgorithmSpi buildSigner(String algorithmURI, SignatureAlgorithmSpi result) throws XMLSignatureException {
throw new XMLSecurityException("signature.signatureAlgorithm", exArgs);
}
signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
}
/**
* Get a SignatureAlgorithmSpi object corresponding to the algorithmURI argument
*/
private static SignatureAlgorithmSpi getSignatureAlgorithmSpi(String algorithmURI)
throws XMLSignatureException {
try { try {
Class<? extends SignatureAlgorithmSpi> implementingClass = Class<? extends SignatureAlgorithmSpi> implementingClass =
SignatureAlgorithm.getImplementingClass(algorithmURI); algorithmHash.get(algorithmURI);
if (log.isLoggable(java.util.logging.Level.FINE)) if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \"" log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
+ implementingClass + "\""); + implementingClass + "\"");
result= implementingClass.newInstance(); }
return result; return implementingClass.newInstance();
} catch (IllegalAccessException ex) { } catch (IllegalAccessException ex) {
Object exArgs[] = { algorithmURI, ex.getMessage() }; Object exArgs[] = { algorithmURI, ex.getMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, } catch (InstantiationException ex) {
ex); Object exArgs[] = { algorithmURI, ex.getMessage() };
} catch (InstantiationException ex) { throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
Object exArgs[] = { algorithmURI, ex.getMessage() }; } catch (NullPointerException ex) {
Object exArgs[] = { algorithmURI, ex.getMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
ex); }
} catch (NullPointerException ex) { }
Object exArgs[] = { algorithmURI, ex.getMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, /**
ex); * Proxy method for {@link java.security.Signature#sign()}
} * which is executed on the internal {@link java.security.Signature} object.
} *
* @return the result of the {@link java.security.Signature#sign()} method
* @throws XMLSignatureException
*/
public byte[] sign() throws XMLSignatureException {
return signatureAlgorithm.engineSign();
}
/**
* Proxy method for {@link java.security.Signature#getAlgorithm}
* which is executed on the internal {@link java.security.Signature} object.
*
* @return the result of the {@link java.security.Signature#getAlgorithm} method
*/
public String getJCEAlgorithmString() {
return signatureAlgorithm.engineGetJCEAlgorithmString();
}
/**
* Method getJCEProviderName
*
* @return The Provider of this Signature Algorithm
*/
public String getJCEProviderName() {
return signatureAlgorithm.engineGetJCEProviderName();
}
/**
* Proxy method for {@link java.security.Signature#update(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param input
* @throws XMLSignatureException
*/
public void update(byte[] input) throws XMLSignatureException {
signatureAlgorithm.engineUpdate(input);
}
/**
* Proxy method for {@link java.security.Signature#update(byte)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param input
* @throws XMLSignatureException
*/
public void update(byte input) throws XMLSignatureException {
signatureAlgorithm.engineUpdate(input);
}
/**
* Proxy method for {@link java.security.Signature#update(byte[], int, int)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param buf
* @param offset
* @param len
* @throws XMLSignatureException
*/
public void update(byte buf[], int offset, int len) throws XMLSignatureException {
signatureAlgorithm.engineUpdate(buf, offset, len);
}
/**
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signingKey
* @throws XMLSignatureException
*/
public void initSign(Key signingKey) throws XMLSignatureException {
signatureAlgorithm.engineInitSign(signingKey);
}
/**
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey,
* java.security.SecureRandom)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signingKey
* @param secureRandom
* @throws XMLSignatureException
*/
public void initSign(Key signingKey, SecureRandom secureRandom) throws XMLSignatureException {
signatureAlgorithm.engineInitSign(signingKey, secureRandom);
}
/**
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signingKey
* @param algorithmParameterSpec
* @throws XMLSignatureException
*/
public void initSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
) throws XMLSignatureException {
signatureAlgorithm.engineInitSign(signingKey, algorithmParameterSpec);
}
/**
* Proxy method for {@link java.security.Signature#setParameter(
* java.security.spec.AlgorithmParameterSpec)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param params
* @throws XMLSignatureException
*/
public void setParameter(AlgorithmParameterSpec params) throws XMLSignatureException {
signatureAlgorithm.engineSetParameter(params);
}
/**
* Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param verificationKey
* @throws XMLSignatureException
*/
public void initVerify(Key verificationKey) throws XMLSignatureException {
signatureAlgorithm.engineInitVerify(verificationKey);
}
/**
* Proxy method for {@link java.security.Signature#verify(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signature
* @return true if if the signature is valid.
*
* @throws XMLSignatureException
*/
public boolean verify(byte[] signature) throws XMLSignatureException {
return signatureAlgorithm.engineVerify(signature);
}
/**
* Returns the URI representation of Transformation algorithm
*
* @return the URI representation of Transformation algorithm
*/
public final String getURI() {
return _constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
}
/**
* Registers implementing class of the Transform algorithm with algorithmURI
*
* @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
* @param implementingClass <code>implementingClass</code> the implementing class of
* {@link SignatureAlgorithmSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
* @throws XMLSignatureException
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
XMLSignatureException {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
}
/** // are we already registered?
* Constructor SignatureAlgorithm Class<? extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI);
* if (registeredClass != null) {
* @param doc Object exArgs[] = { algorithmURI, registeredClass };
* @param algorithmURI throw new AlgorithmAlreadyRegisteredException(
* @param HMACOutputLength "algorithm.alreadyRegistered", exArgs
* @throws XMLSecurityException );
*/
public SignatureAlgorithm(
Document doc, String algorithmURI, int HMACOutputLength)
throws XMLSecurityException {
this(doc, algorithmURI);
this.algorithmURI=algorithmURI;
initializeAlgorithm(true);
this._signatureAlgorithm.engineSetHMACOutputLength(HMACOutputLength);
((IntegrityHmac)this._signatureAlgorithm)
.engineAddContextToElement(this._constructionElement);
}
/**
* Constructor SignatureAlgorithm
*
* @param element
* @param BaseURI
* @throws XMLSecurityException
*/
public SignatureAlgorithm(Element element, String BaseURI)
throws XMLSecurityException {
super(element, BaseURI);
algorithmURI = this.getURI();
}
/**
* Proxy method for {@link java.security.Signature#sign()}
* which is executed on the internal {@link java.security.Signature} object.
*
* @return the result of the {@link java.security.Signature#sign()} method
* @throws XMLSignatureException
*/
public byte[] sign() throws XMLSignatureException {
return this._signatureAlgorithm.engineSign();
}
/**
* Proxy method for {@link java.security.Signature#getAlgorithm}
* which is executed on the internal {@link java.security.Signature} object.
*
* @return the result of the {@link java.security.Signature#getAlgorithm} method
*/
public String getJCEAlgorithmString() {
try {
return getInstanceForVerify(algorithmURI).engineGetJCEAlgorithmString();
} catch (XMLSignatureException e) {
//Ignore.
return null;
} }
} try {
Class<? extends SignatureAlgorithmSpi> clazz =
/** (Class<? extends SignatureAlgorithmSpi>)
* Method getJCEProviderName ClassLoaderUtils.loadClass(implementingClass, SignatureAlgorithm.class);
* algorithmHash.put(algorithmURI, clazz);
* @return The Provider of this Signature Alogrithm } catch (NullPointerException ex) {
*/ Object exArgs[] = { algorithmURI, ex.getMessage() };
public String getJCEProviderName() { throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
try { }
return getInstanceForVerify(algorithmURI).engineGetJCEProviderName(); }
} catch (XMLSignatureException e) {
return null; /**
* Registers implementing class of the Transform algorithm with algorithmURI
*
* @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
* @param implementingClass <code>implementingClass</code> the implementing class of
* {@link SignatureAlgorithmSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
* @throws XMLSignatureException
*/
public static void register(String algorithmURI, Class<? extends SignatureAlgorithmSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
XMLSignatureException {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
}
// are we already registered?
Class<? extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI);
if (registeredClass != null) {
Object exArgs[] = { algorithmURI, registeredClass };
throw new AlgorithmAlreadyRegisteredException(
"algorithm.alreadyRegistered", exArgs
);
} }
} algorithmHash.put(algorithmURI, implementingClass);
}
/**
* Proxy method for {@link java.security.Signature#update(byte[])} /**
* which is executed on the internal {@link java.security.Signature} object. * This method registers the default algorithms.
* */
* @param input public static void registerDefaultAlgorithms() {
* @throws XMLSignatureException algorithmHash.put(
*/ XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class
public void update(byte[] input) throws XMLSignatureException { );
this._signatureAlgorithm.engineUpdate(input); algorithmHash.put(
} XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class
);
/** algorithmHash.put(
* Proxy method for {@link java.security.Signature#update(byte)} XMLSignature.ALGO_ID_MAC_HMAC_SHA1, IntegrityHmac.IntegrityHmacSHA1.class
* which is executed on the internal {@link java.security.Signature} object. );
* algorithmHash.put(
* @param input XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
* @throws XMLSignatureException SignatureBaseRSA.SignatureRSAMD5.class
*/ );
public void update(byte input) throws XMLSignatureException { algorithmHash.put(
this._signatureAlgorithm.engineUpdate(input); XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160,
} SignatureBaseRSA.SignatureRSARIPEMD160.class
);
/** algorithmHash.put(
* Proxy method for {@link java.security.Signature#update(byte[], int, int)} XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256, SignatureBaseRSA.SignatureRSASHA256.class
* which is executed on the internal {@link java.security.Signature} object. );
* algorithmHash.put(
* @param buf XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384, SignatureBaseRSA.SignatureRSASHA384.class
* @param offset );
* @param len algorithmHash.put(
* @throws XMLSignatureException XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512, SignatureBaseRSA.SignatureRSASHA512.class
*/ );
public void update(byte buf[], int offset, int len) algorithmHash.put(
throws XMLSignatureException { XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class
this._signatureAlgorithm.engineUpdate(buf, offset, len); );
} algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class
/** );
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)} algorithmHash.put(
* which is executed on the internal {@link java.security.Signature} object. XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160, IntegrityHmac.IntegrityHmacRIPEMD160.class
* );
* @param signingKey algorithmHash.put(
* @throws XMLSignatureException XMLSignature.ALGO_ID_MAC_HMAC_SHA256, IntegrityHmac.IntegrityHmacSHA256.class
*/ );
public void initSign(Key signingKey) throws XMLSignatureException { algorithmHash.put(
initializeAlgorithm(true); XMLSignature.ALGO_ID_MAC_HMAC_SHA384, IntegrityHmac.IntegrityHmacSHA384.class
Map<String, Key> map=keysSigning.get(); );
if (map.get(this.algorithmURI)==signingKey) { algorithmHash.put(
return; XMLSignature.ALGO_ID_MAC_HMAC_SHA512, IntegrityHmac.IntegrityHmacSHA512.class
} );
map.put(this.algorithmURI,signingKey); }
this._signatureAlgorithm.engineInitSign(signingKey);
} /**
* Method getBaseNamespace
/** *
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, java.security.SecureRandom)} * @return URI of this element
* which is executed on the internal {@link java.security.Signature} object. */
* public String getBaseNamespace() {
* @param signingKey return Constants.SignatureSpecNS;
* @param secureRandom }
* @throws XMLSignatureException
*/ /**
public void initSign(Key signingKey, SecureRandom secureRandom) * Method getBaseLocalName
throws XMLSignatureException { *
initializeAlgorithm(true); * @return Local name
this._signatureAlgorithm.engineInitSign(signingKey, secureRandom); */
} public String getBaseLocalName() {
return Constants._TAG_SIGNATUREMETHOD;
/** }
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signingKey
* @param algorithmParameterSpec
* @throws XMLSignatureException
*/
public void initSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
throws XMLSignatureException {
initializeAlgorithm(true);
this._signatureAlgorithm.engineInitSign(signingKey,
algorithmParameterSpec);
}
/**
* Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param params
* @throws XMLSignatureException
*/
public void setParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
this._signatureAlgorithm.engineSetParameter(params);
}
/**
* Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param verificationKey
* @throws XMLSignatureException
*/
public void initVerify(Key verificationKey) throws XMLSignatureException {
initializeAlgorithm(false);
Map<String, Key> map=keysVerify.get();
if (map.get(this.algorithmURI)==verificationKey) {
return;
}
map.put(this.algorithmURI,verificationKey);
this._signatureAlgorithm.engineInitVerify(verificationKey);
}
/**
* Proxy method for {@link java.security.Signature#verify(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signature
* @return true if if the signature is valid.
*
* @throws XMLSignatureException
*/
public boolean verify(byte[] signature) throws XMLSignatureException {
return this._signatureAlgorithm.engineVerify(signature);
}
/**
* Returns the URI representation of Transformation algorithm
*
* @return the URI representation of Transformation algorithm
*/
public final String getURI() {
return this._constructionElement.getAttributeNS(null,
Constants._ATT_ALGORITHM);
}
/**
* Initalizes for this {@link com.sun.org.apache.xml.internal.security.transforms.Transform}
*
*/
public static void providerInit() {
if (SignatureAlgorithm.log == null) {
SignatureAlgorithm.log =
java.util.logging.Logger
.getLogger(SignatureAlgorithm.class.getName());
}
log.log(java.util.logging.Level.FINE, "Init() called");
if (!SignatureAlgorithm._alreadyInitialized) {
SignatureAlgorithm._algorithmHash = new HashMap<String, Class<? extends SignatureAlgorithmSpi>>(10);
SignatureAlgorithm._alreadyInitialized = true;
}
}
/**
* Registers implementing class of the Transform algorithm with algorithmURI
*
* @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
* @param implementingClass <code>implementingClass</code> the implementing class of {@link SignatureAlgorithmSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
* @throws XMLSignatureException
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException,XMLSignatureException {
{
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
// are we already registered?
Class<? extends SignatureAlgorithmSpi> registeredClassClass =
SignatureAlgorithm.getImplementingClass(algorithmURI);
if (registeredClassClass!=null) {
String registeredClass = registeredClassClass.getName();
if ((registeredClass != null) && (registeredClass.length() != 0)) {
Object exArgs[] = { algorithmURI, registeredClass };
throw new AlgorithmAlreadyRegisteredException(
"algorithm.alreadyRegistered", exArgs);
}
}
try {
SignatureAlgorithm._algorithmHash.put(algorithmURI, (Class <? extends SignatureAlgorithmSpi>)Class.forName(implementingClass));
} catch (ClassNotFoundException ex) {
Object exArgs[] = { algorithmURI, ex.getMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
ex);
} catch (NullPointerException ex) {
Object exArgs[] = { algorithmURI, ex.getMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
ex);
}
}
}
/**
* Method getImplementingClass
*
* @param URI
* @return the class that implements the URI
*/
private static Class<? extends SignatureAlgorithmSpi> getImplementingClass(String URI) {
if (SignatureAlgorithm._algorithmHash == null) {
return null;
}
return SignatureAlgorithm._algorithmHash.get(URI);
}
/**
* Method getBaseNamespace
*
* @return URI of this element
*/
public String getBaseNamespace() {
return Constants.SignatureSpecNS;
}
/**
* Method getBaseLocalName
*
* @return Local name
*/
public String getBaseLocalName() {
return Constants._TAG_SIGNATUREMETHOD;
}
} }
...@@ -2,34 +2,43 @@ ...@@ -2,34 +2,43 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /**
* Copyright 1999-2008 The Apache Software Foundation. * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* http://www.apache.org/licenses/LICENSE-2.0 * with the License. You may obtain a copy of the License at
* *
* Unless required by applicable law or agreed to in writing, software * http://www.apache.org/licenses/LICENSE-2.0
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n; package com.sun.org.apache.xml.internal.security.c14n;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_WithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclOmitComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclWithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments;
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException; import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -46,7 +55,7 @@ public class Canonicalizer { ...@@ -46,7 +55,7 @@ public class Canonicalizer {
public static final String ENCODING = "UTF8"; public static final String ENCODING = "UTF8";
/** /**
* XPath Expresion for selecting every node and continuous comments joined * XPath Expression for selecting every node and continuous comments joined
* in only one node * in only one node
*/ */
public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE = public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE =
...@@ -83,22 +92,10 @@ public class Canonicalizer { ...@@ -83,22 +92,10 @@ public class Canonicalizer {
public static final String ALGO_ID_C14N11_WITH_COMMENTS = public static final String ALGO_ID_C14N11_WITH_COMMENTS =
ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments"; ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments";
static boolean _alreadyInitialized = false; private static Map<String, Class<? extends CanonicalizerSpi>> canonicalizerHash =
static Map<String,Class<? extends CanonicalizerSpi>> _canonicalizerHash = null; new ConcurrentHashMap<String, Class<? extends CanonicalizerSpi>>();
protected CanonicalizerSpi canonicalizerSpi = null;
/**
* Method init
*
*/
public static void init() {
if (!Canonicalizer._alreadyInitialized) { private final CanonicalizerSpi canonicalizerSpi;
Canonicalizer._canonicalizerHash = new HashMap<String, Class<? extends CanonicalizerSpi>>(10);
Canonicalizer._alreadyInitialized = true;
}
}
/** /**
* Constructor Canonicalizer * Constructor Canonicalizer
...@@ -106,21 +103,18 @@ public class Canonicalizer { ...@@ -106,21 +103,18 @@ public class Canonicalizer {
* @param algorithmURI * @param algorithmURI
* @throws InvalidCanonicalizerException * @throws InvalidCanonicalizerException
*/ */
private Canonicalizer(String algorithmURI) private Canonicalizer(String algorithmURI) throws InvalidCanonicalizerException {
throws InvalidCanonicalizerException {
try { try {
Class<? extends CanonicalizerSpi> implementingClass = Class<? extends CanonicalizerSpi> implementingClass =
getImplementingClass(algorithmURI); canonicalizerHash.get(algorithmURI);
this.canonicalizerSpi = canonicalizerSpi = implementingClass.newInstance();
implementingClass.newInstance(); canonicalizerSpi.reset = true;
this.canonicalizerSpi.reset=true;
} catch (Exception e) { } catch (Exception e) {
Object exArgs[] = { algorithmURI }; Object exArgs[] = { algorithmURI };
throw new InvalidCanonicalizerException( throw new InvalidCanonicalizerException(
"signature.Canonicalizer.UnknownCanonicalizer", exArgs); "signature.Canonicalizer.UnknownCanonicalizer", exArgs, e
);
} }
} }
...@@ -128,15 +122,12 @@ public class Canonicalizer { ...@@ -128,15 +122,12 @@ public class Canonicalizer {
* Method getInstance * Method getInstance
* *
* @param algorithmURI * @param algorithmURI
* @return a Conicicalizer instance ready for the job * @return a Canonicalizer instance ready for the job
* @throws InvalidCanonicalizerException * @throws InvalidCanonicalizerException
*/ */
public static final Canonicalizer getInstance(String algorithmURI) public static final Canonicalizer getInstance(String algorithmURI)
throws InvalidCanonicalizerException { throws InvalidCanonicalizerException {
return new Canonicalizer(algorithmURI);
Canonicalizer c14nizer = new Canonicalizer(algorithmURI);
return c14nizer;
} }
/** /**
...@@ -148,23 +139,69 @@ public class Canonicalizer { ...@@ -148,23 +139,69 @@ public class Canonicalizer {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass) public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException { throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
// check whether URI is already registered // check whether URI is already registered
Class<? extends CanonicalizerSpi> registeredClass = getImplementingClass(algorithmURI); Class<? extends CanonicalizerSpi> registeredClass =
canonicalizerHash.get(algorithmURI);
if (registeredClass != null) { if (registeredClass != null) {
Object exArgs[] = { algorithmURI, registeredClass }; Object exArgs[] = { algorithmURI, registeredClass };
throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
throw new AlgorithmAlreadyRegisteredException(
"algorithm.alreadyRegistered", exArgs);
} }
try { canonicalizerHash.put(
_canonicalizerHash.put(algorithmURI, (Class<? extends CanonicalizerSpi>) Class.forName(implementingClass)); algorithmURI, (Class<? extends CanonicalizerSpi>)Class.forName(implementingClass)
} catch (ClassNotFoundException e) { );
throw new RuntimeException("c14n class not found"); }
/**
* Method register
*
* @param algorithmURI
* @param implementingClass
* @throws AlgorithmAlreadyRegisteredException
*/
public static void register(String algorithmURI, Class<CanonicalizerSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
// check whether URI is already registered
Class<? extends CanonicalizerSpi> registeredClass = canonicalizerHash.get(algorithmURI);
if (registeredClass != null) {
Object exArgs[] = { algorithmURI, registeredClass };
throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
} }
canonicalizerHash.put(algorithmURI, implementingClass);
}
/**
* This method registers the default algorithms.
*/
public static void registerDefaultAlgorithms() {
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS,
Canonicalizer20010315OmitComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS,
Canonicalizer20010315WithComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS,
Canonicalizer20010315ExclOmitComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS,
Canonicalizer20010315ExclWithComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS,
Canonicalizer11_OmitComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS,
Canonicalizer11_WithComments.class
);
} }
/** /**
...@@ -173,7 +210,7 @@ public class Canonicalizer { ...@@ -173,7 +210,7 @@ public class Canonicalizer {
* @return the URI defined for this c14n instance. * @return the URI defined for this c14n instance.
*/ */
public final String getURI() { public final String getURI() {
return this.canonicalizerSpi.engineGetURI(); return canonicalizerSpi.engineGetURI();
} }
/** /**
...@@ -182,7 +219,7 @@ public class Canonicalizer { ...@@ -182,7 +219,7 @@ public class Canonicalizer {
* @return true if the c14n respect the comments. * @return true if the c14n respect the comments.
*/ */
public boolean getIncludeComments() { public boolean getIncludeComments() {
return this.canonicalizerSpi.engineGetIncludeComments(); return canonicalizerSpi.engineGetIncludeComments();
} }
/** /**
...@@ -191,33 +228,32 @@ public class Canonicalizer { ...@@ -191,33 +228,32 @@ public class Canonicalizer {
* wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>. * wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>.
* *
* @param inputBytes * @param inputBytes
* @return the result of the conicalization. * @return the result of the canonicalization.
* @throws CanonicalizationException * @throws CanonicalizationException
* @throws java.io.IOException * @throws java.io.IOException
* @throws javax.xml.parsers.ParserConfigurationException * @throws javax.xml.parsers.ParserConfigurationException
* @throws org.xml.sax.SAXException * @throws org.xml.sax.SAXException
*/ */
public byte[] canonicalize(byte[] inputBytes) public byte[] canonicalize(byte[] inputBytes)
throws javax.xml.parsers.ParserConfigurationException, throws javax.xml.parsers.ParserConfigurationException,
java.io.IOException, org.xml.sax.SAXException, java.io.IOException, org.xml.sax.SAXException, CanonicalizationException {
CanonicalizationException { InputStream bais = new ByteArrayInputStream(inputBytes);
ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);
InputSource in = new InputSource(bais); InputSource in = new InputSource(bais);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
dfactory.setNamespaceAware(true); dfactory.setNamespaceAware(true);
// needs to validate for ID attribute nomalization // needs to validate for ID attribute normalization
dfactory.setValidating(true); dfactory.setValidating(true);
DocumentBuilder db = dfactory.newDocumentBuilder(); DocumentBuilder db = dfactory.newDocumentBuilder();
/* /*
* for some of the test vectors from the specification, * for some of the test vectors from the specification,
* there has to be a validatin parser for ID attributes, default * there has to be a validating parser for ID attributes, default
* attribute values, NMTOKENS, etc. * attribute values, NMTOKENS, etc.
* Unfortunaltely, the test vectors do use different DTDs or * Unfortunately, the test vectors do use different DTDs or
* even no DTD. So Xerces 1.3.1 fires many warnings about using * even no DTD. So Xerces 1.3.1 fires many warnings about using
* ErrorHandlers. * ErrorHandlers.
* *
...@@ -233,28 +269,23 @@ public class Canonicalizer { ...@@ -233,28 +269,23 @@ public class Canonicalizer {
* declaration are used to help create the canonical form, even * declaration are used to help create the canonical form, even
* though the document type declaration is not retained in the * though the document type declaration is not retained in the
* canonical form. * canonical form.
*
*/ */
db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());
.IgnoreAllErrorHandler());
Document document = db.parse(in); Document document = db.parse(in);
byte result[] = this.canonicalizeSubtree(document); return this.canonicalizeSubtree(document);
return result;
} }
/** /**
* Canonicalizes the subtree rooted by <CODE>node</CODE>. * Canonicalizes the subtree rooted by <CODE>node</CODE>.
* *
* @param node The node to canicalize * @param node The node to canonicalize
* @return the result of the c14n. * @return the result of the c14n.
* *
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] canonicalizeSubtree(Node node) public byte[] canonicalizeSubtree(Node node) throws CanonicalizationException {
throws CanonicalizationException { return canonicalizerSpi.engineCanonicalizeSubTree(node);
return this.canonicalizerSpi.engineCanonicalizeSubTree(node);
} }
/** /**
...@@ -266,9 +297,8 @@ public class Canonicalizer { ...@@ -266,9 +297,8 @@ public class Canonicalizer {
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces) public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces)
throws CanonicalizationException { throws CanonicalizationException {
return this.canonicalizerSpi.engineCanonicalizeSubTree(node, return canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces);
inclusiveNamespaces);
} }
/** /**
...@@ -280,8 +310,8 @@ public class Canonicalizer { ...@@ -280,8 +310,8 @@ public class Canonicalizer {
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet) public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet)
throws CanonicalizationException { throws CanonicalizationException {
return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
} }
/** /**
...@@ -294,10 +324,10 @@ public class Canonicalizer { ...@@ -294,10 +324,10 @@ public class Canonicalizer {
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] canonicalizeXPathNodeSet( public byte[] canonicalizeXPathNodeSet(
NodeList xpathNodeSet, String inclusiveNamespaces) NodeList xpathNodeSet, String inclusiveNamespaces
throws CanonicalizationException { ) throws CanonicalizationException {
return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, return
inclusiveNamespaces); canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces);
} }
/** /**
...@@ -308,8 +338,8 @@ public class Canonicalizer { ...@@ -308,8 +338,8 @@ public class Canonicalizer {
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] canonicalizeXPathNodeSet(Set<Node> xpathNodeSet) public byte[] canonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
throws CanonicalizationException { throws CanonicalizationException {
return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
} }
/** /**
...@@ -320,10 +350,11 @@ public class Canonicalizer { ...@@ -320,10 +350,11 @@ public class Canonicalizer {
* @return the result of the c14n. * @return the result of the c14n.
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] canonicalizeXPathNodeSet(Set<Node> xpathNodeSet, public byte[] canonicalizeXPathNodeSet(
String inclusiveNamespaces) throws CanonicalizationException { Set<Node> xpathNodeSet, String inclusiveNamespaces
return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, ) throws CanonicalizationException {
inclusiveNamespaces); return
canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces);
} }
/** /**
...@@ -332,7 +363,7 @@ public class Canonicalizer { ...@@ -332,7 +363,7 @@ public class Canonicalizer {
* @param os * @param os
*/ */
public void setWriter(OutputStream os) { public void setWriter(OutputStream os) {
this.canonicalizerSpi.setWriter(os); canonicalizerSpi.setWriter(os);
} }
/** /**
...@@ -341,23 +372,14 @@ public class Canonicalizer { ...@@ -341,23 +372,14 @@ public class Canonicalizer {
* @return the name of the implementing {@link CanonicalizerSpi} class * @return the name of the implementing {@link CanonicalizerSpi} class
*/ */
public String getImplementingCanonicalizerClass() { public String getImplementingCanonicalizerClass() {
return this.canonicalizerSpi.getClass().getName(); return canonicalizerSpi.getClass().getName();
}
/**
* Method getImplementingClass
*
* @param URI
* @return the name of the class that implements the given URI
*/
private static Class<? extends CanonicalizerSpi> getImplementingClass(String URI) {
return _canonicalizerHash.get(URI);
} }
/** /**
* Set the canonicalizer behaviour to not reset. * Set the canonicalizer behaviour to not reset.
*/ */
public void notReset() { public void notReset() {
this.canonicalizerSpi.reset = false; canonicalizerSpi.reset = false;
} }
} }
...@@ -26,6 +26,7 @@ import java.io.ByteArrayInputStream; ...@@ -26,6 +26,7 @@ import java.io.ByteArrayInputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Set; import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
...@@ -67,6 +68,7 @@ public abstract class CanonicalizerSpi { ...@@ -67,6 +68,7 @@ public abstract class CanonicalizerSpi {
java.io.ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes); java.io.ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);
InputSource in = new InputSource(bais); InputSource in = new InputSource(bais);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
// needs to validate for ID attribute nomalization // needs to validate for ID attribute nomalization
dfactory.setNamespaceAware(true); dfactory.setNamespaceAware(true);
......
...@@ -41,6 +41,7 @@ import javax.crypto.Cipher; ...@@ -41,6 +41,7 @@ import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException; import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException; import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.IvParameterSpec;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
...@@ -1981,22 +1982,23 @@ public class XMLCipher { ...@@ -1981,22 +1982,23 @@ public class XMLCipher {
try { try {
DocumentBuilderFactory dbf = DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance(); DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true); dbf.setNamespaceAware(true);
dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
DocumentBuilder db = dbf.newDocumentBuilder(); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
Document d = db.parse( DocumentBuilder db = dbf.newDocumentBuilder();
new InputSource(new StringReader(fragment))); Document d = db.parse(
new InputSource(new StringReader(fragment)));
Element fragElt = (Element) _contextDocument.importNode(
Element fragElt = (Element) _contextDocument.importNode(
d.getDocumentElement(), true); d.getDocumentElement(), true);
result = _contextDocument.createDocumentFragment(); result = _contextDocument.createDocumentFragment();
Node child = fragElt.getFirstChild(); Node child = fragElt.getFirstChild();
while (child != null) { while (child != null) {
fragElt.removeChild(child); fragElt.removeChild(child);
result.appendChild(child); result.appendChild(child);
child = fragElt.getFirstChild(); child = fragElt.getFirstChild();
} }
// String outp = serialize(d); // String outp = serialize(d);
} catch (SAXException se) { } catch (SAXException se) {
throw new XMLEncryptionException("empty", se); throw new XMLEncryptionException("empty", se);
......
...@@ -719,42 +719,36 @@ public class KeyInfo extends SignatureElementProxy { ...@@ -719,42 +719,36 @@ public class KeyInfo extends SignatureElementProxy {
return null; return null;
} }
/** /**
* Searches the library wide keyresolvers for public keys * Searches the library wide keyresolvers for public keys
* *
* @return The publick contained in this Node. * @return The public key contained in this Node.
* @throws KeyResolverException * @throws KeyResolverException
*/ */
PublicKey getPublicKeyFromStaticResolvers() throws KeyResolverException { PublicKey getPublicKeyFromStaticResolvers() throws KeyResolverException {
int length=KeyResolver.length(); Iterator<KeyResolverSpi> it = KeyResolver.iterator();
int storageLength=this._storageResolvers.size(); while (it.hasNext()) {
Iterator<KeyResolverSpi> it= KeyResolver.iterator(); KeyResolverSpi keyResolver = it.next();
for (int i = 0; i < length; i++) { Node currentChild = this._constructionElement.getFirstChild();
KeyResolverSpi keyResolver = it.next(); String uri = this.getBaseURI();
Node currentChild=this._constructionElement.getFirstChild(); while (currentChild != null) {
String uri= this.getBaseURI(); if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
while (currentChild!=null) { for (StorageResolver storage : _storageResolvers) {
if (currentChild.getNodeType() == Node.ELEMENT_NODE) { PublicKey pk =
for (int k = 0; k < storageLength; k++) { keyResolver.engineLookupAndResolvePublicKey(
StorageResolver storage = (Element) currentChild, uri, storage
this._storageResolvers.get(k); );
PublicKey pk = if (pk != null) {
keyResolver.engineLookupAndResolvePublicKey((Element) currentChild, return pk;
uri, }
storage); }
}
if (pk != null) { currentChild = currentChild.getNextSibling();
KeyResolver.hit(it);
return pk;
}
}
} }
currentChild=currentChild.getNextSibling(); }
} return null;
} }
return null;
}
/** /**
* Searches the per-KeyInfo keyresolvers for public keys * Searches the per-KeyInfo keyresolvers for public keys
...@@ -829,81 +823,83 @@ public class KeyInfo extends SignatureElementProxy { ...@@ -829,81 +823,83 @@ public class KeyInfo extends SignatureElementProxy {
return null; return null;
} }
/** /**
* This method uses each System-wide {@link KeyResolver} to search the * This method uses each System-wide {@link KeyResolver} to search the
* child elements. Each combination of {@link KeyResolver} and child element * child elements. Each combination of {@link KeyResolver} and child element
* is checked against all {@link StorageResolver}s. * is checked against all {@link StorageResolver}s.
* *
* @return The certificate contined in this KeyInfo * @return The certificate contained in this KeyInfo
* @throws KeyResolverException * @throws KeyResolverException
*/ */
X509Certificate getX509CertificateFromStaticResolvers() X509Certificate getX509CertificateFromStaticResolvers()
throws KeyResolverException { throws KeyResolverException {
if (log.isLoggable(java.util.logging.Level.FINE)) if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Start getX509CertificateFromStaticResolvers() with " log.log(java.util.logging.Level.FINE,
+ KeyResolver.length() + " resolvers"); "Start getX509CertificateFromStaticResolvers() with " + KeyResolver.length()
String uri=this.getBaseURI(); + " resolvers"
int length= KeyResolver.length(); );
int storageLength=this._storageResolvers.size(); }
Iterator<KeyResolverSpi> it = KeyResolver.iterator(); String uri = this.getBaseURI();
for (int i = 0; i <length; i++) { Iterator<KeyResolverSpi> it = KeyResolver.iterator();
KeyResolverSpi keyResolver = it.next(); while (it.hasNext()) {
X509Certificate cert= applyCurrentResolver(uri, storageLength, keyResolver); KeyResolverSpi keyResolver = it.next();
if (cert!=null) { X509Certificate cert = applyCurrentResolver(uri, keyResolver);
KeyResolver.hit(it); if (cert != null) {
return cert; return cert;
} }
} }
return null; return null;
} }
private X509Certificate applyCurrentResolver(String uri, int storageLength, KeyResolverSpi keyResolver) throws KeyResolverException {
Node currentChild=this._constructionElement.getFirstChild();
while (currentChild!=null) {
if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
for (int k = 0; k < storageLength; k++) {
StorageResolver storage =
this._storageResolvers.get(k);
X509Certificate cert = keyResolver
.engineLookupResolveX509Certificate((Element) currentChild, uri,
storage);
if (cert != null) { private X509Certificate applyCurrentResolver(
return cert; String uri, KeyResolverSpi keyResolver
} ) throws KeyResolverException {
} Node currentChild = this._constructionElement.getFirstChild();
while (currentChild != null) {
if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
for (StorageResolver storage : _storageResolvers) {
X509Certificate cert =
keyResolver.engineLookupResolveX509Certificate(
(Element) currentChild, uri, storage
);
if (cert != null) {
return cert;
}
}
} }
currentChild=currentChild.getNextSibling(); currentChild = currentChild.getNextSibling();
} }
return null; return null;
} }
/** /**
* Method getX509CertificateFromInternalResolvers * Method getX509CertificateFromInternalResolvers
* *
* @return The certificate contined in this KeyInfo * @return The certificate contined in this KeyInfo
* @throws KeyResolverException * @throws KeyResolverException
*/ */
X509Certificate getX509CertificateFromInternalResolvers() X509Certificate getX509CertificateFromInternalResolvers()
throws KeyResolverException { throws KeyResolverException {
if (log.isLoggable(java.util.logging.Level.FINE)) if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Start getX509CertificateFromInternalResolvers() with " log.log(java.util.logging.Level.FINE,
+ this.lengthInternalKeyResolver() + " resolvers"); "Start getX509CertificateFromInternalResolvers() with "
String uri=this.getBaseURI(); + this.lengthInternalKeyResolver() + " resolvers"
int storageLength=this._storageResolvers.size(); );
for (int i = 0; i < this.lengthInternalKeyResolver(); i++) { }
KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i); String uri = this.getBaseURI();
if (log.isLoggable(java.util.logging.Level.FINE)) for (KeyResolverSpi keyResolver : _internalKeyResolvers) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
X509Certificate cert= applyCurrentResolver(uri, storageLength, keyResolver); }
if (cert!=null) { X509Certificate cert = applyCurrentResolver(uri, keyResolver);
return cert; if (cert != null) {
} return cert;
} }
}
return null; return null;
} }
/** /**
* This method returns a secret (symmetric) key. This is for XML Encryption. * This method returns a secret (symmetric) key. This is for XML Encryption.
...@@ -1048,7 +1044,7 @@ public class KeyInfo extends SignatureElementProxy { ...@@ -1048,7 +1044,7 @@ public class KeyInfo extends SignatureElementProxy {
} }
/** Field _storageResolvers */ /** Field _storageResolvers */
List<StorageResolver> _storageResolvers = nullList; private List<StorageResolver> _storageResolvers = nullList;
/** /**
* Method addStorageResolver * Method addStorageResolver
......
...@@ -2,357 +2,402 @@ ...@@ -2,357 +2,402 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /**
* Copyright 1999-2004 The Apache Software Foundation. * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* http://www.apache.org/licenses/LICENSE-2.0 * with the License. You may obtain a copy of the License at
* *
* Unless required by applicable law or agreed to in writing, software * http://www.apache.org/licenses/LICENSE-2.0
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package com.sun.org.apache.xml.internal.security.keys.keyresolver; package com.sun.org.apache.xml.internal.security.keys.keyresolver;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RSAKeyValueResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RetrievalMethodResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509CertificateResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509IssuerSerialResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
/** /**
* KeyResolver is factory class for subclass of KeyResolverSpi that * KeyResolver is factory class for subclass of KeyResolverSpi that
* represent child element of KeyInfo. * represent child element of KeyInfo.
*
* @author $Author: mullan $
* @version %I%, %G%
*/ */
public class KeyResolver { public class KeyResolver {
/** {@link java.util.logging} logging facility */ /** {@link org.apache.commons.logging} logging facility */
static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(KeyResolver.class.getName()); java.util.logging.Logger.getLogger(KeyResolver.class.getName());
/** Field _alreadyInitialized */ /** Field resolverVector */
static boolean _alreadyInitialized = false; private static List<KeyResolver> resolverVector = new CopyOnWriteArrayList<KeyResolver>();
/** Field _resolverVector */ /** Field resolverSpi */
static List<KeyResolver> _resolverVector = null; private final KeyResolverSpi resolverSpi;
/** Field _resolverSpi */ /**
protected KeyResolverSpi _resolverSpi = null; * Constructor.
*
/** Field _storage */ * @param keyResolverSpi a KeyResolverSpi instance
protected StorageResolver _storage = null; */
private KeyResolver(KeyResolverSpi keyResolverSpi) {
/** resolverSpi = keyResolverSpi;
* Constructor ResourceResolver }
*
* @param className /**
* @throws ClassNotFoundException * Method length
* @throws IllegalAccessException *
* @throws InstantiationException * @return the length of resolvers registered
*/ */
private KeyResolver(String className) public static int length() {
throws ClassNotFoundException, IllegalAccessException, return resolverVector.size();
InstantiationException { }
this._resolverSpi =
(KeyResolverSpi) Class.forName(className).newInstance(); /**
this._resolverSpi.setGlobalResolver(true); * Method getX509Certificate
} *
* @param element
/** * @param baseURI
* Method length * @param storage
* * @return The certificate represented by the element.
* @return the length of resolvers registed *
*/ * @throws KeyResolverException
public static int length() { */
return KeyResolver._resolverVector.size(); public static final X509Certificate getX509Certificate(
} Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
public static void hit(Iterator<KeyResolverSpi> hintI) { for (KeyResolver resolver : resolverVector) {
ResolverIterator hint = (ResolverIterator) hintI; if (resolver == null) {
int i = hint.i; Object exArgs[] = {
if (i!=1 && hint.res ==_resolverVector) { (((element != null)
List<KeyResolver> resolverVector=getResolverVectorClone(); && (element.getNodeType() == Node.ELEMENT_NODE))
KeyResolver ob=resolverVector.remove(i-1); ? element.getTagName() : "null")
resolverVector.add(0,ob); };
_resolverVector=resolverVector;
} else { throw new KeyResolverException("utils.resolver.noClass", exArgs);
//System.out.println("KeyResolver hitting"); }
} if (log.isLoggable(java.util.logging.Level.FINE)) {
}
/**
* Method getInstance
*
* @param element
* @param BaseURI
* @param storage
* @return The certificate represented by the element.
*
* @throws KeyResolverException
*/
public static final X509Certificate getX509Certificate(
Element element, String BaseURI, StorageResolver storage)
throws KeyResolverException {
// use the old vector to not be hit by updates
List<KeyResolver> resolverVector = KeyResolver._resolverVector;
for (KeyResolver resolver : resolverVector) {
if (resolver==null) {
Object exArgs[] = {
(((element != null)
&& (element.getNodeType() == Node.ELEMENT_NODE))
? element.getTagName()
: "null") };
throw new KeyResolverException("utils.resolver.noClass", exArgs);
}
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass()); log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass());
}
X509Certificate cert = resolver.resolveX509Certificate(element, baseURI, storage);
if (cert != null) {
return cert;
}
}
X509Certificate cert=resolver.resolveX509Certificate(element, BaseURI, storage); Object exArgs[] = {
if (cert!=null) { (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
return cert; ? element.getTagName() : "null")
} };
}
throw new KeyResolverException("utils.resolver.noClass", exArgs);
Object exArgs[] = { }
(((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
? element.getTagName() /**
: "null") }; * Method getPublicKey
*
throw new KeyResolverException("utils.resolver.noClass", exArgs); * @param element
} * @param baseURI
/** * @param storage
* Method getInstance * @return the public key contained in the element
* *
* @param element * @throws KeyResolverException
* @param BaseURI */
* @param storage public static final PublicKey getPublicKey(
* @return the public key contained in the element Element element, String baseURI, StorageResolver storage
* ) throws KeyResolverException {
* @throws KeyResolverException for (KeyResolver resolver : resolverVector) {
*/ if (resolver == null) {
public static final PublicKey getPublicKey( Object exArgs[] = {
Element element, String BaseURI, StorageResolver storage) (((element != null)
throws KeyResolverException { && (element.getNodeType() == Node.ELEMENT_NODE))
? element.getTagName() : "null")
List<KeyResolver> resolverVector = KeyResolver._resolverVector; };
for (KeyResolver resolver : resolverVector) {
throw new KeyResolverException("utils.resolver.noClass", exArgs);
if (resolver==null) { }
Object exArgs[] = { if (log.isLoggable(java.util.logging.Level.FINE)) {
(((element != null)
&& (element.getNodeType() == Node.ELEMENT_NODE))
? element.getTagName()
: "null") };
throw new KeyResolverException("utils.resolver.noClass", exArgs);
}
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass()); log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass());
}
PublicKey cert=resolver.resolvePublicKey(element, BaseURI, storage); PublicKey cert = resolver.resolvePublicKey(element, baseURI, storage);
if (cert!=null) { if (cert != null) {
if (resolverVector.indexOf(resolver)!=0 && resolverVector==_resolverVector) { return cert;
//update resolver. }
resolverVector=getResolverVectorClone();
resolverVector.remove(resolver);
resolverVector.add(0,resolver);
_resolverVector=resolverVector;
}
return cert;
}
}
Object exArgs[] = {
(((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
? element.getTagName()
: "null") };
throw new KeyResolverException("utils.resolver.noClass", exArgs);
}
@SuppressWarnings("unchecked")
private static List<KeyResolver> getResolverVectorClone() {
return (List<KeyResolver>)((ArrayList<KeyResolver>)_resolverVector).clone();
}
/**
* The init() function is called by com.sun.org.apache.xml.internal.security.Init.init()
*/
public static void init() {
if (!KeyResolver._alreadyInitialized) {
KeyResolver._resolverVector = new ArrayList<KeyResolver>(10);
_alreadyInitialized = true;
}
}
/**
* This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
* personalized {@link KeyResolverSpi}s should only be registered directly
* to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
* {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
*
* @param className
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
*/
public static void register(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
KeyResolver._resolverVector.add(new KeyResolver(className));
}
/**
* This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
* personalized {@link KeyResolverSpi}s should only be registered directly
* to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
*
* @param className
*/
public static void registerAtStart(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
register(className);
}
/**
* Method resolve
*
* @param element
* @param BaseURI
* @param storage
* @return resolved public key from the registered from the elements
*
* @throws KeyResolverException
*/
public PublicKey resolvePublicKey(
Element element, String BaseURI, StorageResolver storage)
throws KeyResolverException {
return this._resolverSpi.engineLookupAndResolvePublicKey(element, BaseURI, storage);
}
/**
* Method resolveX509Certificate
*
* @param element
* @param BaseURI
* @param storage
* @return resolved X509certificate key from the registered from the elements
*
* @throws KeyResolverException
*/
public X509Certificate resolveX509Certificate(
Element element, String BaseURI, StorageResolver storage)
throws KeyResolverException {
return this._resolverSpi.engineLookupResolveX509Certificate(element, BaseURI,
storage);
}
/**
* @param element
* @param BaseURI
* @param storage
* @return resolved SecretKey key from the registered from the elements
* @throws KeyResolverException
*/
public SecretKey resolveSecretKey(
Element element, String BaseURI, StorageResolver storage)
throws KeyResolverException {
return this._resolverSpi.engineLookupAndResolveSecretKey(element, BaseURI,
storage);
}
/**
* Method setProperty
*
* @param key
* @param value
*/
public void setProperty(String key, String value) {
this._resolverSpi.engineSetProperty(key, value);
}
/**
* Method getProperty
*
* @param key
* @return the property setted for this resolver
*/
public String getProperty(String key) {
return this._resolverSpi.engineGetProperty(key);
}
/**
* Method understandsProperty
*
* @param propertyToTest
* @return true if the resolver understands property propertyToTest
*/
public boolean understandsProperty(String propertyToTest) {
return this._resolverSpi.understandsProperty(propertyToTest);
}
/**
* Method resolverClassName
*
* @return the name of the resolver.
*/
public String resolverClassName() {
return this._resolverSpi.getClass().getName();
}
static class ResolverIterator implements Iterator<KeyResolverSpi> {
List<KeyResolver> res;
Iterator<KeyResolver> it;
int i;
public ResolverIterator(List<KeyResolver> list) {
res = list;
it = res.iterator();
} }
public boolean hasNext() {
// TODO Auto-generated method stub Object exArgs[] = {
return it.hasNext(); (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
} ? element.getTagName() : "null")
};
public KeyResolverSpi next() {
i++; throw new KeyResolverException("utils.resolver.noClass", exArgs);
KeyResolver resolver = it.next(); }
if (resolver==null) {
throw new RuntimeException("utils.resolver.noClass"); /**
} * This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
return resolver._resolverSpi; * personalized {@link KeyResolverSpi}s should only be registered directly
} * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
* {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
public void remove() { * Please note that this method will create a new copy of the underlying array, as the
// TODO Auto-generated method stub * underlying collection is a CopyOnWriteArrayList.
*
} * @param className
* @param globalResolver Whether the KeyResolverSpi is a global resolver or not
}; * @throws InstantiationException
public static Iterator<KeyResolverSpi> iterator() { * @throws IllegalAccessException
return new ResolverIterator(_resolverVector); * @throws ClassNotFoundException
} */
public static void register(String className, boolean globalResolver)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
KeyResolverSpi keyResolverSpi =
(KeyResolverSpi) Class.forName(className).newInstance();
keyResolverSpi.setGlobalResolver(globalResolver);
register(keyResolverSpi, false);
}
/**
* This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
* personalized {@link KeyResolverSpi}s should only be registered directly
* to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
* {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
* Please note that this method will create a new copy of the underlying array, as the
* underlying collection is a CopyOnWriteArrayList.
*
* @param className
* @param globalResolver Whether the KeyResolverSpi is a global resolver or not
*/
public static void registerAtStart(String className, boolean globalResolver) {
KeyResolverSpi keyResolverSpi = null;
Exception ex = null;
try {
keyResolverSpi = (KeyResolverSpi) Class.forName(className).newInstance();
} catch (ClassNotFoundException e) {
ex = e;
} catch (IllegalAccessException e) {
ex = e;
} catch (InstantiationException e) {
ex = e;
}
if (ex != null) {
throw (IllegalArgumentException) new
IllegalArgumentException("Invalid KeyResolver class name").initCause(ex);
}
keyResolverSpi.setGlobalResolver(globalResolver);
register(keyResolverSpi, true);
}
/**
* This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
* personalized {@link KeyResolverSpi}s should only be registered directly
* to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
* {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
* Please note that this method will create a new copy of the underlying array, as the
* underlying collection is a CopyOnWriteArrayList.
*
* @param keyResolverSpi a KeyResolverSpi instance to register
* @param start whether to register the KeyResolverSpi at the start of the list or not
*/
public static void register(
KeyResolverSpi keyResolverSpi,
boolean start
) {
KeyResolver resolver = new KeyResolver(keyResolverSpi);
if (start) {
resolverVector.add(0, resolver);
} else {
resolverVector.add(resolver);
}
}
/**
* This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
* personalized {@link KeyResolverSpi}s should only be registered directly
* to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
* {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
* The KeyResolverSpi instances are not registered as a global resolver.
*
*
* @param classNames
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
*/
public static void registerClassNames(List<String> classNames)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
List<KeyResolver> keyResolverList = new ArrayList<KeyResolver>(classNames.size());
for (String className : classNames) {
KeyResolverSpi keyResolverSpi =
(KeyResolverSpi) Class.forName(className).newInstance();
keyResolverSpi.setGlobalResolver(false);
keyResolverList.add(new KeyResolver(keyResolverSpi));
}
resolverVector.addAll(keyResolverList);
}
/**
* This method registers the default resolvers.
*/
public static void registerDefaultResolvers() {
List<KeyResolver> keyResolverList = new ArrayList<KeyResolver>();
keyResolverList.add(new KeyResolver(new RSAKeyValueResolver()));
keyResolverList.add(new KeyResolver(new DSAKeyValueResolver()));
keyResolverList.add(new KeyResolver(new X509CertificateResolver()));
keyResolverList.add(new KeyResolver(new X509SKIResolver()));
keyResolverList.add(new KeyResolver(new RetrievalMethodResolver()));
keyResolverList.add(new KeyResolver(new X509SubjectNameResolver()));
keyResolverList.add(new KeyResolver(new X509IssuerSerialResolver()));
resolverVector.addAll(keyResolverList);
}
/**
* Method resolvePublicKey
*
* @param element
* @param baseURI
* @param storage
* @return resolved public key from the registered from the elements
*
* @throws KeyResolverException
*/
public PublicKey resolvePublicKey(
Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
return resolverSpi.engineLookupAndResolvePublicKey(element, baseURI, storage);
}
/**
* Method resolveX509Certificate
*
* @param element
* @param baseURI
* @param storage
* @return resolved X509certificate key from the registered from the elements
*
* @throws KeyResolverException
*/
public X509Certificate resolveX509Certificate(
Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
return resolverSpi.engineLookupResolveX509Certificate(element, baseURI, storage);
}
/**
* @param element
* @param baseURI
* @param storage
* @return resolved SecretKey key from the registered from the elements
* @throws KeyResolverException
*/
public SecretKey resolveSecretKey(
Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
return resolverSpi.engineLookupAndResolveSecretKey(element, baseURI, storage);
}
/**
* Method setProperty
*
* @param key
* @param value
*/
public void setProperty(String key, String value) {
resolverSpi.engineSetProperty(key, value);
}
/**
* Method getProperty
*
* @param key
* @return the property set for this resolver
*/
public String getProperty(String key) {
return resolverSpi.engineGetProperty(key);
}
/**
* Method understandsProperty
*
* @param propertyToTest
* @return true if the resolver understands property propertyToTest
*/
public boolean understandsProperty(String propertyToTest) {
return resolverSpi.understandsProperty(propertyToTest);
}
/**
* Method resolverClassName
*
* @return the name of the resolver.
*/
public String resolverClassName() {
return resolverSpi.getClass().getName();
}
/**
* Iterate over the KeyResolverSpi instances
*/
static class ResolverIterator implements Iterator<KeyResolverSpi> {
List<KeyResolver> res;
Iterator<KeyResolver> it;
public ResolverIterator(List<KeyResolver> list) {
res = list;
it = res.iterator();
}
public boolean hasNext() {
return it.hasNext();
}
public KeyResolverSpi next() {
KeyResolver resolver = it.next();
if (resolver == null) {
throw new RuntimeException("utils.resolver.noClass");
}
return resolver.resolverSpi;
}
public void remove() {
throw new UnsupportedOperationException("Can't remove resolvers using the iterator");
}
};
public static Iterator<KeyResolverSpi> iterator() {
return new ResolverIterator(resolverVector);
}
} }
...@@ -34,6 +34,7 @@ import java.util.List; ...@@ -34,6 +34,7 @@ import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Set; import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
...@@ -251,6 +252,7 @@ public class RetrievalMethodResolver extends KeyResolverSpi { ...@@ -251,6 +252,7 @@ public class RetrievalMethodResolver extends KeyResolverSpi {
try { try {
javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true); dbf.setNamespaceAware(true);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = org.w3c.dom.Document doc =
db.parse(new java.io.ByteArrayInputStream(bytes)); db.parse(new java.io.ByteArrayInputStream(bytes));
......
algorithm.alreadyRegistered = URI {0} already assigned to class {1} algorithm.alreadyRegistered = URI {0} already assigned to class {1}
algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH
algorithm.ClassDoesNotExist = Class {0} does not exist algorithm.ClassDoesNotExist = Class {0} does not exist
algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2} algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2}
algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1} algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1}
algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1} algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1}
algorithms.operationOnlyVerification = A public key can only used for verification of a signature. algorithms.operationOnlyVerification = A public key can only used for verification of a signature.
algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed. algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed.
attributeValueIllegal = The attribute {0} has value {1} but must be {2} attributeValueIllegal = The attribute {0} has value {1} but must be {2}
c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0} c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0}
c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1} c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1}
c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0} c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0}
c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0} c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0}
c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}" c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}"
c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0} c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0}
c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0} c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0}
c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0} c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0}
c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation
c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document) c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document)
certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0} certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0}
certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString
certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier
defaultNamespaceCannotBeSetHere = Default namespace cannot be set here defaultNamespaceCannotBeSetHere = Default namespace cannot be set here
ElementProxy.nullElement = Cannot create an ElementProxy from a null argument ElementProxy.nullElement = Cannot create an ElementProxy from a null argument
empty = {0} empty = {0}
encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0} encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0}
encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams
encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt
encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap
encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit
encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this. encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this.
encryption.RSAOAEP.dataHashWrong = data hash wrong encryption.RSAOAEP.dataHashWrong = data hash wrong
encryption.RSAOAEP.dataStartWrong = data wrong start {0} encryption.RSAOAEP.dataStartWrong = data wrong start {0}
encryption.RSAOAEP.dataTooShort = data too short encryption.RSAOAEP.dataTooShort = data too short
encryption.RSAPKCS15.blockTruncated = block truncated encryption.RSAPKCS15.blockTruncated = block truncated
encryption.RSAPKCS15.noDataInBlock = no data in block encryption.RSAPKCS15.noDataInBlock = no data in block
encryption.RSAPKCS15.unknownBlockType = unknown block type encryption.RSAPKCS15.unknownBlockType = unknown block type
encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers
endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at <http://xml.apache.org/security/Java/installation.html> how to solve this problem. endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at <http://xml.apache.org/security/Java/installation.html> how to solve this problem.
errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution. errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution.
errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed. errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed.
errorMessages.IOException = Other file I/O and similar exceptions. errorMessages.IOException = Other file I/O and similar exceptions.
errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again. errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again.
errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again. errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again.
errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0} errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0}
errorMessages.NotYetImplementedException = Functionality not yet there. errorMessages.NotYetImplementedException = Functionality not yet there.
errorMessages.XMLSignatureException = Verification failed for some other reason. errorMessages.XMLSignatureException = Verification failed for some other reason.
decoding.divisible.four = It should be divisible by four decoding.divisible.four = It should be divisible by four
decoding.general = Error while decoding decoding.general = Error while decoding
FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented. FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented.
FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0} FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0}
FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1} FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1}
FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0} FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0}
generic.dontHaveConstructionElement = I do not have a construction Element generic.dontHaveConstructionElement = I do not have a construction Element
generic.EmptyMessage = {0} generic.EmptyMessage = {0}
generic.NotYetImplemented = {0} Not YET implemented ;-(( generic.NotYetImplemented = {0} Not YET implemented ;-((
java.security.InvalidKeyException = Invalid key java.security.InvalidKeyException = Invalid key
java.security.NoSuchProviderException = Unknown or unsupported provider java.security.NoSuchProviderException = Unknown or unsupported provider
java.security.UnknownKeyType = Unknown or unsupported key type {0} java.security.UnknownKeyType = Unknown or unsupported key type {0}
KeyInfo.needKeyResolver = More than one keyResovler have to be registered KeyInfo.needKeyResolver = More than one keyResovler have to be registered
KeyInfo.nokey = Cannot get key from {0} KeyInfo.nokey = Cannot get key from {0}
KeyInfo.noKey = Cannot get the public key KeyInfo.noKey = Cannot get the public key
KeyInfo.wrongNumberOfObject = Need {0} keyObjects KeyInfo.wrongNumberOfObject = Need {0} keyObjects
KeyInfo.wrongUse = This object was made for getting {0} KeyInfo.wrongUse = This object was made for getting {0}
keyResolver.alreadyRegistered = {1} class has already been registered for {0} keyResolver.alreadyRegistered = {1} class has already been registered for {0}
KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0} KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0}
KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0} KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0}
KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0} KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0}
KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0} KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0}
KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0} KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0}
KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0} KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0}
KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0} KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0}
KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0} KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0}
KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0} KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0}
KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0} KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0}
KeyStore.alreadyRegistered = {0} Class has already been registered for {1} KeyStore.alreadyRegistered = {0} Class has already been registered for {1}
KeyStore.register = {1} type class register error in class {0} KeyStore.register = {1} type class register error in class {0}
KeyStore.registerStore.register = Registeration error for type {0} KeyStore.registerStore.register = Registeration error for type {0}
KeyValue.IllegalArgument = Cannot create a {0} from {1} KeyValue.IllegalArgument = Cannot create a {0} from {1}
namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1} namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1}
notYetInitialized = The module {0} is not yet initialized notYetInitialized = The module {0} is not yet initialized
prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2} prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2}
signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0} signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0}
signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled
signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled
signature.Transform.NotYetImplemented = Transform {0} not yet implemented signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set
signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug? signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform
signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0} signature.Transform.NotYetImplemented = Transform {0} not yet implemented
signature.Transform.node = Current Node: {0} signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug?
signature.Transform.nodeAndType = Current Node: {0}, type: {1} signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0}
signature.Util.BignumNonPositive = bigInteger.signum() must be positive signature.Transform.node = Current Node: {0}
signature.Util.NonTextNode = Not a text node signature.Transform.nodeAndType = Current Node: {0}, type: {1}
signature.Util.TooManyChilds = Too many childs of Type {0} in {1} signature.Util.BignumNonPositive = bigInteger.signum() must be positive
signature.Verification.certificateError = Certificate error signature.Util.NonTextNode = Not a text node
signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References signature.Util.TooManyChilds = Too many childs of Type {0} in {1}
signature.Verification.internalError = Internal error signature.Verification.certificateError = Certificate error
signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0} signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References
signature.Verification.keyStore = KeyStore error signature.Verification.internalError = Internal error
signature.Verification.MissingID = Cannot resolve element with ID {0} signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0}
signature.Verification.MissingResources = Cannot resolve external resource {0} signature.Verification.keyStore = KeyStore error
signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1} signature.Verification.MissingID = Cannot resolve element with ID {0}
signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput signature.Verification.MissingResources = Cannot resolve external resource {0}
signature.Verification.SignatureError = Signature error signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected
signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0} signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1}
signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput
signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference signature.Verification.SignatureError = Signature error
transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream. signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0}
transform.init.NotInitialized = signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it
transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference
utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4 transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream.
Base64Decoding = Error while decoding transform.init.NotInitialized =
utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1} transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization
xml.WrongContent = Cannot find {0} in {1} utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4
xml.WrongElement = Cannot create a {0} from a {1} element Base64Decoding = Error while decoding
xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1}
xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0} xml.WrongContent = Cannot find {0} in {1}
xml.WrongElement = Cannot create a {0} from a {1} element
xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node
xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0}
...@@ -25,6 +25,7 @@ import java.io.IOException; ...@@ -25,6 +25,7 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm; import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
...@@ -186,8 +187,10 @@ public class SignedInfo extends Manifest { ...@@ -186,8 +187,10 @@ public class SignedInfo extends Manifest {
javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory dbf =
javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true); dbf.setNamespaceAware(true);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
Boolean.TRUE);
javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document newdoc = Document newdoc =
db.parse(new ByteArrayInputStream(this._c14nizedBytes)); db.parse(new ByteArrayInputStream(this._c14nizedBytes));
Node imported = Node imported =
this._doc.importNode(newdoc.getDocumentElement(), true); this._doc.importNode(newdoc.getDocumentElement(), true);
......
...@@ -201,14 +201,13 @@ private Element signatureValueElement; ...@@ -201,14 +201,13 @@ private Element signatureValueElement;
super(doc); super(doc);
String xmlnsDsPrefix = String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
getDefaultPrefixBindings(Constants.SignatureSpecNS);
if (xmlnsDsPrefix == null) { if (xmlnsDsPrefix == null) {
this._constructionElement.setAttributeNS this._constructionElement.setAttributeNS
(Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS); (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS);
} else { } else {
this._constructionElement.setAttributeNS this._constructionElement.setAttributeNS
(Constants.NamespaceSpecNS, xmlnsDsPrefix, Constants.SignatureSpecNS); (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS);
} }
XMLUtils.addReturnToElement(this._constructionElement); XMLUtils.addReturnToElement(this._constructionElement);
...@@ -242,14 +241,13 @@ private Element signatureValueElement; ...@@ -242,14 +241,13 @@ private Element signatureValueElement;
super(doc); super(doc);
String xmlnsDsPrefix = String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
getDefaultPrefixBindings(Constants.SignatureSpecNS);
if (xmlnsDsPrefix == null) { if (xmlnsDsPrefix == null) {
this._constructionElement.setAttributeNS this._constructionElement.setAttributeNS
(Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS); (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS);
} else { } else {
this._constructionElement.setAttributeNS this._constructionElement.setAttributeNS
(Constants.NamespaceSpecNS, xmlnsDsPrefix, Constants.SignatureSpecNS); (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS);
} }
XMLUtils.addReturnToElement(this._constructionElement); XMLUtils.addReturnToElement(this._constructionElement);
......
...@@ -31,6 +31,7 @@ import java.util.HashSet; ...@@ -31,6 +31,7 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
...@@ -603,6 +604,8 @@ public class XMLSignatureInput implements Cloneable { ...@@ -603,6 +604,8 @@ public class XMLSignatureInput implements Cloneable {
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setValidating(false); dfactory.setValidating(false);
dfactory.setNamespaceAware(true); dfactory.setNamespaceAware(true);
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
Boolean.TRUE);
DocumentBuilder db = dfactory.newDocumentBuilder(); DocumentBuilder db = dfactory.newDocumentBuilder();
// select all nodes, also the comments. // select all nodes, also the comments.
try { try {
......
...@@ -2,29 +2,29 @@ ...@@ -2,29 +2,29 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /**
* Copyright 1999-2004 The Apache Software Foundation. * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* http://www.apache.org/licenses/LICENSE-2.0 * with the License. You may obtain a copy of the License at
* *
* Unless required by applicable law or agreed to in writing, software * http://www.apache.org/licenses/LICENSE-2.0
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package com.sun.org.apache.xml.internal.security.transforms; package com.sun.org.apache.xml.internal.security.transforms;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.security.AccessController; import java.util.concurrent.ConcurrentHashMap;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
...@@ -33,6 +33,18 @@ import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerExcepti ...@@ -33,6 +33,18 @@ import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerExcepti
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException; import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14N;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14N11;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14N11_WithComments;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14NExclusive;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14NExclusiveWithComments;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14NWithComments;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformEnvelopedSignature;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath2Filter;
import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXSLT;
import com.sun.org.apache.xml.internal.security.utils.ClassLoaderUtils;
import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.HelperNodeList; import com.sun.org.apache.xml.internal.security.utils.HelperNodeList;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
...@@ -54,112 +66,31 @@ import org.xml.sax.SAXException; ...@@ -54,112 +66,31 @@ import org.xml.sax.SAXException;
* @author Christian Geuer-Pollmann * @author Christian Geuer-Pollmann
* @see Transforms * @see Transforms
* @see TransformSpi * @see TransformSpi
*
*/ */
public final class Transform extends SignatureElementProxy { public final class Transform extends SignatureElementProxy {
/** {@link java.util.logging} logging facility */ /** {@link org.apache.commons.logging} logging facility */
static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(Transform.class.getName()); java.util.logging.Logger.getLogger(Transform.class.getName());
/** Field _alreadyInitialized */
private static boolean alreadyInitialized = false;
/** All available Transform classes are registered here */ /** All available Transform classes are registered here */
private static Map<String, Class<?>> transformClassHash = null; private static Map<String, Class<? extends TransformSpi>> transformSpiHash =
new ConcurrentHashMap<String, Class<? extends TransformSpi>>();
private static Map<String, TransformSpi> transformSpiHash = new HashMap<String, TransformSpi>();
private TransformSpi transformSpi = null;
/**
* Constructs {@link Transform}
*
* @param doc the {@link Document} in which <code>Transform</code> will be
* placed
* @param algorithmURI URI representation of
* <code>Transform algorithm</code> which will be specified as parameter of
* {@link #getInstance(Document, String)}, when generated. </br>
* @param contextNodes the child node list of <code>Transform</code> element
* @throws InvalidTransformException
*/
public Transform(Document doc, String algorithmURI, NodeList contextNodes)
throws InvalidTransformException {
super(doc);
this._constructionElement.setAttributeNS
(null, Constants._ATT_ALGORITHM, algorithmURI);
transformSpi = getTransformSpi(algorithmURI);
if (transformSpi == null) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException(
"signature.Transform.UnknownTransform", exArgs);
}
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
+ transformSpi.getClass() + "\"");
log.log(java.util.logging.Level.FINE, "The NodeList is " + contextNodes);
}
// give it to the current document
if (contextNodes != null) {
for (int i = 0; i < contextNodes.getLength(); i++) {
this._constructionElement.appendChild
(contextNodes.item(i).cloneNode(true));
}
}
}
/**
* This constructor can only be called from the {@link Transforms} object,
* so it's protected.
*
* @param element <code>ds:Transform</code> element
* @param BaseURI the URI of the resource where the XML instance was stored
* @throws InvalidTransformException
* @throws TransformationException
* @throws XMLSecurityException
*/
public Transform(Element element, String BaseURI)
throws InvalidTransformException, TransformationException,
XMLSecurityException {
super(element, BaseURI); private final TransformSpi transformSpi;
// retrieve Algorithm Attribute from ds:Transform
String algorithmURI = element.getAttributeNS(null, Constants._ATT_ALGORITHM);
if (algorithmURI == null || algorithmURI.length() == 0) {
Object exArgs[] = { Constants._ATT_ALGORITHM,
Constants._TAG_TRANSFORM };
throw new TransformationException("xml.WrongContent", exArgs);
}
transformSpi = getTransformSpi(algorithmURI);
if (transformSpi == null) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException(
"signature.Transform.UnknownTransform", exArgs);
}
}
/** /**
* Generates a Transform object that implements the specified * Generates a Transform object that implements the specified
* <code>Transform algorithm</code> URI. * <code>Transform algorithm</code> URI.
* *
* @param doc the proxy {@link Document}
* @param algorithmURI <code>Transform algorithm</code> URI representation, * @param algorithmURI <code>Transform algorithm</code> URI representation,
* such as specified in * such as specified in
* <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>Transform algorithm </a> * <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>Transform algorithm </a>
* @param doc the proxy {@link Document}
* @return <code>{@link Transform}</code> object
* @throws InvalidTransformException * @throws InvalidTransformException
*/ */
public static Transform getInstance( public Transform(Document doc, String algorithmURI) throws InvalidTransformException {
Document doc, String algorithmURI) throws InvalidTransformException { this(doc, algorithmURI, (NodeList)null);
return getInstance(doc, algorithmURI, (NodeList) null);
} }
/** /**
...@@ -171,82 +102,160 @@ public final class Transform extends SignatureElementProxy { ...@@ -171,82 +102,160 @@ public final class Transform extends SignatureElementProxy {
* <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>Transform algorithm </a> * <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>Transform algorithm </a>
* @param contextChild the child element of <code>Transform</code> element * @param contextChild the child element of <code>Transform</code> element
* @param doc the proxy {@link Document} * @param doc the proxy {@link Document}
* @return <code>{@link Transform}</code> object
* @throws InvalidTransformException * @throws InvalidTransformException
*/ */
public static Transform getInstance( public Transform(Document doc, String algorithmURI, Element contextChild)
Document doc, String algorithmURI, Element contextChild)
throws InvalidTransformException { throws InvalidTransformException {
super(doc);
HelperNodeList contextNodes = null;
HelperNodeList contextNodes = new HelperNodeList(); if (contextChild != null) {
contextNodes = new HelperNodeList();
XMLUtils.addReturnToElement(doc, contextNodes); XMLUtils.addReturnToElement(doc, contextNodes);
contextNodes.appendChild(contextChild); contextNodes.appendChild(contextChild);
XMLUtils.addReturnToElement(doc, contextNodes); XMLUtils.addReturnToElement(doc, contextNodes);
}
return getInstance(doc, algorithmURI, contextNodes); transformSpi = initializeTransform(algorithmURI, contextNodes);
} }
/** /**
* Generates a Transform object that implements the specified * Constructs {@link Transform}
* <code>Transform algorithm</code> URI.
* *
* @param algorithmURI <code>Transform algorithm</code> URI form, such as * @param doc the {@link Document} in which <code>Transform</code> will be
* specified in <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg> * placed
* Transform algorithm </a> * @param algorithmURI URI representation of <code>Transform algorithm</code>
* @param contextNodes the child node list of <code>Transform</code> element * @param contextNodes the child node list of <code>Transform</code> element
* @param doc the proxy {@link Document}
* @return <code>{@link Transform}</code> object
* @throws InvalidTransformException * @throws InvalidTransformException
*/ */
public static Transform getInstance( public Transform(Document doc, String algorithmURI, NodeList contextNodes)
Document doc, String algorithmURI, NodeList contextNodes)
throws InvalidTransformException { throws InvalidTransformException {
return new Transform(doc, algorithmURI, contextNodes); super(doc);
transformSpi = initializeTransform(algorithmURI, contextNodes);
} }
/** /**
* Initalizes for this {@link Transform}. * @param element <code>ds:Transform</code> element
* @param BaseURI the URI of the resource where the XML instance was stored
* @throws InvalidTransformException
* @throws TransformationException
* @throws XMLSecurityException
*/ */
public static void init() { public Transform(Element element, String BaseURI)
if (!alreadyInitialized) { throws InvalidTransformException, TransformationException, XMLSecurityException {
transformClassHash = new HashMap<String,Class<?>>(10); super(element, BaseURI);
// make sure builtin algorithms are all registered first
com.sun.org.apache.xml.internal.security.Init.init(); // retrieve Algorithm Attribute from ds:Transform
alreadyInitialized = true; String algorithmURI = element.getAttributeNS(null, Constants._ATT_ALGORITHM);
if (algorithmURI == null || algorithmURI.length() == 0) {
Object exArgs[] = { Constants._ATT_ALGORITHM, Constants._TAG_TRANSFORM };
throw new TransformationException("xml.WrongContent", exArgs);
}
Class<? extends TransformSpi> transformSpiClass = transformSpiHash.get(algorithmURI);
if (transformSpiClass == null) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException("signature.Transform.UnknownTransform", exArgs);
}
try {
transformSpi = transformSpiClass.newInstance();
} catch (InstantiationException ex) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException(
"signature.Transform.UnknownTransform", exArgs, ex
);
} catch (IllegalAccessException ex) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException(
"signature.Transform.UnknownTransform", exArgs, ex
);
} }
} }
/** /**
* Registers implementing class of the Transform algorithm with algorithmURI * Registers implementing class of the Transform algorithm with algorithmURI
* *
* @param algorithmURI algorithmURI URI representation of * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>
* <code>Transform algorithm</code> will be specified as parameter of
* {@link #getInstance(Document, String)}, when generate. </br>
* @param implementingClass <code>implementingClass</code> the implementing * @param implementingClass <code>implementingClass</code> the implementing
* class of {@link TransformSpi} * class of {@link TransformSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
* is already registered * is already registered
*/ */
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass) public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException { throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
InvalidTransformException {
// are we already registered? // are we already registered?
Class<? extends TransformSpi> registeredClass = getImplementingClass(algorithmURI); Class<? extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
if ((registeredClass != null) ) { if (transformSpi != null) {
Object exArgs[] = { algorithmURI, registeredClass }; Object exArgs[] = { algorithmURI, transformSpi };
throw new AlgorithmAlreadyRegisteredException( throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
"algorithm.alreadyRegistered", exArgs);
} }
Class<? extends TransformSpi> transformSpiClass =
(Class<? extends TransformSpi>)
ClassLoaderUtils.loadClass(implementingClass, Transform.class);
transformSpiHash.put(algorithmURI, transformSpiClass);
}
ClassLoader cl = Thread.currentThread().getContextClassLoader(); /**
* Registers implementing class of the Transform algorithm with algorithmURI
try { *
transformClassHash.put * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>
(algorithmURI, Class.forName(implementingClass, true, cl)); * @param implementingClass <code>implementingClass</code> the implementing
} catch (ClassNotFoundException e) { * class of {@link TransformSpi}
throw new RuntimeException(e); * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
* is already registered
*/
public static void register(String algorithmURI, Class<? extends TransformSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException {
// are we already registered?
Class<? extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
if (transformSpi != null) {
Object exArgs[] = { algorithmURI, transformSpi };
throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
} }
transformSpiHash.put(algorithmURI, implementingClass);
}
/**
* This method registers the default algorithms.
*/
public static void registerDefaultAlgorithms() {
transformSpiHash.put(
Transforms.TRANSFORM_BASE64_DECODE, TransformBase64Decode.class
);
transformSpiHash.put(
Transforms.TRANSFORM_C14N_OMIT_COMMENTS, TransformC14N.class
);
transformSpiHash.put(
Transforms.TRANSFORM_C14N_WITH_COMMENTS, TransformC14NWithComments.class
);
transformSpiHash.put(
Transforms.TRANSFORM_C14N11_OMIT_COMMENTS, TransformC14N11.class
);
transformSpiHash.put(
Transforms.TRANSFORM_C14N11_WITH_COMMENTS, TransformC14N11_WithComments.class
);
transformSpiHash.put(
Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, TransformC14NExclusive.class
);
transformSpiHash.put(
Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS, TransformC14NExclusiveWithComments.class
);
transformSpiHash.put(
Transforms.TRANSFORM_XPATH, TransformXPath.class
);
transformSpiHash.put(
Transforms.TRANSFORM_ENVELOPED_SIGNATURE, TransformEnvelopedSignature.class
);
transformSpiHash.put(
Transforms.TRANSFORM_XSLT, TransformXSLT.class
);
transformSpiHash.put(
Transforms.TRANSFORM_XPATH2FILTER, TransformXPath2Filter.class
);
} }
/** /**
...@@ -255,8 +264,7 @@ public final class Transform extends SignatureElementProxy { ...@@ -255,8 +264,7 @@ public final class Transform extends SignatureElementProxy {
* @return the URI representation of Transformation algorithm * @return the URI representation of Transformation algorithm
*/ */
public String getURI() { public String getURI() {
return this._constructionElement.getAttributeNS return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
(null, Constants._ATT_ALGORITHM);
} }
/** /**
...@@ -272,30 +280,15 @@ public final class Transform extends SignatureElementProxy { ...@@ -272,30 +280,15 @@ public final class Transform extends SignatureElementProxy {
* @throws TransformationException * @throws TransformationException
*/ */
public XMLSignatureInput performTransform(XMLSignatureInput input) public XMLSignatureInput performTransform(XMLSignatureInput input)
throws IOException, CanonicalizationException, throws IOException, CanonicalizationException,
InvalidCanonicalizerException, TransformationException { InvalidCanonicalizerException, TransformationException {
return performTransform(input, null);
XMLSignatureInput result = null;
try {
result = transformSpi.enginePerformTransform(input, this);
} catch (ParserConfigurationException ex) {
Object exArgs[] = { this.getURI(), "ParserConfigurationException" };
throw new CanonicalizationException(
"signature.Transform.ErrorDuringTransform", exArgs, ex);
} catch (SAXException ex) {
Object exArgs[] = { this.getURI(), "SAXException" };
throw new CanonicalizationException(
"signature.Transform.ErrorDuringTransform", exArgs, ex);
}
return result;
} }
/** /**
* Transforms the input, and generates {@link XMLSignatureInput} as output. * Transforms the input, and generates {@link XMLSignatureInput} as output.
* *
* @param input input {@link XMLSignatureInput} which can supplied Octet * @param input input {@link XMLSignatureInput} which can supplied Octect
* Stream and NodeSet as Input of Transformation * Stream and NodeSet as Input of Transformation
* @param os where to output the result of the last transformation * @param os where to output the result of the last transformation
* @return the {@link XMLSignatureInput} class as the result of * @return the {@link XMLSignatureInput} class as the result of
...@@ -305,10 +298,10 @@ public final class Transform extends SignatureElementProxy { ...@@ -305,10 +298,10 @@ public final class Transform extends SignatureElementProxy {
* @throws InvalidCanonicalizerException * @throws InvalidCanonicalizerException
* @throws TransformationException * @throws TransformationException
*/ */
public XMLSignatureInput performTransform(XMLSignatureInput input, public XMLSignatureInput performTransform(
OutputStream os) throws IOException, CanonicalizationException, XMLSignatureInput input, OutputStream os
) throws IOException, CanonicalizationException,
InvalidCanonicalizerException, TransformationException { InvalidCanonicalizerException, TransformationException {
XMLSignatureInput result = null; XMLSignatureInput result = null;
try { try {
...@@ -326,44 +319,52 @@ public final class Transform extends SignatureElementProxy { ...@@ -326,44 +319,52 @@ public final class Transform extends SignatureElementProxy {
return result; return result;
} }
/** /** @inheritDoc */
* Method getImplementingClass public String getBaseLocalName() {
* return Constants._TAG_TRANSFORM;
* @param URI
* @return The name of the class implementing the URI.
*/
@SuppressWarnings("unchecked")
private static Class<? extends TransformSpi> getImplementingClass(String URI) {
return (Class<? extends TransformSpi>)transformClassHash.get(URI);
} }
private static TransformSpi getTransformSpi(String URI) /**
* Initialize the transform object.
*/
private TransformSpi initializeTransform(String algorithmURI, NodeList contextNodes)
throws InvalidTransformException { throws InvalidTransformException {
this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
Class<? extends TransformSpi> transformSpiClass = transformSpiHash.get(algorithmURI);
if (transformSpiClass == null) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException("signature.Transform.UnknownTransform", exArgs);
}
TransformSpi newTransformSpi = null;
try { try {
TransformSpi value = transformSpiHash.get(URI); newTransformSpi = transformSpiClass.newInstance();
if (value != null) {
return value;
}
Class<? extends TransformSpi> cl = getImplementingClass(URI);
if (cl != null) {
TransformSpi tr = cl.newInstance();
transformSpiHash.put(URI, tr);
return tr;
}
} catch (InstantiationException ex) { } catch (InstantiationException ex) {
Object exArgs[] = { URI }; Object exArgs[] = { algorithmURI };
throw new InvalidTransformException( throw new InvalidTransformException(
"signature.Transform.UnknownTransform", exArgs, ex); "signature.Transform.UnknownTransform", exArgs, ex
);
} catch (IllegalAccessException ex) { } catch (IllegalAccessException ex) {
Object exArgs[] = { URI }; Object exArgs[] = { algorithmURI };
throw new InvalidTransformException( throw new InvalidTransformException(
"signature.Transform.UnknownTransform", exArgs, ex); "signature.Transform.UnknownTransform", exArgs, ex
);
} }
return null;
}
/** @inheritDoc */ if (log.isLoggable(java.util.logging.Level.FINE)) {
public String getBaseLocalName() { log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
return Constants._TAG_TRANSFORM; + newTransformSpi.getClass() + "\"");
log.log(java.util.logging.Level.FINE, "The NodeList is " + contextNodes);
}
// give it to the current document
if (contextNodes != null) {
for (int i = 0; i < contextNodes.getLength(); i++) {
this._constructionElement.appendChild(contextNodes.item(i).cloneNode(true));
}
}
return newTransformSpi;
} }
} }
...@@ -158,8 +158,7 @@ public class Transforms extends SignatureElementProxy { ...@@ -158,8 +158,7 @@ public class Transforms extends SignatureElementProxy {
if (log.isLoggable(java.util.logging.Level.FINE)) if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
Transform transform = Transform transform = new Transform(this._doc, transformURI);
Transform.getInstance(this._doc, transformURI);
this.addTransform(transform); this.addTransform(transform);
} catch (InvalidTransformException ex) { } catch (InvalidTransformException ex) {
...@@ -184,8 +183,7 @@ public class Transforms extends SignatureElementProxy { ...@@ -184,8 +183,7 @@ public class Transforms extends SignatureElementProxy {
if (log.isLoggable(java.util.logging.Level.FINE)) if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
Transform transform = Transform transform = new Transform(this._doc, transformURI, contextElement);
Transform.getInstance(this._doc, transformURI, contextElement);
this.addTransform(transform); this.addTransform(transform);
} catch (InvalidTransformException ex) { } catch (InvalidTransformException ex) {
...@@ -207,8 +205,7 @@ public class Transforms extends SignatureElementProxy { ...@@ -207,8 +205,7 @@ public class Transforms extends SignatureElementProxy {
throws TransformationException { throws TransformationException {
try { try {
Transform transform = Transform transform = new Transform(this._doc, transformURI, contextNodes);
Transform.getInstance(this._doc, transformURI, contextNodes);
this.addTransform(transform); this.addTransform(transform);
} catch (InvalidTransformException ex) { } catch (InvalidTransformException ex) {
throw new TransformationException("empty", ex); throw new TransformationException("empty", ex);
......
...@@ -26,6 +26,7 @@ import java.io.BufferedInputStream; ...@@ -26,6 +26,7 @@ import java.io.BufferedInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
...@@ -145,11 +146,13 @@ public class TransformBase64Decode extends TransformSpi { ...@@ -145,11 +146,13 @@ public class TransformBase64Decode extends TransformSpi {
} }
try { try {
//Exceptional case there is current not text case testing this(Before it was a // Exceptional case there is current not text case testing this
//a common case). // (before it was a a common case).
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
Boolean.TRUE);
Document doc = Document doc =
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( dbf.newDocumentBuilder().parse(input.getOctetStream());
input.getOctetStream());
Element rootNode = doc.getDocumentElement(); Element rootNode = doc.getDocumentElement();
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
...@@ -157,13 +160,13 @@ public class TransformBase64Decode extends TransformSpi { ...@@ -157,13 +160,13 @@ public class TransformBase64Decode extends TransformSpi {
byte[] decodedBytes = Base64.decode(sb.toString()); byte[] decodedBytes = Base64.decode(sb.toString());
return new XMLSignatureInput(decodedBytes); return new XMLSignatureInput(decodedBytes);
} catch (ParserConfigurationException e) { } catch (ParserConfigurationException e) {
throw new TransformationException("c14n.Canonicalizer.Exception",e); throw new TransformationException("c14n.Canonicalizer.Exception",e);
} catch (SAXException e) { } catch (SAXException e) {
throw new TransformationException("SAX exception", e); throw new TransformationException("SAX exception", e);
} }
} catch (Base64DecodingException e) { } catch (Base64DecodingException e) {
throw new TransformationException("Base64Decoding", e); throw new TransformationException("Base64Decoding", e);
} }
} }
......
...@@ -26,6 +26,7 @@ import java.io.IOException; ...@@ -26,6 +26,7 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import javax.xml.XMLConstants;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerConfigurationException;
...@@ -109,7 +110,8 @@ public class TransformXSLT extends TransformSpi { ...@@ -109,7 +110,8 @@ public class TransformXSLT extends TransformSpi {
TransformerFactory tFactory = TransformerFactory.newInstance(); TransformerFactory tFactory = TransformerFactory.newInstance();
// Process XSLT stylesheets in a secure manner // Process XSLT stylesheets in a secure manner
tFactory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", Boolean.TRUE); tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
Boolean.TRUE);
/* /*
* This transform requires an octet stream as input. If the actual * This transform requires an octet stream as input. If the actual
* input is an XPath node-set, then the signature application should * input is an XPath node-set, then the signature application should
......
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.utils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* This class is extremely useful for loading resources and classes in a fault
* tolerant manner that works across different applications servers. Do not
* touch this unless you're a grizzled classloading guru veteran who is going to
* verify any change on 6 different application servers.
*/
public final class ClassLoaderUtils {
/** {@link org.apache.commons.logging} logging facility */
private static final java.util.logging.Logger log =
java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName());
private ClassLoaderUtils() {
}
/**
* Load a given resource. <p/> This method will try to load the resource
* using the following methods (in order):
* <ul>
* <li>From Thread.currentThread().getContextClassLoader()
* <li>From ClassLoaderUtil.class.getClassLoader()
* <li>callingClass.getClassLoader()
* </ul>
*
* @param resourceName The name of the resource to load
* @param callingClass The Class object of the calling object
*/
public static URL getResource(String resourceName, Class<?> callingClass) {
URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
if (url == null && resourceName.startsWith("/")) {
//certain classloaders need it without the leading /
url =
Thread.currentThread().getContextClassLoader().getResource(
resourceName.substring(1)
);
}
ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
if (cluClassloader == null) {
cluClassloader = ClassLoader.getSystemClassLoader();
}
if (url == null) {
url = cluClassloader.getResource(resourceName);
}
if (url == null && resourceName.startsWith("/")) {
//certain classloaders need it without the leading /
url = cluClassloader.getResource(resourceName.substring(1));
}
if (url == null) {
ClassLoader cl = callingClass.getClassLoader();
if (cl != null) {
url = cl.getResource(resourceName);
}
}
if (url == null) {
url = callingClass.getResource(resourceName);
}
if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
return getResource('/' + resourceName, callingClass);
}
return url;
}
/**
* Load a given resources. <p/> This method will try to load the resources
* using the following methods (in order):
* <ul>
* <li>From Thread.currentThread().getContextClassLoader()
* <li>From ClassLoaderUtil.class.getClassLoader()
* <li>callingClass.getClassLoader()
* </ul>
*
* @param resourceName The name of the resource to load
* @param callingClass The Class object of the calling object
*/
public static List<URL> getResources(String resourceName, Class<?> callingClass) {
List<URL> ret = new ArrayList<URL>();
Enumeration<URL> urls = new Enumeration<URL>() {
public boolean hasMoreElements() {
return false;
}
public URL nextElement() {
return null;
}
};
try {
urls = Thread.currentThread().getContextClassLoader().getResources(resourceName);
} catch (IOException e) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, e.getMessage(), e);
}
//ignore
}
if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
//certain classloaders need it without the leading /
try {
urls =
Thread.currentThread().getContextClassLoader().getResources(
resourceName.substring(1)
);
} catch (IOException e) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, e.getMessage(), e);
}
// ignore
}
}
ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
if (cluClassloader == null) {
cluClassloader = ClassLoader.getSystemClassLoader();
}
if (!urls.hasMoreElements()) {
try {
urls = cluClassloader.getResources(resourceName);
} catch (IOException e) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, e.getMessage(), e);
}
// ignore
}
}
if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
//certain classloaders need it without the leading /
try {
urls = cluClassloader.getResources(resourceName.substring(1));
} catch (IOException e) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, e.getMessage(), e);
}
// ignore
}
}
if (!urls.hasMoreElements()) {
ClassLoader cl = callingClass.getClassLoader();
if (cl != null) {
try {
urls = cl.getResources(resourceName);
} catch (IOException e) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, e.getMessage(), e);
}
// ignore
}
}
}
if (!urls.hasMoreElements()) {
URL url = callingClass.getResource(resourceName);
if (url != null) {
ret.add(url);
}
}
while (urls.hasMoreElements()) {
ret.add(urls.nextElement());
}
if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) {
return getResources('/' + resourceName, callingClass);
}
return ret;
}
/**
* This is a convenience method to load a resource as a stream. <p/> The
* algorithm used to find the resource is given in getResource()
*
* @param resourceName The name of the resource to load
* @param callingClass The Class object of the calling object
*/
public static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
URL url = getResource(resourceName, callingClass);
try {
return (url != null) ? url.openStream() : null;
} catch (IOException e) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, e.getMessage(), e);
}
return null;
}
}
/**
* Load a class with a given name. <p/> It will try to load the class in the
* following order:
* <ul>
* <li>From Thread.currentThread().getContextClassLoader()
* <li>Using the basic Class.forName()
* <li>From ClassLoaderUtil.class.getClassLoader()
* <li>From the callingClass.getClassLoader()
* </ul>
*
* @param className The name of the class to load
* @param callingClass The Class object of the calling object
* @throws ClassNotFoundException If the class cannot be found anywhere.
*/
public static Class<?> loadClass(String className, Class<?> callingClass)
throws ClassNotFoundException {
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
return cl.loadClass(className);
}
} catch (ClassNotFoundException e) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, e.getMessage(), e);
}
//ignore
}
return loadClass2(className, callingClass);
}
private static Class<?> loadClass2(String className, Class<?> callingClass)
throws ClassNotFoundException {
try {
return Class.forName(className);
} catch (ClassNotFoundException ex) {
try {
if (ClassLoaderUtils.class.getClassLoader() != null) {
return ClassLoaderUtils.class.getClassLoader().loadClass(className);
}
} catch (ClassNotFoundException exc) {
if (callingClass != null && callingClass.getClassLoader() != null) {
return callingClass.getClassLoader().loadClass(className);
}
}
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
}
throw ex;
}
}
}
...@@ -2,28 +2,28 @@ ...@@ -2,28 +2,28 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /**
* Copyright 1999-2008 The Apache Software Foundation. * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* http://www.apache.org/licenses/LICENSE-2.0 * with the License. You may obtain a copy of the License at
* *
* Unless required by applicable law or agreed to in writing, software * http://www.apache.org/licenses/LICENSE-2.0
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package com.sun.org.apache.xml.internal.security.utils; package com.sun.org.apache.xml.internal.security.utils;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.Map; import java.util.Map;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
...@@ -35,496 +35,475 @@ import org.w3c.dom.Node; ...@@ -35,496 +35,475 @@ import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.w3c.dom.Text; import org.w3c.dom.Text;
/** /**
* This is the base class to all Objects which have a direct 1:1 mapping to an * This is the base class to all Objects which have a direct 1:1 mapping to an
* Element in a particular namespace. * Element in a particular namespace.
*
* @author $Author: mullan $
*/ */
public abstract class ElementProxy { public abstract class ElementProxy {
/** {@link java.util.logging} logging facility */ protected static final java.util.logging.Logger log =
static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(ElementProxy.class.getName()); java.util.logging.Logger.getLogger(ElementProxy.class.getName());
/** /** Field constructionElement */
* Returns the namespace of the Elements of the sub-class. protected Element _constructionElement = null;
*
* @return the namespace of the Elements of the sub-class. /** Field baseURI */
*/ protected String _baseURI = null;
public abstract String getBaseNamespace();
/** Field doc */
/** protected Document _doc = null;
* Returns the localname of the Elements of the sub-class.
* /** Field prefixMappings */
* @return the localname of the Elements of the sub-class. private static Map<String, String> prefixMappings = new ConcurrentHashMap<String, String>();
*/
public abstract String getBaseLocalName(); /**
* Constructor ElementProxy
/** Field _constructionElement */ *
protected Element _constructionElement = null; */
public ElementProxy() {
/** Field _baseURI */ }
protected String _baseURI = null;
/** Field _doc */
protected Document _doc = null;
/**
* Constructor ElementProxy
*
*/
public ElementProxy() {
}
/**
* Constructor ElementProxy
*
* @param doc
*/
public ElementProxy(Document doc) {
if (doc == null) {
throw new RuntimeException("Document is null");
}
this._doc = doc;
this._constructionElement = createElementForFamilyLocal(this._doc,
this.getBaseNamespace(), this.getBaseLocalName());
}
protected Element createElementForFamilyLocal(Document doc, String namespace,
String localName) {
Element result = null;
if (namespace == null) {
result = doc.createElementNS(null, localName);
} else {
String baseName=this.getBaseNamespace();
String prefix=ElementProxy.getDefaultPrefix(baseName);
if ((prefix == null) || (prefix.length() == 0)) {
result = doc.createElementNS(namespace, localName);
result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns",
namespace);
} else {
String tagName=null;
String defaultPrefixNaming=ElementProxy.getDefaultPrefixBindings(baseName);
StringBuffer sb=new StringBuffer(prefix);
sb.append(':');
sb.append(localName);
tagName=sb.toString();
result = doc.createElementNS(namespace, tagName );
result.setAttributeNS(Constants.NamespaceSpecNS, defaultPrefixNaming,
namespace);
}
}
return result;
}
/**
* Constructor ElementProxy
*
* @param doc
*/
public ElementProxy(Document doc) {
if (doc == null) {
throw new RuntimeException("Document is null");
}
this._doc = doc;
this._constructionElement =
createElementForFamilyLocal(this._doc, this.getBaseNamespace(), this.getBaseLocalName());
}
/** /**
* This method creates an Element in a given namespace with a given localname. * Constructor ElementProxy
* It uses the {@link ElementProxy#getDefaultPrefix} method to decide whether *
* a particular prefix is bound to that namespace. * @param element
* <BR /> * @param BaseURI
* This method was refactored out of the constructor. * @throws XMLSecurityException
* */
* @param doc public ElementProxy(Element element, String BaseURI) throws XMLSecurityException {
* @param namespace if (element == null) {
* @param localName throw new XMLSecurityException("ElementProxy.nullElement");
* @return The element created. }
*/
public static Element createElementForFamily(Document doc, String namespace, if (log.isLoggable(java.util.logging.Level.FINE)) {
String localName) { log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")");
//Element nscontext = XMLUtils.createDSctx(doc, "x", namespace); }
Element result = null;
String prefix = ElementProxy.getDefaultPrefix(namespace); this._doc = element.getOwnerDocument();
this._constructionElement = element;
if (namespace == null) { this._baseURI = BaseURI;
result = doc.createElementNS(null, localName);
} else { this.guaranteeThatElementInCorrectSpace();
if ((prefix == null) || (prefix.length() == 0)) { }
result = doc.createElementNS(namespace, localName);
/**
result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", * Returns the namespace of the Elements of the sub-class.
namespace); *
} else { * @return the namespace of the Elements of the sub-class.
result = doc.createElementNS(namespace, prefix + ":" + localName); */
public abstract String getBaseNamespace();
result.setAttributeNS(Constants.NamespaceSpecNS, ElementProxy.getDefaultPrefixBindings(namespace),
namespace); /**
} * Returns the localname of the Elements of the sub-class.
} *
* @return the localname of the Elements of the sub-class.
return result; */
} public abstract String getBaseLocalName();
/**
* Method setElement protected Element createElementForFamilyLocal(
* Document doc, String namespace, String localName
* @param element ) {
* @param BaseURI Element result = null;
* @throws XMLSecurityException if (namespace == null) {
*/ result = doc.createElementNS(null, localName);
public void setElement(Element element, String BaseURI) } else {
throws XMLSecurityException { String baseName = this.getBaseNamespace();
String prefix = ElementProxy.getDefaultPrefix(baseName);
if (element == null) { if ((prefix == null) || (prefix.length() == 0)) {
throw new XMLSecurityException("ElementProxy.nullElement"); result = doc.createElementNS(namespace, localName);
} result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
} else {
if (log.isLoggable(java.util.logging.Level.FINE)) { result = doc.createElementNS(namespace, prefix + ":" + localName);
log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\""); result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace);
}
this._doc = element.getOwnerDocument();
this._constructionElement = element;
this._baseURI = BaseURI;
}
/**
* Constructor ElementProxy
*
* @param element
* @param BaseURI
* @throws XMLSecurityException
*/
public ElementProxy(Element element, String BaseURI)
throws XMLSecurityException {
if (element == null) {
throw new XMLSecurityException("ElementProxy.nullElement");
}
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI
+ "\")");
}
this._doc = element.getOwnerDocument();
this._constructionElement = element;
this._baseURI = BaseURI;
this.guaranteeThatElementInCorrectSpace();
}
/**
* Returns the Element which was constructed by the Object.
*
* @return the Element which was constructed by the Object.
*/
public final Element getElement() {
return this._constructionElement;
}
/**
* Returns the Element plus a leading and a trailing CarriageReturn Text node.
*
* @return the Element which was constructed by the Object.
*/
public final NodeList getElementPlusReturns() {
HelperNodeList nl = new HelperNodeList();
nl.appendChild(this._doc.createTextNode("\n"));
nl.appendChild(this.getElement());
nl.appendChild(this._doc.createTextNode("\n"));
return nl;
}
/**
* Method getDocument
*
* @return the Document where this element is contained.
*/
public Document getDocument() {
return this._doc;
}
/**
* Method getBaseURI
*
* @return the base uri of the namespace of this element
*/
public String getBaseURI() {
return this._baseURI;
}
static ElementChecker checker = new ElementCheckerImpl.InternedNsChecker();
/**
* Method guaranteeThatElementInCorrectSpace
*
* @throws XMLSecurityException
*/
void guaranteeThatElementInCorrectSpace()
throws XMLSecurityException {
checker.guaranteeThatElementInCorrectSpace(this,this._constructionElement);
}
/**
* Method setVal
*
* @param bi
* @param localname
*/
public void addBigIntegerElement(BigInteger bi, String localname) {
if (bi != null) {
Element e = XMLUtils.createElementInSignatureSpace(this._doc,
localname);
Base64.fillElementWithBigInteger(e, bi);
this._constructionElement.appendChild(e);
XMLUtils.addReturnToElement(this._constructionElement);
}
}
/**
* Method addBase64Element
*
* @param bytes
* @param localname
*/
public void addBase64Element(byte[] bytes, String localname) {
if (bytes != null) {
Element e = Base64.encodeToElement(this._doc, localname, bytes);
this._constructionElement.appendChild(e);
if (!XMLUtils.ignoreLineBreaks()) {
this._constructionElement.appendChild(this._doc.createTextNode("\n"));
}
}
}
/**
* Method addTextElement
*
* @param text
* @param localname
*/
public void addTextElement(String text, String localname) {
Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
Text t = this._doc.createTextNode(text);
e.appendChild(t);
this._constructionElement.appendChild(e);
XMLUtils.addReturnToElement(this._constructionElement);
}
/**
* Method addBase64Text
*
* @param bytes
*/
public void addBase64Text(byte[] bytes) {
if (bytes != null) {
Text t = XMLUtils.ignoreLineBreaks()
? this._doc.createTextNode(Base64.encode(bytes))
: this._doc.createTextNode("\n" + Base64.encode(bytes) + "\n");
this._constructionElement.appendChild(t);
}
}
/**
* Method addText
*
* @param text
*/
public void addText(String text) {
if (text != null) {
Text t = this._doc.createTextNode(text);
this._constructionElement.appendChild(t);
}
}
/**
* Method getVal
*
* @param localname
* @param namespace
* @return The biginter contained in the given element
* @throws Base64DecodingException
*/
public BigInteger getBigIntegerFromChildElement(
String localname, String namespace) throws Base64DecodingException {
return Base64.decodeBigIntegerFromText(
XMLUtils.selectNodeText(this._constructionElement.getFirstChild(),
namespace,localname,0));
}
/**
* Method getBytesFromChildElement
* @deprecated
* @param localname
* @param namespace
* @return the bytes
* @throws XMLSecurityException
*/
@Deprecated
public byte[] getBytesFromChildElement(String localname, String namespace)
throws XMLSecurityException {
Element e =
XMLUtils.selectNode(
this._constructionElement.getFirstChild(),
namespace,
localname,
0);
return Base64.decode(e);
}
/**
* Method getTextFromChildElement
*
* @param localname
* @param namespace
* @return the Text of the textNode
*/
public String getTextFromChildElement(String localname, String namespace) {
return XMLUtils.selectNode(
this._constructionElement.getFirstChild(),
namespace,
localname,
0).getFirstChild().getNodeValue();
}
/**
* Method getBytesFromTextChild
*
* @return The base64 bytes from the text children of this element
* @throws XMLSecurityException
*/
public byte[] getBytesFromTextChild() throws XMLSecurityException {
return Base64.decode
(XMLUtils.getFullTextChildrenFromElement(this._constructionElement));
}
/**
* Method getTextFromTextChild
*
* @return the Text obtained by concatenating all the text nodes of this
* element
*/
public String getTextFromTextChild() {
return XMLUtils.getFullTextChildrenFromElement(this._constructionElement);
}
/**
* Method length
*
* @param namespace
* @param localname
* @return the number of elements {namespace}:localname under this element
*/
public int length(String namespace, String localname) {
int number=0;
Node sibling=this._constructionElement.getFirstChild();
while (sibling!=null) {
if (localname.equals(sibling.getLocalName())
&&
namespace==sibling.getNamespaceURI() ) {
number++;
}
sibling=sibling.getNextSibling();
} }
return number; }
} return result;
}
/**
* Adds an xmlns: definition to the Element. This can be called as follows:
*
* <PRE>
* // set namespace with ds prefix
* xpathContainer.setXPathNamespaceContext("ds", "http://www.w3.org/2000/09/xmldsig#");
* xpathContainer.setXPathNamespaceContext("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
* </PRE>
*
* @param prefix
* @param uri
* @throws XMLSecurityException
*/
public void setXPathNamespaceContext(String prefix, String uri)
throws XMLSecurityException {
String ns;
if ((prefix == null) || (prefix.length() == 0)) {
throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
} else if (prefix.equals("xmlns")) {
throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
} else if (prefix.startsWith("xmlns:")) {
ns = prefix;//"xmlns:" + prefix.substring("xmlns:".length());
} else {
ns = "xmlns:" + prefix;
}
Attr a = this._constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns);
if (a != null) {
if (!a.getNodeValue().equals(uri)) {
Object exArgs[] = { ns,
this._constructionElement.getAttributeNS(null,
ns) };
throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI",
exArgs);
}
return;
}
this._constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns,
uri);
}
/** Field _prefixMappings */
static Map<String, String> _prefixMappings = new HashMap<String,String>();
static Map<String, String> _prefixMappingsBindings = new HashMap<String,String>();
/** /**
* Method setDefaultPrefix * This method creates an Element in a given namespace with a given localname.
* It uses the {@link ElementProxy#getDefaultPrefix} method to decide whether
* a particular prefix is bound to that namespace.
* <BR />
* This method was refactored out of the constructor.
*
* @param doc
* @param namespace
* @param localName
* @return The element created.
*/
public static Element createElementForFamily(Document doc, String namespace, String localName) {
Element result = null;
String prefix = ElementProxy.getDefaultPrefix(namespace);
if (namespace == null) {
result = doc.createElementNS(null, localName);
} else {
if ((prefix == null) || (prefix.length() == 0)) {
result = doc.createElementNS(namespace, localName);
result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
} else {
result = doc.createElementNS(namespace, prefix + ":" + localName);
result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace);
}
}
return result;
}
/**
* Method setElement
*
* @param element
* @param BaseURI
* @throws XMLSecurityException
*/
public void setElement(Element element, String BaseURI) throws XMLSecurityException {
if (element == null) {
throw new XMLSecurityException("ElementProxy.nullElement");
}
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\"");
}
this._doc = element.getOwnerDocument();
this._constructionElement = element;
this._baseURI = BaseURI;
}
/**
* Returns the Element which was constructed by the Object.
*
* @return the Element which was constructed by the Object.
*/
public final Element getElement() {
return this._constructionElement;
}
/**
* Returns the Element plus a leading and a trailing CarriageReturn Text node.
*
* @return the Element which was constructed by the Object.
*/
public final NodeList getElementPlusReturns() {
HelperNodeList nl = new HelperNodeList();
nl.appendChild(this._doc.createTextNode("\n"));
nl.appendChild(this.getElement());
nl.appendChild(this._doc.createTextNode("\n"));
return nl;
}
/**
* Method getDocument
*
* @return the Document where this element is contained.
*/
public Document getDocument() {
return this._doc;
}
/**
* Method getBaseURI
*
* @return the base uri of the namespace of this element
*/
public String getBaseURI() {
return this._baseURI;
}
/**
* Method guaranteeThatElementInCorrectSpace
*
* @throws XMLSecurityException
*/
void guaranteeThatElementInCorrectSpace() throws XMLSecurityException {
String expectedLocalName = this.getBaseLocalName();
String expectedNamespaceUri = this.getBaseNamespace();
String actualLocalName = this._constructionElement.getLocalName();
String actualNamespaceUri = this._constructionElement.getNamespaceURI();
if(!expectedNamespaceUri.equals(actualNamespaceUri)
&& !expectedLocalName.equals(actualLocalName)) {
Object exArgs[] = { actualNamespaceUri + ":" + actualLocalName,
expectedNamespaceUri + ":" + expectedLocalName};
throw new XMLSecurityException("xml.WrongElement", exArgs);
}
}
/**
* Method addBigIntegerElement
*
* @param bi
* @param localname
*/
public void addBigIntegerElement(BigInteger bi, String localname) {
if (bi != null) {
Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
Base64.fillElementWithBigInteger(e, bi);
this._constructionElement.appendChild(e);
XMLUtils.addReturnToElement(this._constructionElement);
}
}
/**
* Method addBase64Element
*
* @param bytes
* @param localname
*/
public void addBase64Element(byte[] bytes, String localname) {
if (bytes != null) {
Element e = Base64.encodeToElement(this._doc, localname, bytes);
this._constructionElement.appendChild(e);
if (!XMLUtils.ignoreLineBreaks()) {
this._constructionElement.appendChild(this._doc.createTextNode("\n"));
}
}
}
/**
* Method addTextElement
* *
* @param text
* @param localname
*/
public void addTextElement(String text, String localname) {
Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
Text t = this._doc.createTextNode(text);
e.appendChild(t);
this._constructionElement.appendChild(e);
XMLUtils.addReturnToElement(this._constructionElement);
}
/**
* Method addBase64Text
*
* @param bytes
*/
public void addBase64Text(byte[] bytes) {
if (bytes != null) {
Text t = XMLUtils.ignoreLineBreaks()
? this._doc.createTextNode(Base64.encode(bytes))
: this._doc.createTextNode("\n" + Base64.encode(bytes) + "\n");
this._constructionElement.appendChild(t);
}
}
/**
* Method addText
*
* @param text
*/
public void addText(String text) {
if (text != null) {
Text t = this._doc.createTextNode(text);
this._constructionElement.appendChild(t);
}
}
/**
* Method getVal
*
* @param localname
* @param namespace * @param namespace
* @return The biginteger contained in the given element
* @throws Base64DecodingException
*/
public BigInteger getBigIntegerFromChildElement(
String localname, String namespace
) throws Base64DecodingException {
return Base64.decodeBigIntegerFromText(
XMLUtils.selectNodeText(
this._constructionElement.getFirstChild(), namespace, localname, 0
)
);
}
/**
* Method getBytesFromChildElement
* @deprecated
* @param localname
* @param namespace
* @return the bytes
* @throws XMLSecurityException
*/
@Deprecated
public byte[] getBytesFromChildElement(String localname, String namespace)
throws XMLSecurityException {
Element e =
XMLUtils.selectNode(
this._constructionElement.getFirstChild(), namespace, localname, 0
);
return Base64.decode(e);
}
/**
* Method getTextFromChildElement
*
* @param localname
* @param namespace
* @return the Text of the textNode
*/
public String getTextFromChildElement(String localname, String namespace) {
return XMLUtils.selectNode(
this._constructionElement.getFirstChild(),
namespace,
localname,
0).getTextContent();
}
/**
* Method getBytesFromTextChild
*
* @return The base64 bytes from the text children of this element
* @throws XMLSecurityException
*/
public byte[] getBytesFromTextChild() throws XMLSecurityException {
return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this._constructionElement));
}
/**
* Method getTextFromTextChild
*
* @return the Text obtained by concatenating all the text nodes of this
* element
*/
public String getTextFromTextChild() {
return XMLUtils.getFullTextChildrenFromElement(this._constructionElement);
}
/**
* Method length
*
* @param namespace
* @param localname
* @return the number of elements {namespace}:localname under this element
*/
public int length(String namespace, String localname) {
int number = 0;
Node sibling = this._constructionElement.getFirstChild();
while (sibling != null) {
if (localname.equals(sibling.getLocalName())
&& namespace.equals(sibling.getNamespaceURI())) {
number++;
}
sibling = sibling.getNextSibling();
}
return number;
}
/**
* Adds an xmlns: definition to the Element. This can be called as follows:
*
* <PRE>
* // set namespace with ds prefix
* xpathContainer.setXPathNamespaceContext("ds", "http://www.w3.org/2000/09/xmldsig#");
* xpathContainer.setXPathNamespaceContext("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
* </PRE>
*
* @param prefix * @param prefix
* @param uri
* @throws XMLSecurityException * @throws XMLSecurityException
*/ */
public static void setDefaultPrefix(String namespace, String prefix) public void setXPathNamespaceContext(String prefix, String uri)
throws XMLSecurityException { throws XMLSecurityException {
String ns;
if ((prefix == null) || (prefix.length() == 0)) {
throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
} else if (prefix.equals("xmlns")) {
throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
} else if (prefix.startsWith("xmlns:")) {
ns = prefix;//"xmlns:" + prefix.substring("xmlns:".length());
} else {
ns = "xmlns:" + prefix;
}
if (ElementProxy._prefixMappings.containsValue(prefix)) { Attr a = this._constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns);
Object storedNamespace=ElementProxy._prefixMappings.get(namespace); if (a != null) {
if (!storedNamespace.equals(prefix)) { if (!a.getNodeValue().equals(uri)) {
Object exArgs[] = { prefix, namespace, storedNamespace }; Object exArgs[] = { ns, this._constructionElement.getAttributeNS(null, ns) };
throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI", exArgs);
}
return;
}
this._constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri);
}
/**
* Method setDefaultPrefix
*
* @param namespace
* @param prefix
* @throws XMLSecurityException
*/
public static void setDefaultPrefix(String namespace, String prefix)
throws XMLSecurityException {
if (prefixMappings.containsValue(prefix)) {
String storedPrefix = prefixMappings.get(namespace);
if (!storedPrefix.equals(prefix)) {
Object exArgs[] = { prefix, namespace, storedPrefix };
throw new XMLSecurityException("prefix.AlreadyAssigned", exArgs); throw new XMLSecurityException("prefix.AlreadyAssigned", exArgs);
} }
} }
if (Constants.SignatureSpecNS.equals(namespace)) { if (Constants.SignatureSpecNS.equals(namespace)) {
XMLUtils.dsPrefix=prefix; XMLUtils.setDsPrefix(prefix);
} }
ElementProxy._prefixMappings.put(namespace, prefix.intern()); if (EncryptionConstants.EncryptionSpecNS.equals(namespace)) {
if (prefix.length() == 0) { XMLUtils.setXencPrefix(prefix);
ElementProxy._prefixMappingsBindings.put(namespace, "xmlns");
} else {
ElementProxy._prefixMappingsBindings.put(namespace, ("xmlns:"+prefix).intern());
} }
} prefixMappings.put(namespace, prefix);
}
/**
* This method registers the default prefixes.
*/
public static void registerDefaultPrefixes() throws XMLSecurityException {
setDefaultPrefix("http://www.w3.org/2000/09/xmldsig#", "ds");
setDefaultPrefix("http://www.w3.org/2001/04/xmlenc#", "xenc");
setDefaultPrefix("http://www.w3.org/2009/xmlenc11#", "xenc11");
setDefaultPrefix("http://www.xmlsecurity.org/experimental#", "experimental");
setDefaultPrefix("http://www.w3.org/2002/04/xmldsig-filter2", "dsig-xpath-old");
setDefaultPrefix("http://www.w3.org/2002/06/xmldsig-filter2", "dsig-xpath");
setDefaultPrefix("http://www.w3.org/2001/10/xml-exc-c14n#", "ec");
setDefaultPrefix(
"http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter", "xx"
);
}
/** /**
* Method getDefaultPrefix * Method getDefaultPrefix
...@@ -533,10 +512,7 @@ public abstract class ElementProxy { ...@@ -533,10 +512,7 @@ public abstract class ElementProxy {
* @return the default prefix bind to this element. * @return the default prefix bind to this element.
*/ */
public static String getDefaultPrefix(String namespace) { public static String getDefaultPrefix(String namespace) {
return ElementProxy._prefixMappings.get(namespace); return prefixMappings.get(namespace);
} }
public static String getDefaultPrefixBindings(String namespace) {
return ElementProxy._prefixMappingsBindings.get(namespace);
}
} }
...@@ -2,21 +2,23 @@ ...@@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /**
* Copyright 1999-2004 The Apache Software Foundation. * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* http://www.apache.org/licenses/LICENSE-2.0 * with the License. You may obtain a copy of the License at
* *
* Unless required by applicable law or agreed to in writing, software * http://www.apache.org/licenses/LICENSE-2.0
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package com.sun.org.apache.xml.internal.security.utils; package com.sun.org.apache.xml.internal.security.utils;
...@@ -31,202 +33,136 @@ import java.util.ResourceBundle; ...@@ -31,202 +33,136 @@ import java.util.ResourceBundle;
*/ */
public class I18n { public class I18n {
/** Field NOT_INITIALIZED_MSG */ /** Field NOT_INITIALIZED_MSG */
public static final String NOT_INITIALIZED_MSG = public static final String NOT_INITIALIZED_MSG =
"You must initialize the xml-security library correctly before you use it. " "You must initialize the xml-security library correctly before you use it. "
+ "Call the static method \"com.sun.org.apache.xml.internal.security.Init.init();\" to do that " + "Call the static method \"com.sun.org.apache.xml.internal.security.Init.init();\" to do that "
+ "before you use any functionality from that library."; + "before you use any functionality from that library.";
/** Field defaultLanguageCode */ /** Field resourceBundle */
private static String defaultLanguageCode; // will be set in static{} block private static ResourceBundle resourceBundle;
/** Field defaultCountryCode */ /** Field alreadyInitialized */
private static String defaultCountryCode; // will be set in static{} block private static boolean alreadyInitialized = false;
/** Field resourceBundle */ /**
private static ResourceBundle resourceBundle = * Constructor I18n
ResourceBundle.getBundle *
(Constants.exceptionMessagesResourceBundleBase, Locale.US); */
private I18n() {
/** Field alreadyInitialized */ // we don't allow instantiation
private static boolean alreadyInitialized = false; }
/** Field _languageCode */ /**
private static String _languageCode = null; * Method translate
*
/** Field _countryCode */ * translates a message ID into an internationalized String, see alse
private static String _countryCode = null; * <CODE>XMLSecurityException.getExceptionMEssage()</CODE>. The strings are
* stored in the <CODE>ResourceBundle</CODE>, which is identified in
/** * <CODE>exceptionMessagesResourceBundleBase</CODE>
* Constructor I18n *
* * @param message
*/ * @param args is an <CODE>Object[]</CODE> array of strings which are inserted into
private I18n() { * the String which is retrieved from the <CODE>ResouceBundle</CODE>
* @return message translated
// we don't allow instantiation */
} public static String translate(String message, Object[] args) {
return getExceptionMessage(message, args);
/** }
* Method translate
* /**
* translates a message ID into an internationalized String, see alse * Method translate
* <CODE>XMLSecurityException.getExceptionMEssage()</CODE>. The strings are *
* stored in the <CODE>ResourceBundle</CODE>, which is identified in * translates a message ID into an internationalized String, see also
* <CODE>exceptionMessagesResourceBundleBase</CODE> * <CODE>XMLSecurityException.getExceptionMessage()</CODE>
* *
* @param message * @param message
* @param args is an <CODE>Object[]</CODE> array of strings which are inserted into the String which is retrieved from the <CODE>ResouceBundle</CODE> * @return message translated
* @return message translated */
*/ public static String translate(String message) {
public static String translate(String message, Object[] args) { return getExceptionMessage(message);
return getExceptionMessage(message, args); }
}
/**
/** * Method getExceptionMessage
* Method translate *
* * @param msgID
* translates a message ID into an internationalized String, see alse * @return message translated
* <CODE>XMLSecurityException.getExceptionMEssage()</CODE> *
* */
* @param message public static String getExceptionMessage(String msgID) {
* @return message translated try {
*/ return resourceBundle.getString(msgID);
public static String translate(String message) { } catch (Throwable t) {
return getExceptionMessage(message); if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) {
} return "No message with ID \"" + msgID
+ "\" found in resource bundle \""
/** + Constants.exceptionMessagesResourceBundleBase + "\"";
* Method getExceptionMessage }
* return I18n.NOT_INITIALIZED_MSG;
* @param msgID }
* @return message translated }
*
*/ /**
public static String getExceptionMessage(String msgID) { * Method getExceptionMessage
*
try { * @param msgID
String s = resourceBundle.getString(msgID); * @param originalException
* @return message translated
return s; */
} catch (Throwable t) { public static String getExceptionMessage(String msgID, Exception originalException) {
if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) { try {
return "No message with ID \"" + msgID Object exArgs[] = { originalException.getMessage() };
+ "\" found in resource bundle \"" return MessageFormat.format(resourceBundle.getString(msgID), exArgs);
+ Constants.exceptionMessagesResourceBundleBase + "\""; } catch (Throwable t) {
} if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) {
return I18n.NOT_INITIALIZED_MSG; return "No message with ID \"" + msgID
} + "\" found in resource bundle \""
} + Constants.exceptionMessagesResourceBundleBase
+ "\". Original Exception was a "
/** + originalException.getClass().getName() + " and message "
* Method getExceptionMessage + originalException.getMessage();
* }
* @param msgID return I18n.NOT_INITIALIZED_MSG;
* @param originalException }
* @return message translated }
*/
public static String getExceptionMessage(String msgID, /**
Exception originalException) { * Method getExceptionMessage
*
try { * @param msgID
Object exArgs[] = { originalException.getMessage() }; * @param exArgs
String s = MessageFormat.format(resourceBundle.getString(msgID), * @return message translated
exArgs); */
public static String getExceptionMessage(String msgID, Object exArgs[]) {
return s; try {
} catch (Throwable t) { return MessageFormat.format(resourceBundle.getString(msgID), exArgs);
if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) { } catch (Throwable t) {
return "No message with ID \"" + msgID if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) {
+ "\" found in resource bundle \"" return "No message with ID \"" + msgID
+ Constants.exceptionMessagesResourceBundleBase + "\" found in resource bundle \""
+ "\". Original Exception was a " + Constants.exceptionMessagesResourceBundleBase + "\"";
+ originalException.getClass().getName() + " and message " }
+ originalException.getMessage(); return I18n.NOT_INITIALIZED_MSG;
} }
return I18n.NOT_INITIALIZED_MSG; }
}
} /**
* Method init
/** *
* Method getExceptionMessage * @param languageCode
* * @param countryCode
* @param msgID */
* @param exArgs public synchronized static void init(String languageCode, String countryCode) {
* @return message translated if (alreadyInitialized) {
*/ return;
public static String getExceptionMessage(String msgID, Object exArgs[]) { }
try { I18n.resourceBundle =
String s = MessageFormat.format(resourceBundle.getString(msgID), ResourceBundle.getBundle(
exArgs); Constants.exceptionMessagesResourceBundleBase,
new Locale(languageCode, countryCode)
return s; );
} catch (Throwable t) { alreadyInitialized = true;
if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) { }
return "No message with ID \"" + msgID
+ "\" found in resource bundle \""
+ Constants.exceptionMessagesResourceBundleBase + "\"";
}
return I18n.NOT_INITIALIZED_MSG;
}
}
//
// Commented out because it modifies shared static
// state which could be maliciously called by untrusted code
//
// /**
// * Method init
// *
// * @param _defaultLanguageCode
// * @param _defaultCountryCode
// */
// public static void init(String _defaultLanguageCode,
// String _defaultCountryCode) {
//
// I18n.defaultLanguageCode = _defaultLanguageCode;
//
// if (I18n.defaultLanguageCode == null) {
// I18n.defaultLanguageCode = Locale.getDefault().getLanguage();
// }
//
// I18n.defaultCountryCode = _defaultCountryCode;
//
// if (I18n.defaultCountryCode == null) {
// I18n.defaultCountryCode = Locale.getDefault().getCountry();
// }
//
// initLocale(I18n.defaultLanguageCode, I18n.defaultCountryCode);
// }
//
// Commented out because it modifies shared static
// state which could be maliciously called by untrusted code
//
// /**
// * Method initLocale
// *
// * @param languageCode
// * @param countryCode
// */
// public static void initLocale(String languageCode, String countryCode) {
//
// if (alreadyInitialized && languageCode.equals(_languageCode)
// && countryCode.equals(_countryCode)) {
// return;
// }
//
// if ((languageCode != null) && (countryCode != null)
// && (languageCode.length() > 0) && (countryCode.length() > 0)) {
// _languageCode = languageCode;
// _countryCode = countryCode;
// } else {
// _countryCode = I18n.defaultCountryCode;
// _languageCode = I18n.defaultLanguageCode;
// }
//
// I18n.resourceBundle =
// ResourceBundle.getBundle(Constants.exceptionMessagesResourceBundleBase,
// new Locale(_languageCode, _countryCode));
// }
} }
...@@ -21,14 +21,15 @@ ...@@ -21,14 +21,15 @@
package com.sun.org.apache.xml.internal.security.utils; package com.sun.org.apache.xml.internal.security.utils;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
...@@ -60,6 +61,12 @@ public class XMLUtils { ...@@ -60,6 +61,12 @@ public class XMLUtils {
} }
}); });
private static volatile String dsPrefix = "ds";
private static volatile String xencPrefix = "xenc";
private static final java.util.logging.Logger log =
java.util.logging.Logger.getLogger(XMLUtils.class.getName());
/** /**
* Constructor XMLUtils * Constructor XMLUtils
* *
...@@ -68,6 +75,23 @@ public class XMLUtils { ...@@ -68,6 +75,23 @@ public class XMLUtils {
// we don't allow instantiation // we don't allow instantiation
} }
/**
* Set the prefix for the digital signature namespace
* @param prefix the new prefix for the digital signature namespace
*/
public static void setDsPrefix(String prefix) {
dsPrefix = prefix;
}
/**
* Set the prefix for the encryption namespace
* @param prefix the new prefix for the encryption namespace
*/
public static void setXencPrefix(String prefix) {
xencPrefix = prefix;
}
public static Element getNextElement(Node el) { public static Element getNextElement(Node el) {
while ((el!=null) && (el.getNodeType()!=Node.ELEMENT_NODE)) { while ((el!=null) && (el.getNodeType()!=Node.ELEMENT_NODE)) {
el=el.getNextSibling(); el=el.getNextSibling();
...@@ -230,9 +254,8 @@ public class XMLUtils { ...@@ -230,9 +254,8 @@ public class XMLUtils {
return sb.toString(); return sb.toString();
} }
static String dsPrefix=null;
static Map<String, String> namePrefixes=new HashMap<String, String>(); static Map<String, String> namePrefixes=new HashMap<String, String>();
/** /**
* Creates an Element in the XML Signature specification namespace. * Creates an Element in the XML Signature specification namespace.
* *
...@@ -261,31 +284,38 @@ public class XMLUtils { ...@@ -261,31 +284,38 @@ public class XMLUtils {
return doc.createElementNS(Constants.SignatureSpecNS, namePrefix); return doc.createElementNS(Constants.SignatureSpecNS, namePrefix);
} }
/** /**
* Returns true if the element is in XML Signature namespace and the local * Returns true if the element is in XML Signature namespace and the local
* name equals the supplied one. * name equals the supplied one.
* *
* @param element * @param element
* @param localName * @param localName
* @return true if the element is in XML Signature namespace and the local name equals the supplied one * @return true if the element is in XML Signature namespace and the local name equals the supplied one
*/ */
public static boolean elementIsInSignatureSpace(Element element, public static boolean elementIsInSignatureSpace(Element element, String localName) {
String localName) { if (element == null) {
return ElementProxy.checker.isNamespaceElement(element, localName, Constants.SignatureSpecNS); return false;
} }
/** return Constants.SignatureSpecNS.equals(element.getNamespaceURI())
* Returns true if the element is in XML Encryption namespace and the local && element.getLocalName().equals(localName);
* name equals the supplied one. }
*
* @param element /**
* @param localName * Returns true if the element is in XML Encryption namespace and the local
* @return true if the element is in XML Encryption namespace and the local name equals the supplied one * name equals the supplied one.
*/ *
public static boolean elementIsInEncryptionSpace(Element element, * @param element
String localName) { * @param localName
return ElementProxy.checker.isNamespaceElement(element, localName, EncryptionConstants.EncryptionSpecNS); * @return true if the element is in XML Encryption namespace and the local name equals the supplied one
} */
public static boolean elementIsInEncryptionSpace(Element element, String localName) {
if (element == null) {
return false;
}
return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI())
&& element.getLocalName().equals(localName);
}
/** /**
* This method returns the owner document of a particular node. * This method returns the owner document of a particular node.
...@@ -504,45 +534,45 @@ public class XMLUtils { ...@@ -504,45 +534,45 @@ public class XMLUtils {
} while (true); } while (true);
} }
/** /**
* @param sibling * @param sibling
* @param nodeName * @param nodeName
* @param number * @param number
* @return nodes with the constrain * @return nodes with the constrain
*/ */
public static Element selectDsNode(Node sibling, String nodeName, int number) { public static Element selectDsNode(Node sibling, String nodeName, int number) {
while (sibling!=null) { while (sibling != null) {
if (ElementProxy.checker.isNamespaceElement(sibling, nodeName, Constants.SignatureSpecNS )) { if (Constants.SignatureSpecNS.equals(sibling.getNamespaceURI())
if (number==0){ && sibling.getLocalName().equals(nodeName)) {
return (Element)sibling; if (number == 0){
} return (Element)sibling;
number--;
} }
sibling=sibling.getNextSibling(); number--;
}
sibling = sibling.getNextSibling();
} }
return null; return null;
} }
/**
* @param sibling
* @param nodeName
* @param number
* @return nodes with the constrain
*/
public static Element selectXencNode(Node sibling, String nodeName, int number) { /**
while (sibling!=null) { * @param sibling
if (ElementProxy.checker.isNamespaceElement(sibling, nodeName, EncryptionConstants.EncryptionSpecNS )) { * @param nodeName
if (number==0){ * @param number
return (Element)sibling; * @return nodes with the constrain
} */
number--; public static Element selectXencNode(Node sibling, String nodeName, int number) {
while (sibling != null) {
if (EncryptionConstants.EncryptionSpecNS.equals(sibling.getNamespaceURI())
&& sibling.getLocalName().equals(nodeName)) {
if (number == 0){
return (Element)sibling;
} }
sibling=sibling.getNextSibling(); number--;
}
sibling = sibling.getNextSibling();
} }
return null; return null;
} }
/** /**
* @param sibling * @param sibling
...@@ -581,62 +611,53 @@ public class XMLUtils { ...@@ -581,62 +611,53 @@ public class XMLUtils {
return (Text)n; return (Text)n;
} }
/** /**
* @param sibling * @param sibling
* @param uri * @param uri
* @param nodeName * @param nodeName
* @param number * @param number
* @return nodes with the constrain * @return nodes with the constrain
*/ */
public static Element selectNode(Node sibling, String uri,String nodeName, int number) { public static Element selectNode(Node sibling, String uri, String nodeName, int number) {
while (sibling!=null) { while (sibling != null) {
if (ElementProxy.checker.isNamespaceElement(sibling, nodeName, uri)) { if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
if (number==0){ && sibling.getLocalName().equals(nodeName)) {
return (Element)sibling; if (number == 0){
} return (Element)sibling;
number--;
} }
sibling=sibling.getNextSibling(); number--;
}
sibling = sibling.getNextSibling();
} }
return null; return null;
} }
/** /**
* @param sibling * @param sibling
* @param nodeName * @param nodeName
* @return nodes with the constrain * @return nodes with the constrain
*/ */
public static Element[] selectDsNodes(Node sibling,String nodeName) { public static Element[] selectDsNodes(Node sibling, String nodeName) {
return selectNodes(sibling,Constants.SignatureSpecNS,nodeName); return selectNodes(sibling,Constants.SignatureSpecNS, nodeName);
} }
/**
* @param sibling /**
* @param uri * @param sibling
* @param nodeName * @param uri
* @return nodes with the constrain * @param nodeName
*/ * @return nodes with the constrain
public static Element[] selectNodes(Node sibling,String uri,String nodeName) { */
int size=20; public static Element[] selectNodes(Node sibling, String uri, String nodeName) {
Element[] a= new Element[size]; List<Element> list = new ArrayList<Element>();
int curr=0; while (sibling != null) {
//List list=new ArrayList(); if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
while (sibling!=null) { && sibling.getLocalName().equals(nodeName)) {
if (ElementProxy.checker.isNamespaceElement(sibling, nodeName, uri)) { list.add((Element)sibling);
a[curr++]=(Element)sibling; }
if (size<=curr) { sibling = sibling.getNextSibling();
int cursize= size<<2;
Element []cp=new Element[cursize];
System.arraycopy(a,0,cp,0,size);
a=cp;
size=cursize;
}
}
sibling=sibling.getNextSibling();
} }
Element []af=new Element[curr]; return list.toArray(new Element[list.size()]);
System.arraycopy(a,0,af,0,curr); }
return af;
}
/** /**
* @param signatureElement * @param signatureElement
...@@ -694,4 +715,127 @@ public class XMLUtils { ...@@ -694,4 +715,127 @@ public class XMLUtils {
public static boolean ignoreLineBreaks() { public static boolean ignoreLineBreaks() {
return ignoreLineBreaks; return ignoreLineBreaks;
} }
/**
* This method is a tree-search to help prevent against wrapping attacks.
* It checks that no two Elements have ID Attributes that match the "value"
* argument, if this is the case then "false" is returned. Note that a
* return value of "true" does not necessarily mean that a matching Element
* has been found, just that no wrapping attack has been detected.
*/
public static boolean protectAgainstWrappingAttack(Node startNode,
String value)
{
Node startParent = startNode.getParentNode();
Node processedNode = null;
Element foundElement = null;
String id = value.trim();
if (id.charAt(0) == '#') {
id = id.substring(1);
}
while (startNode != null) {
if (startNode.getNodeType() == Node.ELEMENT_NODE) {
Element se = (Element) startNode;
NamedNodeMap attributes = se.getAttributes();
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
Attr attr = (Attr)attributes.item(i);
if (attr.isId() && id.equals(attr.getValue())) {
if (foundElement == null) {
// Continue searching to find duplicates
foundElement = attr.getOwnerElement();
} else {
log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!");
return false;
}
}
}
}
}
processedNode = startNode;
startNode = startNode.getFirstChild();
// no child, this node is done.
if (startNode == null) {
// close node processing, get sibling
startNode = processedNode.getNextSibling();
}
// no more siblings, get parent, all children
// of parent are processed.
while (startNode == null) {
processedNode = processedNode.getParentNode();
if (processedNode == startParent) {
return true;
}
// close parent node processing (processed node now)
startNode = processedNode.getNextSibling();
}
}
return true;
}
/**
* This method is a tree-search to help prevent against wrapping attacks.
* It checks that no other Element than the given "knownElement" argument
* has an ID attribute that matches the "value" argument, which is the ID
* value of "knownElement". If this is the case then "false" is returned.
*/
public static boolean protectAgainstWrappingAttack(Node startNode,
Element knownElement,
String value)
{
Node startParent = startNode.getParentNode();
Node processedNode = null;
String id = value.trim();
if (id.charAt(0) == '#') {
id = id.substring(1);
}
while (startNode != null) {
if (startNode.getNodeType() == Node.ELEMENT_NODE) {
Element se = (Element) startNode;
NamedNodeMap attributes = se.getAttributes();
if (attributes != null) {
for (int i = 0; i < attributes.getLength(); i++) {
Attr attr = (Attr)attributes.item(i);
if (attr.isId() && id.equals(attr.getValue())
&& se != knownElement)
{
log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!");
return false;
}
}
}
}
processedNode = startNode;
startNode = startNode.getFirstChild();
// no child, this node is done.
if (startNode == null) {
// close node processing, get sibling
startNode = processedNode.getNextSibling();
}
// no more siblings, get parent, all children
// of parent are processed.
while (startNode == null) {
processedNode = processedNode.getParentNode();
if (processedNode == startParent) {
return true;
}
// close parent node processing (processed node now)
startNode = processedNode.getNextSibling();
}
}
return true;
}
} }
...@@ -2,21 +2,23 @@ ...@@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /**
* Copyright 1999-2004 The Apache Software Foundation. * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* http://www.apache.org/licenses/LICENSE-2.0 * with the License. You may obtain a copy of the License at
* *
* Unless required by applicable law or agreed to in writing, software * http://www.apache.org/licenses/LICENSE-2.0
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package com.sun.org.apache.xml.internal.security.utils.resolver; package com.sun.org.apache.xml.internal.security.utils.resolver;
...@@ -25,311 +27,318 @@ import java.util.List; ...@@ -25,311 +27,318 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverDirectHTTP;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverLocalFilesystem;
import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverXPointer;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
/** /**
* During reference validation, we have to retrieve resources from somewhere. * During reference validation, we have to retrieve resources from somewhere.
* This is done by retrieving a Resolver. The resolver needs two arguments: The * This is done by retrieving a Resolver. The resolver needs two arguments: The
* URI in which the link to the new resource is defined and the BaseURI of the * URI in which the link to the new resource is defined and the baseURI of the
* file/entity in which the URI occurs (the BaseURI is the same as the SystemId. * file/entity in which the URI occurs (the baseURI is the same as the SystemId).
*
* <UL xml:lang="DE" LANG="DE">
* <LI> Verschiedene Implementierungen k??nnen sich als Resolver registrieren.
* <LI> Standardm????ig werden erste Implementierungen auf dem XML config file registrirt.
* <LI> Der Benutzer kann bei Bedarf Implementierungen voranstellen oder anf??gen.
* <LI> Implementierungen k??nnen mittels Features customized werden ??
* (z.B. um Proxy-Passworter ??bergeben zu k??nnen).
* <LI> Jede Implementierung bekommt das URI Attribut und den Base URI
* ??bergeben und muss antworten, ob sie aufl??sen kann.
* <LI> Die erste Implementierung, die die Aufgabe erf??llt, f??hrt die Aufl??sung durch.
* </UL>
*
* @author $Author: mullan $
*/ */
public class ResourceResolver { public class ResourceResolver {
/** {@link java.util.logging} logging facility */ /** {@link org.apache.commons.logging} logging facility */
static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(ResourceResolver.class.getName()); java.util.logging.Logger.getLogger(ResourceResolver.class.getName());
/** Field _alreadyInitialized */ /** these are the system-wide resolvers */
static boolean _alreadyInitialized = false; private static List<ResourceResolver> resolverList = new ArrayList<ResourceResolver>();
/** these are the system-wide resolvers */
static List<ResourceResolver> _resolverVector = null;
static boolean allThreadSafeInList=true;
/** Field transformSpi */
protected ResourceResolverSpi _resolverSpi = null;
/**
* Constructor ResourceResolver
*
* @param className
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
private ResourceResolver(String className)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException {
this._resolverSpi =
(ResourceResolverSpi) Class.forName(className).newInstance();
}
/**
* Constructor ResourceResolver
*
* @param resourceResolver
*/
public ResourceResolver(ResourceResolverSpi resourceResolver) {
this._resolverSpi = resourceResolver;
}
/** /** Field resolverSpi */
* Method getInstance private final ResourceResolverSpi resolverSpi;
*
* @param uri
* @param BaseURI
* @return the instnace
*
* @throws ResourceResolverException
*/
public static final ResourceResolver getInstance(Attr uri, String BaseURI)
throws ResourceResolverException {
int length=ResourceResolver._resolverVector.size();
for (int i = 0; i < length; i++) {
ResourceResolver resolver =
ResourceResolver._resolverVector.get(i);
ResourceResolver resolverTmp=null;
try {
resolverTmp = allThreadSafeInList || resolver._resolverSpi.engineIsThreadSafe() ? resolver :
new ResourceResolver((ResourceResolverSpi)resolver._resolverSpi.getClass().newInstance());
} catch (InstantiationException e) {
throw new ResourceResolverException("",e,uri,BaseURI);
} catch (IllegalAccessException e) {
throw new ResourceResolverException("",e,uri,BaseURI);
}
if (log.isLoggable(java.util.logging.Level.FINE)) /**
log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver._resolverSpi.getClass().getName()); * Constructor ResourceResolver
*
if ((resolver != null) && resolverTmp.canResolve(uri, BaseURI)) { * @param resourceResolver
if (i!=0) { */
//update resolver. public ResourceResolver(ResourceResolverSpi resourceResolver) {
//System.out.println("Swaping"); this.resolverSpi = resourceResolver;
List<ResourceResolver> resolverVector=getResolverVectorClone(); }
resolverVector.remove(i);
resolverVector.add(0,resolver);
_resolverVector=resolverVector;
} else {
//System.out.println("hitting");
}
return resolverTmp;
}
}
Object exArgs[] = { ((uri != null)
? uri.getNodeValue()
: "null"), BaseURI };
throw new ResourceResolverException("utils.resolver.noClass", exArgs, /**
uri, BaseURI); * Method getInstance
} *
* @param uri
* @param baseURI
* @return the instance
*
* @throws ResourceResolverException
*/
public static final ResourceResolver getInstance(Attr uri, String baseURI)
throws ResourceResolverException {
return getInstance(uri, baseURI, false);
}
/** /**
* Method getResolverVectorClone * Method getInstance
* *
* @return clone of _resolverVector * @param uri
*/ * @param baseURI
@SuppressWarnings("unchecked") * @param secureValidation
private static List<ResourceResolver> getResolverVectorClone() { * @return the instance
return (List<ResourceResolver>)((ArrayList<ResourceResolver>)_resolverVector).clone(); *
} * @throws ResourceResolverException
*/
public static final ResourceResolver getInstance(
Attr uri, String baseURI, boolean secureValidation
) throws ResourceResolverException {
synchronized (resolverList) {
for (ResourceResolver resolver : resolverList) {
ResourceResolver resolverTmp = resolver;
if (!resolver.resolverSpi.engineIsThreadSafe()) {
try {
resolverTmp =
new ResourceResolver(resolver.resolverSpi.getClass().newInstance());
} catch (InstantiationException e) {
throw new ResourceResolverException("", e, uri, baseURI);
} catch (IllegalAccessException e) {
throw new ResourceResolverException("", e, uri, baseURI);
}
}
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE,
"check resolvability by class " + resolverTmp.getClass().getName()
);
}
resolverTmp.resolverSpi.secureValidation = secureValidation;
if ((resolverTmp != null) && resolverTmp.canResolve(uri, baseURI)) {
// Check to see whether the Resolver is allowed
if (secureValidation
&& (resolverTmp.resolverSpi instanceof ResolverLocalFilesystem
|| resolverTmp.resolverSpi instanceof ResolverDirectHTTP)) {
Object exArgs[] = { resolverTmp.resolverSpi.getClass().getName() };
throw new ResourceResolverException(
"signature.Reference.ForbiddenResolver", exArgs, uri, baseURI
);
}
return resolverTmp;
}
}
}
/** Object exArgs[] = { ((uri != null) ? uri.getNodeValue() : "null"), baseURI };
* Method getInstance
*
* @param uri
* @param BaseURI
* @param individualResolvers
* @return the instance
*
* @throws ResourceResolverException
*/
public static final ResourceResolver getInstance(
Attr uri, String BaseURI, List<ResourceResolver> individualResolvers)
throws ResourceResolverException {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "I was asked to create a ResourceResolver and got " + (individualResolvers==null? 0 : individualResolvers.size()) ); throw new ResourceResolverException("utils.resolver.noClass", exArgs, uri, baseURI);
log.log(java.util.logging.Level.FINE, " extra resolvers to my existing " + ResourceResolver._resolverVector.size() + " system-wide resolvers"); }
}
// first check the individual Resolvers /**
int size=0; * Method getInstance
if ((individualResolvers != null) && ((size=individualResolvers.size()) > 0)) { *
for (int i = 0; i < size; i++) { * @param uri
ResourceResolver resolver = * @param baseURI
individualResolvers.get(i); * @param individualResolvers
* @return the instance
*
* @throws ResourceResolverException
*/
public static ResourceResolver getInstance(
Attr uri, String baseURI, List<ResourceResolver> individualResolvers
) throws ResourceResolverException {
return getInstance(uri, baseURI, individualResolvers, false);
}
if (resolver != null) { /**
String currentClass = resolver._resolverSpi.getClass().getName(); * Method getInstance
if (log.isLoggable(java.util.logging.Level.FINE)) *
log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass); * @param uri
* @param baseURI
* @param individualResolvers
* @param secureValidation
* @return the instance
*
* @throws ResourceResolverException
*/
public static ResourceResolver getInstance(
Attr uri, String baseURI, List<ResourceResolver> individualResolvers, boolean secureValidation
) throws ResourceResolverException {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE,
"I was asked to create a ResourceResolver and got "
+ (individualResolvers == null ? 0 : individualResolvers.size())
);
}
if (resolver.canResolve(uri, BaseURI)) { // first check the individual Resolvers
return resolver; if (individualResolvers != null) {
} for (int i = 0; i < individualResolvers.size(); i++) {
ResourceResolver resolver = individualResolvers.get(i);
if (resolver != null) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
String currentClass = resolver.resolverSpi.getClass().getName();
log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass);
}
resolver.resolverSpi.secureValidation = secureValidation;
if (resolver.canResolve(uri, baseURI)) {
return resolver;
}
}
} }
} }
}
return getInstance(uri,BaseURI);
}
/**
* The init() function is called by com.sun.org.apache.xml.internal.security.Init.init()
*/
public static void init() {
if (!ResourceResolver._alreadyInitialized) { return getInstance(uri, baseURI, secureValidation);
ResourceResolver._resolverVector = new ArrayList<ResourceResolver>(10); }
_alreadyInitialized = true;
}
}
/** /**
* Registers a ResourceResolverSpi class. This method logs a warning if * Registers a ResourceResolverSpi class. This method logs a warning if
* the class cannot be registered. * the class cannot be registered.
* *
* @param className the name of the ResourceResolverSpi class to be * @param className the name of the ResourceResolverSpi class to be registered
* registered
*/ */
@SuppressWarnings("unchecked")
public static void register(String className) { public static void register(String className) {
register(className, false); try {
Class<ResourceResolverSpi> resourceResolverClass =
(Class<ResourceResolverSpi>) Class.forName(className);
register(resourceResolverClass, false);
} catch (ClassNotFoundException e) {
log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
}
} }
/** /**
* Registers a ResourceResolverSpi class at the beginning of the provider * Registers a ResourceResolverSpi class at the beginning of the provider
* list. This method logs a warning if the class cannot be registered. * list. This method logs a warning if the class cannot be registered.
* *
* @param className the name of the ResourceResolverSpi class to be * @param className the name of the ResourceResolverSpi class to be registered
* registered
*/ */
@SuppressWarnings("unchecked")
public static void registerAtStart(String className) { public static void registerAtStart(String className) {
register(className, true); try {
Class<ResourceResolverSpi> resourceResolverClass =
(Class<ResourceResolverSpi>) Class.forName(className);
register(resourceResolverClass, true);
} catch (ClassNotFoundException e) {
log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
}
} }
private static void register(String className, boolean start) { /**
* Registers a ResourceResolverSpi class. This method logs a warning if the class
* cannot be registered.
* @param className
* @param start
*/
public static void register(Class<? extends ResourceResolverSpi> className, boolean start) {
try { try {
ResourceResolver resolver = new ResourceResolver(className); ResourceResolverSpi resourceResolverSpi = className.newInstance();
register(resourceResolverSpi, start);
} catch (IllegalAccessException e) {
log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
} catch (InstantiationException e) {
log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
}
}
/**
* Registers a ResourceResolverSpi instance. This method logs a warning if the class
* cannot be registered.
* @param resourceResolverSpi
* @param start
*/
public static void register(ResourceResolverSpi resourceResolverSpi, boolean start) {
synchronized(resolverList) {
if (start) { if (start) {
ResourceResolver._resolverVector.add(0, resolver); resolverList.add(0, new ResourceResolver(resourceResolverSpi));
log.log(java.util.logging.Level.FINE, "registered resolver");
} else { } else {
ResourceResolver._resolverVector.add(resolver); resolverList.add(new ResourceResolver(resourceResolverSpi));
} }
if (!resolver._resolverSpi.engineIsThreadSafe()) {
allThreadSafeInList=false;
} }
} catch (Exception e) { if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className +" disabling it"); log.log(java.util.logging.Level.FINE, "Registered resolver: " + resourceResolverSpi.toString());
} catch (NoClassDefFoundError e) {
log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className +" disabling it");
} }
} }
/** /**
* Method resolve * This method registers the default resolvers.
* */
* @param uri public static void registerDefaultResolvers() {
* @param BaseURI synchronized(resolverList) {
* @return the resource resolverList.add(new ResourceResolver(new ResolverFragment()));
* resolverList.add(new ResourceResolver(new ResolverLocalFilesystem()));
* @throws ResourceResolverException resolverList.add(new ResourceResolver(new ResolverXPointer()));
*/ resolverList.add(new ResourceResolver(new ResolverDirectHTTP()));
public static XMLSignatureInput resolveStatic(Attr uri, String BaseURI) }
throws ResourceResolverException { }
ResourceResolver myResolver = ResourceResolver.getInstance(uri, BaseURI);
return myResolver.resolve(uri, BaseURI);
}
/** /**
* Method resolve * Method resolve
* *
* @param uri * @param uri
* @param BaseURI * @param baseURI
* @return the resource * @return the resource
* *
* @throws ResourceResolverException * @throws ResourceResolverException
*/ */
public XMLSignatureInput resolve(Attr uri, String BaseURI) public XMLSignatureInput resolve(Attr uri, String baseURI)
throws ResourceResolverException { throws ResourceResolverException {
return this._resolverSpi.engineResolve(uri, BaseURI); return resolverSpi.engineResolve(uri, baseURI);
} }
/** /**
* Method setProperty * Method setProperty
* *
* @param key * @param key
* @param value * @param value
*/ */
public void setProperty(String key, String value) { public void setProperty(String key, String value) {
this._resolverSpi.engineSetProperty(key, value); resolverSpi.engineSetProperty(key, value);
} }
/** /**
* Method getProperty * Method getProperty
* *
* @param key * @param key
* @return the value of the property * @return the value of the property
*/ */
public String getProperty(String key) { public String getProperty(String key) {
return this._resolverSpi.engineGetProperty(key); return resolverSpi.engineGetProperty(key);
} }
/** /**
* Method addProperties * Method addProperties
* *
* @param properties * @param properties
*/ */
public void addProperties(Map<String,String> properties) { public void addProperties(Map<String, String> properties) {
this._resolverSpi.engineAddProperies(properties); resolverSpi.engineAddProperies(properties);
} }
/** /**
* Method getPropertyKeys * Method getPropertyKeys
* *
* @return all property keys. * @return all property keys.
*/ */
public String[] getPropertyKeys() { public String[] getPropertyKeys() {
return this._resolverSpi.engineGetPropertyKeys(); return resolverSpi.engineGetPropertyKeys();
} }
/** /**
* Method understandsProperty * Method understandsProperty
* *
* @param propertyToTest * @param propertyToTest
* @return true if the resolver understands the property * @return true if the resolver understands the property
*/ */
public boolean understandsProperty(String propertyToTest) { public boolean understandsProperty(String propertyToTest) {
return this._resolverSpi.understandsProperty(propertyToTest); return resolverSpi.understandsProperty(propertyToTest);
} }
/** /**
* Method canResolve * Method canResolve
* *
* @param uri * @param uri
* @param BaseURI * @param baseURI
* @return true if it can resolve the uri * @return true if it can resolve the uri
*/ */
private boolean canResolve(Attr uri, String BaseURI) { private boolean canResolve(Attr uri, String baseURI) {
return this._resolverSpi.engineCanResolve(uri, BaseURI); return resolverSpi.engineCanResolve(uri, baseURI);
} }
} }
...@@ -43,6 +43,8 @@ public abstract class ResourceResolverSpi { ...@@ -43,6 +43,8 @@ public abstract class ResourceResolverSpi {
/** Field _properties */ /** Field _properties */
protected java.util.Map<String,String> _properties = null; protected java.util.Map<String,String> _properties = null;
protected boolean secureValidation;
/** /**
* This is the workhorse method used to resolve resources. * This is the workhorse method used to resolve resources.
* *
......
...@@ -23,11 +23,12 @@ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; ...@@ -23,11 +23,12 @@ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -51,63 +52,68 @@ public class ResolverFragment extends ResourceResolverSpi { ...@@ -51,63 +52,68 @@ public class ResolverFragment extends ResourceResolverSpi {
/** /**
* Method engineResolve * Method engineResolve
* *
* Wird das gleiche Dokument referenziert?
* Wird ein anderes Dokument referenziert?
* @inheritDoc * @inheritDoc
* @param uri * @param uri
* @param BaseURI * @param baseURI
*
*/ */
public XMLSignatureInput engineResolve(Attr uri, String BaseURI) public XMLSignatureInput engineResolve(Attr uri, String baseURI)
throws ResourceResolverException throws ResourceResolverException
{ {
String uriNodeValue = uri.getNodeValue();
String uriNodeValue = uri.getNodeValue(); Document doc = uri.getOwnerElement().getOwnerDocument();
Document doc = uri.getOwnerElement().getOwnerDocument();
Node selectedElem = null;
if (uriNodeValue.equals("")) {
Node selectedElem = null;
if (uriNodeValue.equals("")) { /*
* Identifies the node-set (minus any comment nodes) of the XML
/* * resource containing the signature
* Identifies the node-set (minus any comment nodes) of the XML */
* resource containing the signature
*/ log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)");
selectedElem = doc;
log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)"); } else {
selectedElem = doc;
} else { /*
* URI="#chapter1"
/* * Identifies a node-set containing the element with ID attribute
* URI="#chapter1" * value 'chapter1' of the XML resource containing the signature.
* Identifies a node-set containing the element with ID attribute * XML Signature (and its applications) modify this node-set to
* value 'chapter1' of the XML resource containing the signature. * include the element plus all descendents including namespaces and
* XML Signature (and its applications) modify this node-set to * attributes -- but not comments.
* include the element plus all descendents including namespaces and */
* attributes -- but not comments. String id = uriNodeValue.substring(1);
*/
String id = uriNodeValue.substring(1); selectedElem = doc.getElementById(id);
if (selectedElem == null) {
// Element selectedElem = doc.getElementById(id);
selectedElem = IdResolver.getElementById(doc, id);
if (selectedElem==null) {
Object exArgs[] = { id }; Object exArgs[] = { id };
throw new ResourceResolverException( throw new ResourceResolverException(
"signature.Verification.MissingID", exArgs, uri, BaseURI); "signature.Verification.MissingID", exArgs, uri, baseURI);
} }
if (log.isLoggable(java.util.logging.Level.FINE)) if (secureValidation) {
Element start = uri.getOwnerDocument().getDocumentElement();
if (!XMLUtils.protectAgainstWrappingAttack(start, id)) {
Object exArgs[] = { id };
throw new ResourceResolverException(
"signature.Verification.MultipleIDs", exArgs,
uri, baseURI);
}
}
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Try to catch an Element with ID " + id + " and Element was " + selectedElem); log.log(java.util.logging.Level.FINE, "Try to catch an Element with ID " + id + " and Element was " + selectedElem);
} }
XMLSignatureInput result = new XMLSignatureInput(selectedElem); XMLSignatureInput result = new XMLSignatureInput(selectedElem);
result.setExcludeComments(true); result.setExcludeComments(true);
//log.log(java.util.logging.Level.FINE, "We return a nodeset with " + resultSet.size() + " nodes"); result.setMIMEType("text/xml");
result.setMIMEType("text/xml"); if (baseURI != null && baseURI.length() > 0) {
result.setSourceURI((BaseURI != null) ? BaseURI.concat(uri.getNodeValue()) : result.setSourceURI(baseURI.concat(uri.getNodeValue()));
uri.getNodeValue()); } else {
return result; result.setSourceURI(uri.getNodeValue());
} }
return result;
}
/** /**
* Method engineCanResolve * Method engineCanResolve
......
...@@ -23,11 +23,12 @@ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; ...@@ -23,11 +23,12 @@ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -54,52 +55,55 @@ public class ResolverXPointer extends ResourceResolverSpi { ...@@ -54,52 +55,55 @@ public class ResolverXPointer extends ResourceResolverSpi {
ResolverXPointer.class.getName()); ResolverXPointer.class.getName());
public boolean engineIsThreadSafe() { public boolean engineIsThreadSafe() {
return true; return true;
} }
/**
* @inheritDoc /**
*/ * @inheritDoc
public XMLSignatureInput engineResolve(Attr uri, String BaseURI) */
public XMLSignatureInput engineResolve(Attr uri, String baseURI)
throws ResourceResolverException { throws ResourceResolverException {
Node resultNode = null; Node resultNode = null;
Document doc = uri.getOwnerElement().getOwnerDocument(); Document doc = uri.getOwnerElement().getOwnerDocument();
String uriStr=uri.getNodeValue(); String uriStr = uri.getNodeValue();
if (isXPointerSlash(uriStr)) { if (isXPointerSlash(uriStr)) {
resultNode = doc; resultNode = doc;
} else if (isXPointerId(uriStr)) { } else if (isXPointerId(uriStr)) {
String id = getXPointerId(uriStr); String id = getXPointerId(uriStr);
resultNode =IdResolver.getElementById(doc, id); resultNode = doc.getElementById(id);
// log.log(java.util.logging.Level.FINE, "Use #xpointer(id('" + id + "')) on element " + selectedElem); if (secureValidation) {
Element start = uri.getOwnerDocument().getDocumentElement();
if (!XMLUtils.protectAgainstWrappingAttack(start, id)) {
Object exArgs[] = { id };
throw new ResourceResolverException(
"signature.Verification.MultipleIDs", exArgs,
uri, baseURI);
}
}
if (resultNode == null) { if (resultNode == null) {
Object exArgs[] = { id }; Object exArgs[] = { id };
throw new ResourceResolverException( throw new ResourceResolverException(
"signature.Verification.MissingID", exArgs, uri, BaseURI); "signature.Verification.MissingID", exArgs, uri, baseURI);
} }
/* }
resultNodes =
cXPathAPI
.selectNodeList(selectedElem, Canonicalizer
.XPATH_C14N_WITH_COMMENTS_SINGLE_NODE);*/
}
XMLSignatureInput result = new XMLSignatureInput(resultNode);
XMLSignatureInput result = new XMLSignatureInput(resultNode); result.setMIMEType("text/xml");
if (baseURI != null && baseURI.length() > 0) {
result.setSourceURI(baseURI.concat(uri.getNodeValue()));
} else {
result.setSourceURI(uri.getNodeValue());
}
result.setMIMEType("text/xml"); return result;
if (BaseURI != null && BaseURI.length() > 0) { }
result.setSourceURI(BaseURI.concat(uri.getNodeValue()));
} else {
result.setSourceURI(uri.getNodeValue());
}
return result;
}
/** /**
* @inheritDoc * @inheritDoc
......
/* /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -74,11 +74,7 @@ public class DOMValidateContext extends DOMCryptoContext ...@@ -74,11 +74,7 @@ public class DOMValidateContext extends DOMCryptoContext
if (ks == null) { if (ks == null) {
throw new NullPointerException("key selector is null"); throw new NullPointerException("key selector is null");
} }
if (node == null) { init(node, ks);
throw new NullPointerException("node is null");
}
setKeySelector(ks);
this.node = node;
} }
/** /**
...@@ -97,11 +93,20 @@ public class DOMValidateContext extends DOMCryptoContext ...@@ -97,11 +93,20 @@ public class DOMValidateContext extends DOMCryptoContext
if (validatingKey == null) { if (validatingKey == null) {
throw new NullPointerException("validatingKey is null"); throw new NullPointerException("validatingKey is null");
} }
init(node, KeySelector.singletonKeySelector(validatingKey));
}
private void init(Node node, KeySelector ks) {
if (node == null) { if (node == null) {
throw new NullPointerException("node is null"); throw new NullPointerException("node is null");
} }
setKeySelector(KeySelector.singletonKeySelector(validatingKey));
this.node = node; this.node = node;
super.setKeySelector(ks);
if (System.getSecurityManager() != null) {
super.setProperty("org.jcp.xml.dsig.secureValidation",
Boolean.TRUE);
}
} }
/** /**
......
...@@ -193,7 +193,7 @@ public abstract class ApacheCanonicalizer extends TransformService { ...@@ -193,7 +193,7 @@ public abstract class ApacheCanonicalizer extends TransformService {
if (apacheTransform == null) { if (apacheTransform == null) {
try { try {
apacheTransform = Transform.getInstance apacheTransform = new Transform
(ownerDoc, getAlgorithm(), transformElem.getChildNodes()); (ownerDoc, getAlgorithm(), transformElem.getChildNodes());
apacheTransform.setElement(transformElem, xc.getBaseURI()); apacheTransform.setElement(transformElem, xc.getBaseURI());
if (log.isLoggable(Level.FINE)) { if (log.isLoggable(Level.FINE)) {
......
...@@ -38,6 +38,7 @@ import org.w3c.dom.NodeList; ...@@ -38,6 +38,7 @@ import org.w3c.dom.NodeList;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.transforms.Transform; import com.sun.org.apache.xml.internal.security.transforms.Transform;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
import javax.xml.crypto.*; import javax.xml.crypto.*;
import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dom.DOMCryptoContext;
...@@ -117,7 +118,7 @@ public abstract class ApacheTransform extends TransformService { ...@@ -117,7 +118,7 @@ public abstract class ApacheTransform extends TransformService {
if (apacheTransform == null) { if (apacheTransform == null) {
try { try {
apacheTransform = Transform.getInstance apacheTransform = new Transform
(ownerDoc, getAlgorithm(), transformElem.getChildNodes()); (ownerDoc, getAlgorithm(), transformElem.getChildNodes());
apacheTransform.setElement(transformElem, xc.getBaseURI()); apacheTransform.setElement(transformElem, xc.getBaseURI());
if (log.isLoggable(Level.FINE)) { if (log.isLoggable(Level.FINE)) {
...@@ -130,6 +131,15 @@ public abstract class ApacheTransform extends TransformService { ...@@ -130,6 +131,15 @@ public abstract class ApacheTransform extends TransformService {
} }
} }
if (Utils.secureValidation(xc)) {
String algorithm = getAlgorithm();
if (Transforms.TRANSFORM_XSLT.equals(algorithm)) {
throw new TransformException(
"Transform " + algorithm +
" is forbidden when secure validation is enabled");
}
}
XMLSignatureInput in; XMLSignatureInput in;
if (data instanceof ApacheData) { if (data instanceof ApacheData) {
if (log.isLoggable(Level.FINE)) { if (log.isLoggable(Level.FINE)) {
......
...@@ -34,6 +34,7 @@ import javax.xml.crypto.dom.*; ...@@ -34,6 +34,7 @@ import javax.xml.crypto.dom.*;
import java.security.Provider; import java.security.Provider;
import java.util.*; import java.util.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -87,7 +88,13 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { ...@@ -87,7 +88,13 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo {
public DOMKeyInfo(Element kiElem, XMLCryptoContext context, public DOMKeyInfo(Element kiElem, XMLCryptoContext context,
Provider provider) throws MarshalException { Provider provider) throws MarshalException {
// get Id attribute, if specified // get Id attribute, if specified
id = DOMUtils.getAttributeValue(kiElem, "Id"); Attr attr = kiElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
id = attr.getValue();
kiElem.setIdAttributeNode(attr, true);
} else {
id = null;
}
// get all children nodes // get all children nodes
NodeList nl = kiElem.getChildNodes(); NodeList nl = kiElem.getChildNodes();
......
...@@ -32,6 +32,7 @@ import javax.xml.crypto.dsig.*; ...@@ -32,6 +32,7 @@ import javax.xml.crypto.dsig.*;
import java.security.Provider; import java.security.Provider;
import java.util.*; import java.util.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -85,12 +86,30 @@ public final class DOMManifest extends DOMStructure implements Manifest { ...@@ -85,12 +86,30 @@ public final class DOMManifest extends DOMStructure implements Manifest {
*/ */
public DOMManifest(Element manElem, XMLCryptoContext context, public DOMManifest(Element manElem, XMLCryptoContext context,
Provider provider) throws MarshalException { Provider provider) throws MarshalException {
this.id = DOMUtils.getAttributeValue(manElem, "Id"); Attr attr = manElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
this.id = attr.getValue();
manElem.setIdAttributeNode(attr, true);
} else {
this.id = null;
}
boolean secVal = Utils.secureValidation(context);
Element refElem = DOMUtils.getFirstChildElement(manElem); Element refElem = DOMUtils.getFirstChildElement(manElem);
List refs = new ArrayList(); List refs = new ArrayList();
int refCount = 0;
while (refElem != null) { while (refElem != null) {
refs.add(new DOMReference(refElem, context, provider)); refs.add(new DOMReference(refElem, context, provider));
refElem = DOMUtils.getNextSiblingElement(refElem); refElem = DOMUtils.getNextSiblingElement(refElem);
refCount++;
if (secVal && (refCount > DOMSignedInfo.MAXIMUM_REFERENCE_COUNT)) {
String error = "A maxiumum of " +
DOMSignedInfo.MAXIMUM_REFERENCE_COUNT +
" references per Manifest are allowed with" +
" secure validation";
throw new MarshalException(error);
}
} }
this.references = Collections.unmodifiableList(refs); this.references = Collections.unmodifiableList(refs);
} }
......
...@@ -51,6 +51,7 @@ import org.w3c.dom.Element; ...@@ -51,6 +51,7 @@ import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.jcp.xml.dsig.internal.DigesterOutputStream; import org.jcp.xml.dsig.internal.DigesterOutputStream;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Base64;
...@@ -65,6 +66,12 @@ import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream ...@@ -65,6 +66,12 @@ import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream
public final class DOMReference extends DOMStructure public final class DOMReference extends DOMStructure
implements Reference, DOMURIReference { implements Reference, DOMURIReference {
/**
* The maximum number of transforms per reference, if secure validation
* is enabled.
*/
public static final int MAXIMUM_TRANSFORM_COUNT = 5;
/** /**
* Look up useC14N11 system property. If true, an explicit C14N11 transform * Look up useC14N11 system property. If true, an explicit C14N11 transform
* will be added if necessary when generating the signature. See section * will be added if necessary when generating the signature. See section
...@@ -184,15 +191,27 @@ public final class DOMReference extends DOMStructure ...@@ -184,15 +191,27 @@ public final class DOMReference extends DOMStructure
*/ */
public DOMReference(Element refElem, XMLCryptoContext context, public DOMReference(Element refElem, XMLCryptoContext context,
Provider provider) throws MarshalException { Provider provider) throws MarshalException {
boolean secVal = Utils.secureValidation(context);
// unmarshal Transforms, if specified // unmarshal Transforms, if specified
Element nextSibling = DOMUtils.getFirstChildElement(refElem); Element nextSibling = DOMUtils.getFirstChildElement(refElem);
List transforms = new ArrayList(5); List transforms = new ArrayList(5);
if (nextSibling.getLocalName().equals("Transforms")) { if (nextSibling.getLocalName().equals("Transforms")) {
Element transformElem = DOMUtils.getFirstChildElement(nextSibling); Element transformElem = DOMUtils.getFirstChildElement(nextSibling);
int transformCount = 0;
while (transformElem != null) { while (transformElem != null) {
transforms.add transforms.add
(new DOMTransform(transformElem, context, provider)); (new DOMTransform(transformElem, context, provider));
transformElem = DOMUtils.getNextSiblingElement(transformElem); transformElem = DOMUtils.getNextSiblingElement(transformElem);
transformCount++;
if (secVal && (transformCount > MAXIMUM_TRANSFORM_COUNT)) {
String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT +
" transforms per Reference are allowed" +
" with secure validation";
throw new MarshalException(error);
}
} }
nextSibling = DOMUtils.getNextSiblingElement(nextSibling); nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
} }
...@@ -200,6 +219,14 @@ public final class DOMReference extends DOMStructure ...@@ -200,6 +219,14 @@ public final class DOMReference extends DOMStructure
// unmarshal DigestMethod // unmarshal DigestMethod
Element dmElem = nextSibling; Element dmElem = nextSibling;
this.digestMethod = DOMDigestMethod.unmarshal(dmElem); this.digestMethod = DOMDigestMethod.unmarshal(dmElem);
String digestMethodAlgorithm = this.digestMethod.getAlgorithm();
if (secVal
&& MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm))
{
throw new MarshalException("It is forbidden to use algorithm " +
digestMethod +
" when secure validation is enabled");
}
// unmarshal DigestValue // unmarshal DigestValue
try { try {
...@@ -211,7 +238,14 @@ public final class DOMReference extends DOMStructure ...@@ -211,7 +238,14 @@ public final class DOMReference extends DOMStructure
// unmarshal attributes // unmarshal attributes
this.uri = DOMUtils.getAttributeValue(refElem, "URI"); this.uri = DOMUtils.getAttributeValue(refElem, "URI");
this.id = DOMUtils.getAttributeValue(refElem, "Id");
Attr attr = refElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
this.id = attr.getValue();
refElem.setIdAttributeNode(attr, true);
} else {
this.id = null;
}
this.type = DOMUtils.getAttributeValue(refElem, "Type"); this.type = DOMUtils.getAttributeValue(refElem, "Type");
this.here = refElem.getAttributeNodeNS(null, "URI"); this.here = refElem.getAttributeNodeNS(null, "URI");
......
...@@ -38,6 +38,7 @@ import java.net.URI; ...@@ -38,6 +38,7 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.security.Provider; import java.security.Provider;
import java.util.*; import java.util.*;
import javax.xml.XMLConstants;
import javax.xml.crypto.*; import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dom.DOMCryptoContext;
...@@ -124,9 +125,13 @@ public final class DOMRetrievalMethod extends DOMStructure ...@@ -124,9 +125,13 @@ public final class DOMRetrievalMethod extends DOMStructure
// get here node // get here node
here = rmElem.getAttributeNodeNS(null, "URI"); here = rmElem.getAttributeNodeNS(null, "URI");
boolean secVal = Utils.secureValidation(context);
// get Transforms, if specified // get Transforms, if specified
List transforms = new ArrayList(); List transforms = new ArrayList();
Element transformsElem = DOMUtils.getFirstChildElement(rmElem); Element transformsElem = DOMUtils.getFirstChildElement(rmElem);
int transformCount = 0;
if (transformsElem != null) { if (transformsElem != null) {
Element transformElem = Element transformElem =
DOMUtils.getFirstChildElement(transformsElem); DOMUtils.getFirstChildElement(transformsElem);
...@@ -134,6 +139,17 @@ public final class DOMRetrievalMethod extends DOMStructure ...@@ -134,6 +139,17 @@ public final class DOMRetrievalMethod extends DOMStructure
transforms.add transforms.add
(new DOMTransform(transformElem, context, provider)); (new DOMTransform(transformElem, context, provider));
transformElem = DOMUtils.getNextSiblingElement(transformElem); transformElem = DOMUtils.getNextSiblingElement(transformElem);
transformCount++;
if (secVal &&
(transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT))
{
String error = "A maxiumum of " +
DOMReference.MAXIMUM_TRANSFORM_COUNT +
" transforms per Reference are allowed" +
" with secure validation";
throw new MarshalException(error);
}
} }
} }
if (transforms.isEmpty()) { if (transforms.isEmpty()) {
...@@ -224,6 +240,8 @@ public final class DOMRetrievalMethod extends DOMStructure ...@@ -224,6 +240,8 @@ public final class DOMRetrievalMethod extends DOMStructure
ApacheData data = (ApacheData) dereference(context); ApacheData data = (ApacheData) dereference(context);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true); dbf.setNamespaceAware(true);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
Boolean.TRUE);
DocumentBuilder db = dbf.newDocumentBuilder(); DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream Document doc = db.parse(new ByteArrayInputStream
(data.getXMLSignatureInput().getBytes())); (data.getXMLSignatureInput().getBytes()));
......
...@@ -31,6 +31,7 @@ import javax.xml.crypto.dom.DOMCryptoContext; ...@@ -31,6 +31,7 @@ import javax.xml.crypto.dom.DOMCryptoContext;
import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.*;
import java.util.*; import java.util.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -86,7 +87,13 @@ public final class DOMSignatureProperties extends DOMStructure ...@@ -86,7 +87,13 @@ public final class DOMSignatureProperties extends DOMStructure
*/ */
public DOMSignatureProperties(Element propsElem) throws MarshalException{ public DOMSignatureProperties(Element propsElem) throws MarshalException{
// unmarshal attributes // unmarshal attributes
id = DOMUtils.getAttributeValue(propsElem, "Id"); Attr attr = propsElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
id = attr.getValue();
propsElem.setIdAttributeNode(attr, true);
} else {
id = null;
}
NodeList nodes = propsElem.getChildNodes(); NodeList nodes = propsElem.getChildNodes();
int length = nodes.getLength(); int length = nodes.getLength();
......
...@@ -31,6 +31,7 @@ import javax.xml.crypto.dom.DOMCryptoContext; ...@@ -31,6 +31,7 @@ import javax.xml.crypto.dom.DOMCryptoContext;
import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.*;
import java.util.*; import java.util.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -94,7 +95,13 @@ public final class DOMSignatureProperty extends DOMStructure ...@@ -94,7 +95,13 @@ public final class DOMSignatureProperty extends DOMStructure
if (target == null) { if (target == null) {
throw new MarshalException("target cannot be null"); throw new MarshalException("target cannot be null");
} }
id = DOMUtils.getAttributeValue(propElem, "Id"); Attr attr = propElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
id = attr.getValue();
propElem.setIdAttributeNode(attr, true);
} else {
id = null;
}
NodeList nodes = propElem.getChildNodes(); NodeList nodes = propElem.getChildNodes();
int length = nodes.getLength(); int length = nodes.getLength();
......
...@@ -45,6 +45,7 @@ import org.w3c.dom.Element; ...@@ -45,6 +45,7 @@ import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream; import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
...@@ -55,7 +56,22 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; ...@@ -55,7 +56,22 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
*/ */
public final class DOMSignedInfo extends DOMStructure implements SignedInfo { public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
/**
* The maximum number of references per Manifest, if secure validation is
* enabled.
*/
public static final int MAXIMUM_REFERENCE_COUNT = 30;
private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom");
/** Signature - NOT Recommended RSAwithMD5 */
private static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 =
Constants.MoreAlgorithmsSpecNS + "rsa-md5";
/** HMAC - NOT Recommended HMAC-MD5 */
private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 =
Constants.MoreAlgorithmsSpecNS + "hmac-md5";
private List references; private List references;
private CanonicalizationMethod canonicalizationMethod; private CanonicalizationMethod canonicalizationMethod;
private SignatureMethod signatureMethod; private SignatureMethod signatureMethod;
...@@ -143,12 +159,31 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { ...@@ -143,12 +159,31 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
Element smElem = DOMUtils.getNextSiblingElement(cmElem); Element smElem = DOMUtils.getNextSiblingElement(cmElem);
signatureMethod = DOMSignatureMethod.unmarshal(smElem); signatureMethod = DOMSignatureMethod.unmarshal(smElem);
boolean secVal = Utils.secureValidation(context);
String sigMethAlg = signatureMethod.getAlgorithm();
if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(sigMethAlg)
|| ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(sigMethAlg))))
{
throw new MarshalException("It is forbidden to use algorithm " +
signatureMethod +
" when secure validation is enabled");
}
// unmarshal References // unmarshal References
ArrayList refList = new ArrayList(5); ArrayList refList = new ArrayList(5);
Element refElem = DOMUtils.getNextSiblingElement(smElem); Element refElem = DOMUtils.getNextSiblingElement(smElem);
int refCount = 0;
while (refElem != null) { while (refElem != null) {
refList.add(new DOMReference(refElem, context, provider)); refList.add(new DOMReference(refElem, context, provider));
refElem = DOMUtils.getNextSiblingElement(refElem); refElem = DOMUtils.getNextSiblingElement(refElem);
refCount++;
if (secVal && (refCount > MAXIMUM_REFERENCE_COUNT)) {
String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT +
" references per SignedInfo are allowed with" +
" secure validation";
throw new MarshalException(error);
}
} }
references = Collections.unmodifiableList(refList); references = Collections.unmodifiableList(refList);
} }
......
...@@ -31,7 +31,7 @@ import org.w3c.dom.Element; ...@@ -31,7 +31,7 @@ import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import com.sun.org.apache.xml.internal.security.Init; import com.sun.org.apache.xml.internal.security.Init;
import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
...@@ -68,8 +68,11 @@ public class DOMURIDereferencer implements URIDereferencer { ...@@ -68,8 +68,11 @@ public class DOMURIDereferencer implements URIDereferencer {
Attr uriAttr = (Attr) domRef.getHere(); Attr uriAttr = (Attr) domRef.getHere();
String uri = uriRef.getURI(); String uri = uriRef.getURI();
DOMCryptoContext dcc = (DOMCryptoContext) context; DOMCryptoContext dcc = (DOMCryptoContext) context;
String baseURI = context.getBaseURI();
// Check if same-document URI and register ID boolean secVal = Utils.secureValidation(context);
// Check if same-document URI and already registered on the context
if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') { if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') {
String id = uri.substring(1); String id = uri.substring(1);
...@@ -79,19 +82,38 @@ public class DOMURIDereferencer implements URIDereferencer { ...@@ -79,19 +82,38 @@ public class DOMURIDereferencer implements URIDereferencer {
id = id.substring(i1+1, i2); id = id.substring(i1+1, i2);
} }
// this is a bit of a hack to check for registered Node refElem = dcc.getElementById(id);
// IDRefs and manually register them with Apache's IdResolver if (refElem != null) {
// map which includes builtin schema knowledge of DSig/Enc IDs if (secVal) {
Node referencedElem = dcc.getElementById(id); Element start =
if (referencedElem != null) { refElem.getOwnerDocument().getDocumentElement();
IdResolver.registerElementById((Element) referencedElem, id); if (!XMLUtils.protectAgainstWrappingAttack(start,
(Element)refElem,
id)) {
String error = "Multiple Elements with the same ID " +
id + " were detected";
throw new URIReferenceException(error);
}
}
XMLSignatureInput result = new XMLSignatureInput(refElem);
if (!uri.substring(1).startsWith("xpointer(id(")) {
result.setExcludeComments(true);
}
result.setMIMEType("text/xml");
if (baseURI != null && baseURI.length() > 0) {
result.setSourceURI(baseURI.concat(uriAttr.getNodeValue()));
} else {
result.setSourceURI(uriAttr.getNodeValue());
}
return new ApacheNodeSetData(result);
} }
} }
try { try {
String baseURI = context.getBaseURI();
ResourceResolver apacheResolver = ResourceResolver apacheResolver =
ResourceResolver.getInstance(uriAttr, baseURI); ResourceResolver.getInstance(uriAttr, baseURI, secVal);
XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI); XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI);
if (in.isOctetStream()) { if (in.isOctetStream()) {
return new ApacheOctetStreamData(in); return new ApacheOctetStreamData(in);
......
...@@ -38,8 +38,6 @@ import javax.xml.crypto.dsig.dom.DOMSignContext; ...@@ -38,8 +38,6 @@ import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.spec.*; import javax.xml.crypto.dsig.spec.*;
import com.sun.org.apache.xml.internal.security.utils.IdResolver;
/** /**
* Useful static DOM utility methods. * Useful static DOM utility methods.
* *
...@@ -107,7 +105,7 @@ public class DOMUtils { ...@@ -107,7 +105,7 @@ public class DOMUtils {
public static void setAttributeID(Element elem, String name, String value) { public static void setAttributeID(Element elem, String name, String value) {
if (value == null) return; if (value == null) return;
elem.setAttributeNS(null, name, value); elem.setAttributeNS(null, name, value);
IdResolver.registerElementById(elem, value); elem.setIdAttributeNS(null, name, true);
} }
/** /**
......
...@@ -32,6 +32,7 @@ import javax.xml.crypto.dsig.*; ...@@ -32,6 +32,7 @@ import javax.xml.crypto.dsig.*;
import java.security.Provider; import java.security.Provider;
import java.util.*; import java.util.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -91,7 +92,14 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { ...@@ -91,7 +92,14 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject {
Provider provider) throws MarshalException { Provider provider) throws MarshalException {
// unmarshal attributes // unmarshal attributes
this.encoding = DOMUtils.getAttributeValue(objElem, "Encoding"); this.encoding = DOMUtils.getAttributeValue(objElem, "Encoding");
this.id = DOMUtils.getAttributeValue(objElem, "Id");
Attr attr = objElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
this.id = attr.getValue();
objElem.setIdAttributeNode(attr, true);
} else {
this.id = null;
}
this.mimeType = DOMUtils.getAttributeValue(objElem, "MimeType"); this.mimeType = DOMUtils.getAttributeValue(objElem, "MimeType");
NodeList nodes = objElem.getChildNodes(); NodeList nodes = objElem.getChildNodes();
......
...@@ -50,6 +50,7 @@ import java.util.HashMap; ...@@ -50,6 +50,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -492,7 +493,13 @@ public final class DOMXMLSignature extends DOMStructure ...@@ -492,7 +493,13 @@ public final class DOMXMLSignature extends DOMStructure
throw new MarshalException(bde); throw new MarshalException(bde);
} }
id = DOMUtils.getAttributeValue(sigValueElem, "Id"); Attr attr = sigValueElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
id = attr.getValue();
sigValueElem.setIdAttributeNode(attr, true);
} else {
id = null;
}
this.sigValueElem = sigValueElem; this.sigValueElem = sigValueElem;
} }
......
...@@ -30,6 +30,7 @@ import java.io.ByteArrayOutputStream; ...@@ -30,6 +30,7 @@ import java.io.ByteArrayOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import javax.xml.crypto.XMLCryptoContext;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
...@@ -104,4 +105,13 @@ public final class Utils { ...@@ -104,4 +105,13 @@ public final class Utils {
public static boolean sameDocumentURI(String uri) { public static boolean sameDocumentURI(String uri) {
return (uri != null && (uri.length() == 0 || uri.charAt(0) == '#')); return (uri != null && (uri.length() == 0 || uri.charAt(0) == '#'));
} }
static boolean secureValidation(XMLCryptoContext xc) {
return getBoolean(xc, "org.jcp.xml.dsig.secureValidation");
}
private static boolean getBoolean(XMLCryptoContext xc, String name) {
Boolean value = (Boolean)xc.getProperty(name);
return (value != null && value.booleanValue());
}
} }
...@@ -197,11 +197,13 @@ package.access=sun.,\ ...@@ -197,11 +197,13 @@ package.access=sun.,\
com.sun.org.apache.xalan.internal.xsltc.trax.,\ com.sun.org.apache.xalan.internal.xsltc.trax.,\
com.sun.org.apache.xalan.internal.xsltc.util.,\ com.sun.org.apache.xalan.internal.xsltc.util.,\
com.sun.org.apache.xml.internal.res.,\ com.sun.org.apache.xml.internal.res.,\
com.sun.org.apache.xml.internal.security.,\
com.sun.org.apache.xml.internal.serializer.utils.,\ com.sun.org.apache.xml.internal.serializer.utils.,\
com.sun.org.apache.xml.internal.utils.,\ com.sun.org.apache.xml.internal.utils.,\
com.sun.org.glassfish.,\ com.sun.org.glassfish.,\
com.oracle.xmlns.internal.,\ com.oracle.xmlns.internal.,\
com.oracle.webservices.internal.,\ com.oracle.webservices.internal.,\
org.jcp.xml.dsig.internal.,\
jdk.internal.,\ jdk.internal.,\
jdk.nashorn.internal.,\ jdk.nashorn.internal.,\
jdk.nashorn.tools. jdk.nashorn.tools.
...@@ -238,11 +240,13 @@ package.definition=sun.,\ ...@@ -238,11 +240,13 @@ package.definition=sun.,\
com.sun.org.apache.xalan.internal.xsltc.trax.,\ com.sun.org.apache.xalan.internal.xsltc.trax.,\
com.sun.org.apache.xalan.internal.xsltc.util.,\ com.sun.org.apache.xalan.internal.xsltc.util.,\
com.sun.org.apache.xml.internal.res.,\ com.sun.org.apache.xml.internal.res.,\
com.sun.org.apache.xml.internal.security.,\
com.sun.org.apache.xml.internal.serializer.utils.,\ com.sun.org.apache.xml.internal.serializer.utils.,\
com.sun.org.apache.xml.internal.utils.,\ com.sun.org.apache.xml.internal.utils.,\
com.sun.org.glassfish.,\ com.sun.org.glassfish.,\
com.oracle.xmlns.internal.,\ com.oracle.xmlns.internal.,\
com.oracle.webservices.internal.,\ com.oracle.webservices.internal.,\
org.jcp.xml.dsig.internal.,\
jdk.internal.,\ jdk.internal.,\
jdk.nashorn.internal.,\ jdk.nashorn.internal.,\
jdk.nashorn.tools. jdk.nashorn.tools.
......
...@@ -198,11 +198,13 @@ package.access=sun.,\ ...@@ -198,11 +198,13 @@ package.access=sun.,\
com.sun.org.apache.xalan.internal.xsltc.trax.,\ com.sun.org.apache.xalan.internal.xsltc.trax.,\
com.sun.org.apache.xalan.internal.xsltc.util.,\ com.sun.org.apache.xalan.internal.xsltc.util.,\
com.sun.org.apache.xml.internal.res.,\ com.sun.org.apache.xml.internal.res.,\
com.sun.org.apache.xml.internal.security.,\
com.sun.org.apache.xml.internal.serializer.utils.,\ com.sun.org.apache.xml.internal.serializer.utils.,\
com.sun.org.apache.xml.internal.utils.,\ com.sun.org.apache.xml.internal.utils.,\
com.sun.org.glassfish.,\ com.sun.org.glassfish.,\
com.oracle.xmlns.internal.,\ com.oracle.xmlns.internal.,\
com.oracle.webservices.internal.,\ com.oracle.webservices.internal.,\
org.jcp.xml.dsig.internal.,\
jdk.internal.,\ jdk.internal.,\
jdk.nashorn.internal.,\ jdk.nashorn.internal.,\
jdk.nashorn.tools.,\ jdk.nashorn.tools.,\
...@@ -239,11 +241,13 @@ package.definition=sun.,\ ...@@ -239,11 +241,13 @@ package.definition=sun.,\
com.sun.org.apache.xalan.internal.xsltc.trax.,\ com.sun.org.apache.xalan.internal.xsltc.trax.,\
com.sun.org.apache.xalan.internal.xsltc.util.,\ com.sun.org.apache.xalan.internal.xsltc.util.,\
com.sun.org.apache.xml.internal.res.,\ com.sun.org.apache.xml.internal.res.,\
com.sun.org.apache.xml.internal.security.,\
com.sun.org.apache.xml.internal.serializer.utils.,\ com.sun.org.apache.xml.internal.serializer.utils.,\
com.sun.org.apache.xml.internal.utils.,\ com.sun.org.apache.xml.internal.utils.,\
com.sun.org.glassfish.,\ com.sun.org.glassfish.,\
com.oracle.xmlns.internal.,\ com.oracle.xmlns.internal.,\
com.oracle.webservices.internal.,\ com.oracle.webservices.internal.,\
org.jcp.xml.dsig.internal.,\
jdk.internal.,\ jdk.internal.,\
jdk.nashorn.internal.,\ jdk.nashorn.internal.,\
jdk.nashorn.tools.,\ jdk.nashorn.tools.,\
......
...@@ -199,11 +199,13 @@ package.access=sun.,\ ...@@ -199,11 +199,13 @@ package.access=sun.,\
com.sun.org.apache.xalan.internal.xsltc.trax.,\ com.sun.org.apache.xalan.internal.xsltc.trax.,\
com.sun.org.apache.xalan.internal.xsltc.util.,\ com.sun.org.apache.xalan.internal.xsltc.util.,\
com.sun.org.apache.xml.internal.res.,\ com.sun.org.apache.xml.internal.res.,\
com.sun.org.apache.xml.internal.security.,\
com.sun.org.apache.xml.internal.serializer.utils.,\ com.sun.org.apache.xml.internal.serializer.utils.,\
com.sun.org.apache.xml.internal.utils.,\ com.sun.org.apache.xml.internal.utils.,\
com.sun.org.glassfish.,\ com.sun.org.glassfish.,\
com.oracle.xmlns.internal.,\ com.oracle.xmlns.internal.,\
com.oracle.webservices.internal.,\ com.oracle.webservices.internal.,\
org.jcp.xml.dsig.internal.,\
jdk.internal.,\ jdk.internal.,\
jdk.nashorn.internal.,\ jdk.nashorn.internal.,\
jdk.nashorn.tools. jdk.nashorn.tools.
...@@ -239,11 +241,13 @@ package.definition=sun.,\ ...@@ -239,11 +241,13 @@ package.definition=sun.,\
com.sun.org.apache.xalan.internal.xsltc.trax.,\ com.sun.org.apache.xalan.internal.xsltc.trax.,\
com.sun.org.apache.xalan.internal.xsltc.util.,\ com.sun.org.apache.xalan.internal.xsltc.util.,\
com.sun.org.apache.xml.internal.res.,\ com.sun.org.apache.xml.internal.res.,\
com.sun.org.apache.xml.internal.security.,\
com.sun.org.apache.xml.internal.serializer.utils.,\ com.sun.org.apache.xml.internal.serializer.utils.,\
com.sun.org.apache.xml.internal.utils.,\ com.sun.org.apache.xml.internal.utils.,\
com.sun.org.glassfish.,\ com.sun.org.glassfish.,\
com.oracle.xmlns.internal.,\ com.oracle.xmlns.internal.,\
com.oracle.webservices.internal.,\ com.oracle.webservices.internal.,\
org.jcp.xml.dsig.internal.,\
jdk.internal.,\ jdk.internal.,\
jdk.nashorn.internal.,\ jdk.nashorn.internal.,\
jdk.nashorn.tools. jdk.nashorn.tools.
......
...@@ -198,11 +198,13 @@ package.access=sun.,\ ...@@ -198,11 +198,13 @@ package.access=sun.,\
com.sun.org.apache.xalan.internal.xsltc.trax.,\ com.sun.org.apache.xalan.internal.xsltc.trax.,\
com.sun.org.apache.xalan.internal.xsltc.util.,\ com.sun.org.apache.xalan.internal.xsltc.util.,\
com.sun.org.apache.xml.internal.res.,\ com.sun.org.apache.xml.internal.res.,\
com.sun.org.apache.xml.internal.security.,\
com.sun.org.apache.xml.internal.serializer.utils.,\ com.sun.org.apache.xml.internal.serializer.utils.,\
com.sun.org.apache.xml.internal.utils.,\ com.sun.org.apache.xml.internal.utils.,\
com.sun.org.glassfish.,\ com.sun.org.glassfish.,\
com.oracle.xmlns.internal.,\ com.oracle.xmlns.internal.,\
com.oracle.webservices.internal.,\ com.oracle.webservices.internal.,\
org.jcp.xml.dsig.internal.,\
jdk.internal.,\ jdk.internal.,\
jdk.nashorn.internal.,\ jdk.nashorn.internal.,\
jdk.nashorn.tools.,\ jdk.nashorn.tools.,\
...@@ -239,11 +241,13 @@ package.definition=sun.,\ ...@@ -239,11 +241,13 @@ package.definition=sun.,\
com.sun.org.apache.xalan.internal.xsltc.trax.,\ com.sun.org.apache.xalan.internal.xsltc.trax.,\
com.sun.org.apache.xalan.internal.xsltc.util.,\ com.sun.org.apache.xalan.internal.xsltc.util.,\
com.sun.org.apache.xml.internal.res.,\ com.sun.org.apache.xml.internal.res.,\
com.sun.org.apache.xml.internal.security.,\
com.sun.org.apache.xml.internal.serializer.utils.,\ com.sun.org.apache.xml.internal.serializer.utils.,\
com.sun.org.apache.xml.internal.utils.,\ com.sun.org.apache.xml.internal.utils.,\
com.sun.org.glassfish.,\ com.sun.org.glassfish.,\
com.oracle.xmlns.internal.,\ com.oracle.xmlns.internal.,\
com.oracle.webservices.internal.,\ com.oracle.webservices.internal.,\
org.jcp.xml.dsig.internal.,\
jdk.internal.,\ jdk.internal.,\
jdk.nashorn.internal.,\ jdk.nashorn.internal.,\
jdk.nashorn.tools.,\ jdk.nashorn.tools.,\
......
/* /*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
* @summary Basic unit tests for generating XML Signatures with JSR 105 * @summary Basic unit tests for generating XML Signatures with JSR 105
* @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
* X509KeySelector.java GenerationTests.java * X509KeySelector.java GenerationTests.java
* @run main GenerationTests * @run main/othervm GenerationTests
* @author Sean Mullan * @author Sean Mullan
*/ */
...@@ -487,6 +487,7 @@ public class GenerationTests { ...@@ -487,6 +487,7 @@ public class GenerationTests {
Collections.singletonList(obj), Collections.singletonList(obj),
"signature", null); "signature", null);
DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA"), doc); DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA"), doc);
dsc.setIdAttributeNS(nc, null, "Id");
sig.sign(dsc); sig.sign(dsc);
...@@ -494,6 +495,7 @@ public class GenerationTests { ...@@ -494,6 +495,7 @@ public class GenerationTests {
DOMValidateContext dvc = new DOMValidateContext DOMValidateContext dvc = new DOMValidateContext
(kvks, doc.getDocumentElement()); (kvks, doc.getDocumentElement());
dvc.setIdAttributeNS(nc, null, "Id");
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
if (sig.equals(sig2) == false) { if (sig.equals(sig2) == false) {
......
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -140,6 +140,10 @@ public class XMLDSigWithSecMgr implements Runnable { ...@@ -140,6 +140,10 @@ public class XMLDSigWithSecMgr implements Runnable {
// validate a signature with SecurityManager enabled // validate a signature with SecurityManager enabled
DOMValidateContext dvc = new DOMValidateContext DOMValidateContext dvc = new DOMValidateContext
(kp.getPublic(), envelope.getFirstChild()); (kp.getPublic(), envelope.getFirstChild());
// disable secure validation mode so that http reference will work
dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
sig = fac.unmarshalXMLSignature(dvc); sig = fac.unmarshalXMLSignature(dvc);
if (!sig.validate(dvc)) { if (!sig.validate(dvc)) {
throw new Exception throw new Exception
......
/* /*
* Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
* @summary Basic unit tests for validating XML Signatures with JSR 105 * @summary Basic unit tests for validating XML Signatures with JSR 105
* @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
* X509KeySelector.java ValidationTests.java * X509KeySelector.java ValidationTests.java
* @run main ValidationTests * @run main/othervm ValidationTests
* @author Sean Mullan * @author Sean Mullan
*/ */
import java.io.File; import java.io.File;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册