diff options
Diffstat (limited to 'moaSig/moa-sig-lib/src/main/java/at')
28 files changed, 666 insertions, 3338 deletions
diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TSLConfiguration.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TSLConfiguration.java index 0e0c82c..642c28d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TSLConfiguration.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TSLConfiguration.java @@ -28,6 +28,7 @@ package at.gv.egovernment.moa.spss.api.common; import iaik.xml.crypto.utils.URI;
import java.util.Date;
+import java.util.List;
/**
@@ -78,5 +79,9 @@ public interface TSLConfiguration { * @return
*/
public URI getWorkingDirectoryAsURI();
+
+ public List<java.net.URI> getQualifierForQC();
+
+ public List<java.net.URI> getQualifierForSSCD();
}
diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TSLConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TSLConfigurationImpl.java index 4d69ed7..6fa813f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TSLConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TSLConfigurationImpl.java @@ -26,7 +26,9 @@ package at.gv.egovernment.moa.spss.api.impl; import iaik.xml.crypto.utils.URI;
+import java.util.ArrayList;
import java.util.Date;
+import java.util.List;
import at.gv.egovernment.moa.spss.api.common.TSLConfiguration;
@@ -53,7 +55,10 @@ public class TSLConfigurationImpl implements TSLConfiguration { /** Working directory */
private URI workingDirectoryAsURI;
-
+
+ private List<java.net.URI> qualifierForQC = new ArrayList<java.net.URI>();
+ private List<java.net.URI> qualifierForSSCD = new ArrayList<java.net.URI>();
+
public String getEuTSLUrl() {
return this.euTSLUrl;
}
@@ -94,7 +99,21 @@ public class TSLConfigurationImpl implements TSLConfiguration { this.workingDirectoryAsURI = workingDirectoryAsURI;
}
-
+ public List<java.net.URI> getQualifierForQC() {
+ return qualifierForQC;
+ }
+
+ public List<java.net.URI> getQualifierForSSCD() {
+ return qualifierForSSCD;
+ }
+
+ public void addQualifierForQC(java.net.URI qualifier) {
+ qualifierForQC.add(qualifier);
+ }
+
+ public void addQualifierForSSCD(java.net.URI qualifier) {
+ qualifierForSSCD.add(qualifier);
+ }
}
diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TslInfosImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TslInfosImpl.java new file mode 100644 index 0000000..4c40a5f --- /dev/null +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TslInfosImpl.java @@ -0,0 +1,48 @@ +package at.gv.egovernment.moa.spss.api.impl; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import at.gv.egovernment.moa.spss.api.common.TslInfos; + +public class TslInfosImpl implements TslInfos { + + private String tslServiceTypeIdentifier; + private String tslServiceTypeStatus; + private List<String> tslServiceQualifier = new ArrayList<String>(); + private String tslCountry; + + public TslInfosImpl(String country, String tslServiceTypeStatus, String tslServiceTypeIdentifier, List<URI> tslCertificateQualifier) { + this.tslCountry = country; + this.tslServiceTypeStatus = tslServiceTypeStatus; + this.tslServiceTypeIdentifier = tslServiceTypeIdentifier; + + for (URI el : tslCertificateQualifier) + this.tslServiceQualifier.add(el.toString()); + + + } + + + @Override + public String getTslIssuerCountry() { + return tslCountry; + } + + @Override + public String getServiceTypeStatus() { + return tslServiceTypeStatus; + } + + @Override + public String getServiceTypeIdentifier() { + return tslServiceTypeIdentifier; + } + + @Override + public List<String> getQualifiers() { + return tslServiceQualifier; + } + +} diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationPartsBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationPartsBuilder.java index 6c826ad..1b47013 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationPartsBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationPartsBuilder.java @@ -42,6 +42,7 @@ import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.net.MalformedURLException; +import java.net.URISyntaxException; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; @@ -70,6 +71,7 @@ import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.Constants; import at.gv.egovernment.moaspss.util.DOMUtils; import at.gv.egovernment.moaspss.util.FileUtils; +import at.gv.egovernment.moaspss.util.MiscUtil; import at.gv.egovernment.moaspss.util.StringUtils; import at.gv.egovernment.moaspss.util.XPathUtils; @@ -1220,238 +1222,105 @@ public class ConfigurationPartsBuilder { * * @return The profile ID to profile mapping. */ - public Map buildTrustProfiles(String tslWorkingDir) + + public Map buildTrustProfiles() { Map trustProfiles = new HashMap(); NodeIterator profileIter = XPathUtils.selectNodeIterator(getConfigElem(), TRUST_PROFILE_XPATH); Element profileElem; - while ((profileElem = (Element) profileIter.nextNode()) != null) - { - String id = getElementValue(profileElem, CONF + "Id", null); - String trustAnchorsLocStr = getElementValue(profileElem, CONF + "TrustAnchorsLocation", null); - String signerCertsLocStr = getElementValue(profileElem, CONF + "SignerCertsLocation", null); - Element eutslElem = (Element) XPathUtils.selectSingleNode(profileElem, CONF + "EUTSL"); - boolean tslEnabled = false; - if (eutslElem != null) //EUTSL element found --> TSL enabled - tslEnabled = true; - - String countries = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + "CountrySelection", null); - - URI trustAnchorsLocURI = null; - try - { - trustAnchorsLocURI = new URI(trustAnchorsLocStr); - if (!trustAnchorsLocURI.isAbsolute()) { // make it absolute to the config file - trustAnchorsLocURI = new URI(configRoot_.toURL() + trustAnchorsLocStr); - } - } - catch (URIException e) { - warn("config.14", new Object[] { "uri", id, trustAnchorsLocStr }, e); - continue; - } - catch (MalformedURLException e) - { - warn("config.15", new Object[] {id}, e); - continue; - } - - File profileDir = new File(trustAnchorsLocURI.getPath()); - if (!profileDir.exists() || !profileDir.isDirectory()) { - warn("config.27", new Object[] { "uri", id }); - continue; - } - - - - if (trustProfiles.containsKey(id)) { - warn("config.04", new Object[] { "TrustProfile", id }); - continue; - } - - URI signerCertsLocURI = null; - if (signerCertsLocStr != null && !"".equals(signerCertsLocStr)) - { + while ((profileElem = (Element) profileIter.nextNode()) != null) { + //load basic TrustProfile information + + //check TrustProfileId + String id = getElementValue(profileElem, CONF + "Id", null); + if (MiscUtil.isEmpty(id)) { + warn("config.52", new Object[]{"Id des TrustProfiles ist leer."}); + continue; + + } + //cast profileId to lowercase (changed in 3.0.1) + id = id.trim().toLowerCase(); + if (trustProfiles.containsKey(id)) { + warn("config.04", new Object[] { "TrustProfile", id }); + continue; + } + + //check location of TrustAnchor directory + String trustAnchorsLocStr = getElementValue(profileElem, CONF + "TrustAnchorsLocation", null); + URI trustAnchorsLocURI = null; try { - signerCertsLocURI = new URI(signerCertsLocStr); - if (!signerCertsLocURI.isAbsolute()) signerCertsLocURI = new URI(configRoot_.toURL() + signerCertsLocStr); - - File signerCertsDir = new File(signerCertsLocURI.getPath()); - if (!signerCertsDir.exists() || !signerCertsDir.isDirectory()) { - warn("config.27", new Object[] { "signerCertsUri", id }); - continue; + trustAnchorsLocURI = new URI(trustAnchorsLocStr); + if (!trustAnchorsLocURI.isAbsolute()) { // make it absolute to the config file + trustAnchorsLocURI = new URI(configRoot_.toURL() + trustAnchorsLocStr); } } catch (URIException e) { - warn("config.14", new Object[] { "signerCertsUri", id, trustAnchorsLocStr }, e); + warn("config.14", new Object[] { "uri", id, trustAnchorsLocStr }, e); continue; } - catch (MalformedURLException e) { + catch (MalformedURLException e) + { warn("config.15", new Object[] {id}, e); continue; } - } - - signerCertsLocStr = (signerCertsLocURI != null) ? signerCertsLocURI.toString() : null; - - TrustProfile profile = null; - - if (tslEnabled) { - // create new trust anchor location (=tslworking trust profile) - File fTslWorkingDir = new File(tslWorkingDir); - File tp = new File(fTslWorkingDir, "trustprofiles"); - if (!tp.exists()) - tp.mkdir(); - if (!tp.isDirectory()) { - error("config.50", new Object[] { tp.getPath() }); - } - - File tpid = new File(tp, id); - if (!tpid.exists()) - tpid.mkdir(); - if (!tpid.isDirectory()) { - error("config.50", new Object[] { tpid.getPath() }); - } - - - // create profile - profile = new TrustProfile(id, tpid.getAbsolutePath(), signerCertsLocStr, tslEnabled, countries); - - // set original uri (save original trust anchor location) - profile.setUriOrig(trustAnchorsLocURI.getPath()); - - // delete files in tslworking trust profile - File[] files = tpid.listFiles(); - for (File file : files) - file.delete(); - - // copy files from trustAnchorsLocURI into tslworking trust profile kopieren - File src = new File(trustAnchorsLocURI.getPath()); - files = src.listFiles(); - for (File file : files) { - FileUtils.copyFile(file, new File(tpid, file.getName())); - } - - - } else { - - profile = new TrustProfile(id, trustAnchorsLocURI.toString(), signerCertsLocStr, tslEnabled, countries); - - } - - trustProfiles.put(id, profile); - - } - - return trustProfiles; - } - - /** - * Build the trust profile mapping. - * - * @return The profile ID to profile mapping. - */ - public Map buildTrustProfiles() - { - Map trustProfiles = new HashMap(); - NodeIterator profileIter = XPathUtils.selectNodeIterator(getConfigElem(), TRUST_PROFILE_XPATH); - Element profileElem; - - while ((profileElem = (Element) profileIter.nextNode()) != null) - { - String id = getElementValue(profileElem, CONF + "Id", null); - String trustAnchorsLocStr = getElementValue(profileElem, CONF + "TrustAnchorsLocation", null); - String signerCertsLocStr = getElementValue(profileElem, CONF + "SignerCertsLocation", null); - - URI trustAnchorsLocURI = null; - try - { - trustAnchorsLocURI = new URI(trustAnchorsLocStr); - if (!trustAnchorsLocURI.isAbsolute()) { // make it absolute to the config file - trustAnchorsLocURI = new URI(configRoot_.toURL() + trustAnchorsLocStr); + File profileDir = new File(trustAnchorsLocURI.getPath()); + if (!profileDir.exists() || !profileDir.isDirectory()) { + warn("config.27", new Object[] { "uri", id }); + continue; } - } - catch (URIException e) { - warn("config.14", new Object[] { "uri", id, trustAnchorsLocStr }, e); - continue; - } - catch (MalformedURLException e) - { - warn("config.15", new Object[] {id}, e); - continue; - } - File profileDir = new File(trustAnchorsLocURI.getPath()); - if (!profileDir.exists() || !profileDir.isDirectory()) { - warn("config.27", new Object[] { "uri", id }); - continue; - } - - - - if (trustProfiles.containsKey(id)) { - warn("config.04", new Object[] { "TrustProfile", id }); - continue; - } - - URI signerCertsLocURI = null; - if (signerCertsLocStr != null && !"".equals(signerCertsLocStr)) - { - try + //check signerCertsLocation URL + String signerCertsLocStr = getElementValue(profileElem, CONF + "SignerCertsLocation", null); + URI signerCertsLocURI = null; + if (signerCertsLocStr != null && !"".equals(signerCertsLocStr)) { - signerCertsLocURI = new URI(signerCertsLocStr); - if (!signerCertsLocURI.isAbsolute()) signerCertsLocURI = new URI(configRoot_.toURL() + signerCertsLocStr); - - File signerCertsDir = new File(signerCertsLocURI.getPath()); - if (!signerCertsDir.exists() || !signerCertsDir.isDirectory()) { - warn("config.27", new Object[] { "signerCertsUri", id }); + try + { + signerCertsLocURI = new URI(signerCertsLocStr); + if (!signerCertsLocURI.isAbsolute()) signerCertsLocURI = new URI(configRoot_.toURL() + signerCertsLocStr); + + File signerCertsDir = new File(signerCertsLocURI.getPath()); + if (!signerCertsDir.exists() || !signerCertsDir.isDirectory()) { + warn("config.27", new Object[] { "signerCertsUri", id }); + continue; + } + } + catch (URIException e) { + warn("config.14", new Object[] { "signerCertsUri", id, trustAnchorsLocStr }, e); continue; } - } - catch (URIException e) { - warn("config.14", new Object[] { "signerCertsUri", id, trustAnchorsLocStr }, e); - continue; - } - catch (MalformedURLException e) { - warn("config.15", new Object[] {id}, e); - continue; - } - } - - signerCertsLocStr = (signerCertsLocURI != null) ? signerCertsLocURI.toString() : null; - - TrustProfile profile = null; - - profile = new TrustProfile(id, trustAnchorsLocURI.toString(), signerCertsLocStr, false, null); + catch (MalformedURLException e) { + warn("config.15", new Object[] {id}, e); + continue; + } + } + signerCertsLocStr = (signerCertsLocURI != null) ? signerCertsLocURI.toString() : null; + + + //check if TSL support is enabled + Element eutslElem = (Element) XPathUtils.selectSingleNode(profileElem, CONF + "EUTSL"); + boolean tslEnabled = false; + if (eutslElem != null) //EUTSL element found --> TSL enabled + tslEnabled = true; + + //load TSL configuration + String countries = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + "CountrySelection", null); + String allowedTspStatus = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + "AllowedTSPStatus", null); + String allowedTspServiceTypes = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + "AllowedTSPServiceTypes", null); - trustProfiles.put(id, profile); + + //create profile configuration + TrustProfile profile = new TrustProfile(id, trustAnchorsLocURI.toString(), signerCertsLocStr, + tslEnabled, countries, allowedTspStatus, allowedTspServiceTypes); + trustProfiles.put(id, profile); } return trustProfiles; } - - /** - * checks if a trustprofile with TSL support is enabled - * - * @return true if TSL support is enabled in at least one trustprofile, else false - */ - public boolean checkTrustProfilesTSLenabled() - { - NodeIterator profileIter = XPathUtils.selectNodeIterator(getConfigElem(), TRUST_PROFILE_XPATH); - Element profileElem; - - boolean tslSupportEnabled = false; - while ((profileElem = (Element) profileIter.nextNode()) != null) { - Element eutslElem = (Element) XPathUtils.selectSingleNode(profileElem, CONF + "EUTSL"); - if (eutslElem != null) //EUTSL element found --> TSL enabled - tslSupportEnabled = true; - } - - return tslSupportEnabled; - } - + /** * Returns the location of the certificate store. * @@ -1805,6 +1674,44 @@ public class ConfigurationPartsBuilder { debug("config.39", new Object[] { "WorkingDirectory", workingDirectoryStr }); } + String qcQualifier = getElementValue(getConfigElem(), TSL_CONFIGURATION_XPATH + CONF + "Evaluation/" + CONF + "QCQualifier", null); + if (MiscUtil.isEmpty(qcQualifier)) + info("config.39", new Object[] { "Evaluation/QCQualifier", " EMPTY" }); + + else { + String[] qcQualList = qcQualifier.split(","); + for (String el : qcQualList) { + try { + tslconfiguration.addQualifierForQC(new java.net.URI(el.trim())); + //info("config.39", new Object[] { "Evaluation/QCQualifier", el.trim() }); + + } catch (URISyntaxException e) { + warn("config.39", new Object[] { "Evaluation/QCQualifier", el.trim() }, e); + + } + + } + } + + String sscdQualifier = getElementValue(getConfigElem(), TSL_CONFIGURATION_XPATH + CONF + "Evaluation/" + CONF + "SSCDQualifier", null); + if (MiscUtil.isEmpty(qcQualifier)) + info("config.39", new Object[] { "Evaluation/SSCDQualifier", " EMPTY" }); + + else { + String[] sscdQualList = sscdQualifier.split(","); + for (String el : sscdQualList) { + try { + tslconfiguration.addQualifierForSSCD(new java.net.URI(el.trim())); + //info("config.39", new Object[] { "Evaluation/SSCDQualifier", el.trim() }); + + } catch (URISyntaxException e) { + warn("config.39", new Object[] { "Evaluation/SSCDQualifier", el.trim() }, e); + + } + + } + } + // convert update schedule starting time to Date object Calendar Cal = DatatypeConverter.parseDateTime(updateScheduleStartTime); Date updateScheduleStartTimeDate = Cal.getTime(); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationProvider.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationProvider.java index d777d8f..79ef1d2 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationProvider.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationProvider.java @@ -51,6 +51,7 @@ import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.DOMUtils; +import at.gv.egovernment.moaspss.util.MiscUtil; /** * A class providing access to the MOA configuration data. @@ -354,17 +355,17 @@ public class ConfigurationProvider // build the internal datastructures try { builder = new ConfigurationPartsBuilder(configElem, configRoot); + + //build TSL configuration + tslconfiguration_ = builder.getTSLConfiguration(); - if (builder.checkTrustProfilesTSLenabled()) { - debug("TSL support enabled for at least one trustprofile."); - tslconfiguration_ = builder.getTSLConfiguration(); - trustProfiles = builder.buildTrustProfiles(tslconfiguration_.getWorkingDirectory()); - } - else { - tslconfiguration_ = null; - trustProfiles = builder.buildTrustProfiles(); - } + //build TrustProfile configuration + trustProfiles = builder.buildTrustProfiles(); + //check TSL configuration + checkTSLConfiguration(); + + digestMethodAlgorithmName = builder.getDigestMethodAlgorithmName(); canonicalizationAlgorithmName = builder.getCanonicalizationAlgorithmName(); @@ -401,13 +402,10 @@ public class ConfigurationProvider revocationArchiveJDBCDriverClass_ = builder.getRevocationArchiveJDBCDriverClass(); - - //check TSL configuration - checkTSLConfiguration(); - + //TODO!!!! + certStoreLocation_ = builder.getCertStoreLocation(); - certStoreLocation_ = builder.getCertStoreLocation(); createTransformsInfoProfiles = builder.buildCreateTransformsInfoProfiles(); createSignatureEnvironmentProfiles = builder.buildCreateSignatureEnvironmentProfiles(); verifyTransformsInfoProfiles = builder.buildVerifyTransformsInfoProfiles(); @@ -451,19 +449,19 @@ public class ConfigurationProvider } } - private boolean checkTSLenableTrustprofilesExist()throws ConfigurationException { - boolean bTSLEnabledTPExist = false; - Iterator it = trustProfiles.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry pairs = (Map.Entry)it.next(); - TrustProfile tp = (TrustProfile) pairs.getValue(); - if (tp.isTSLEnabled()) - bTSLEnabledTPExist = bTSLEnabledTPExist || true; - } - - return bTSLEnabledTPExist; - - } +// private boolean checkTSLenableTrustprofilesExist()throws ConfigurationException { +// boolean bTSLEnabledTPExist = false; +// Iterator it = trustProfiles.entrySet().iterator(); +// while (it.hasNext()) { +// Map.Entry pairs = (Map.Entry)it.next(); +// TrustProfile tp = (TrustProfile) pairs.getValue(); +// if (tp.isTSLEnabled()) +// bTSLEnabledTPExist = bTSLEnabledTPExist || true; +// } +// +// return bTSLEnabledTPExist; +// +// } private void checkTSLConfiguration() throws ConfigurationException { boolean bTSLEnabledTPExist = false; @@ -516,7 +514,7 @@ public class ConfigurationProvider return; } - System.setProperty("iaik.xml.crypto.tsl.BinaryHashCache.DIR", hashcache.getAbsolutePath()); +// System.setProperty("iaik.xml.crypto.tsl.BinaryHashCache.DIR", hashcache.getAbsolutePath()); // String hashcachedir = System.getProperty("iaik.xml.crypto.tsl.BinaryHashCache.DIR"); // System.out.println("Hashcache: " + hashcachedir); @@ -826,7 +824,14 @@ public class ConfigurationProvider * <code>null</code>, if none exists. */ public TrustProfile getTrustProfile(String id) { - return (TrustProfile) trustProfiles.get(id); + + if (MiscUtil.isNotEmpty(id)) { + id = id.trim().toLowerCase(); + return (TrustProfile) trustProfiles.get(id); + + } + + return null; } /** diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/TrustProfile.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/TrustProfile.java index 21063c7..f64643f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/TrustProfile.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/TrustProfile.java @@ -24,6 +24,15 @@ package at.gv.egovernment.moa.spss.server.config; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import at.gv.egovernment.moa.sig.tsl.TslConstants; +import at.gv.egovernment.moaspss.logging.Logger; +import at.gv.egovernment.moaspss.util.MiscUtil; import iaik.x509.X509Certificate; /** @@ -39,14 +48,15 @@ public class TrustProfile { private String uri; /** The URI giving the location of the allowed signer certificates. */ private String signerCertsUri; + /** Defines if Trustprofile makes use of EU TSL*/ private boolean tslEnabled; - /** The original URI (out of the configuration) giving the location of the trust profile (used when TSL is enabled) */ - private String uriOrig; /** The countries given */ - private String countries; - /** */ - private X509Certificate[] certificatesToBeRemoved; + private List<String> countries = new ArrayList<String>(); + + private List<URI> allowedTspStatus = new ArrayList<URI>(); + private List<URI> allowedTspServiceTypes = new ArrayList<URI>(); + /** * Create a <code>TrustProfile</code>. @@ -55,16 +65,90 @@ public class TrustProfile { * @param uri The URI of the <code>TrustProfile</code> to create. * @param signerCertsUri The URI of the location of the allowed signer * certificates of the <code>TrustProfile</code> to create. + * @param allowedTspServiceTypes + * @param allowedTspStatus */ - public TrustProfile(String id, String uri, String signerCertsUri, boolean tslEnabled, String countries) { + public TrustProfile(String id, String uri, String signerCertsUri, + boolean tslEnabled, String countries, String allowedTspStatus, String allowedTspServiceTypes) { this.id = id; this.uri = uri; this.signerCertsUri = signerCertsUri; + + //TSL configuration parameters this.tslEnabled = tslEnabled; - this.countries = countries; - this.certificatesToBeRemoved = new X509Certificate[0]; + + setCountries(countries); + Logger.debug("TrustProfile "+ id + " allows " + Arrays.toString(this.countries.toArray()) + " TSL countries"); + + setAllowedTspStatus(allowedTspStatus); + Logger.debug("TrustProfile "+ id + " allows " + Arrays.toString(this.allowedTspStatus.toArray()) + " TSP status identifier"); + + setAllowedTspServiceTypes(allowedTspServiceTypes); + Logger.debug("TrustProfile "+ id + " allows " + Arrays.toString(this.allowedTspServiceTypes.toArray()) + " TSL service-type identifier"); + } + private void setCountries(String countries) { + if (MiscUtil.isNotEmpty(countries)) { + String[] ccArray = countries.split(","); + for (String el : ccArray) + this.countries.add(el.trim()); + + } + } + + private void setAllowedTspStatus(String allowedTspStatus) { + if (MiscUtil.isNotEmpty(allowedTspStatus)) { + String[] ccArray = allowedTspStatus.split(","); + for (String el : ccArray) { + try { + this.allowedTspStatus.add(new URI(el.trim())); + + } catch (URISyntaxException e) { + Logger.warn("TrustProfile: " + this.id + " contains a non-valid TSP Status identifier (" + el + ")"); + + } + + } + + } else { + Logger.info("Use default set of TSP Status identifier"); + this.allowedTspStatus.addAll( + Arrays.asList( + TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.granted), + TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.recognisedatnationallevel), + TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.accredited), + TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.undersupervision))); + + } + + } + + private void setAllowedTspServiceTypes(String allowedTspServiceTypes) { + if (MiscUtil.isNotEmpty(allowedTspServiceTypes)) { + String[] ccArray = allowedTspServiceTypes.split(","); + for (String el : ccArray) { + try { + this.allowedTspStatus.add(new URI(el.trim())); + + } catch (URISyntaxException e) { + Logger.warn("TrustProfile: " + this.id + " contains a non-valid TSP Service-Type identifier (" + el + ")"); + + } + + } + + } else { + Logger.info("Use default set of TSP Service-Type identifier"); + this.allowedTspStatus.addAll( + Arrays.asList( + TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_TYPE_SHORT.CA_QC), + TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_TYPE_SHORT.TSA_QTST))); + + } + + } + /** * Return the ID of this <code>TrustProfile</code>. * @@ -83,14 +167,6 @@ public class TrustProfile { return uri; } - /** - * Return the original URI of this <code>TrustProfile</code>. - * - * @return The original URI of <code>TrustProfile</code>. - */ - public String getUriOrig() { - return uriOrig; - } /** * Return the URI giving the location of the allowed signer certificates @@ -112,21 +188,21 @@ public class TrustProfile { * Returns the given countries * @return Given countries */ - public String getCountries() { + public List<String> getCountries() { if (!tslEnabled) return null; else return countries; } - - - /** - * Sets the original URI of this <code>TrustProfile</code>. - * - * @return The original URI of <code>TrustProfile</code>. - */ - public void setUriOrig(String uriOrig) { - this.uriOrig = uriOrig; + + public List<URI> getAllowedTspStatus() { + return allowedTspStatus; + } + + public List<URI> getAllowedTspServiceTypes() { + return allowedTspServiceTypes; } + + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CertStoreConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CertStoreConfigurationImpl.java index a4f7660..1aa5f6a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CertStoreConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CertStoreConfigurationImpl.java @@ -30,9 +30,11 @@ import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import at.gv.egovernment.moa.sig.tsl.exception.TslException; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.logging.IaikLog; import at.gv.egovernment.moa.spss.server.logging.TransactionId; +import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; import iaik.logging.Log; import iaik.pki.store.certstore.CertStoreConfiguration; import iaik.pki.store.certstore.CertStoreParameters; @@ -68,7 +70,20 @@ public class CertStoreConfigurationImpl extends AbstractObservableConfiguration DirectoryCertStoreParameters dirParameters = new DirectoryCertStoreParametersImpl("MOA Directory CertStore", certStoreRoot, true, false); - parameters = new CertStoreParameters[] { dirParameters }; + if (TSLServiceFactory.isInitialized()) { + try { + CertStoreParameters tslCertStore = TSLServiceFactory.getTSLServiceClient().getCertStoreWithTSLCertificates(); + parameters = new CertStoreParameters[] { dirParameters, tslCertStore}; + + } catch (TslException e) { + logger.warn("TSL based CertStore initialisation FAILED.", e); + logger.warn("Only Directory based CertStore is used ... "); + parameters = new CertStoreParameters[] { dirParameters }; + } + + } else + parameters = new CertStoreParameters[] { dirParameters }; + } /** diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/PKIProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/PKIProfileImpl.java index 3f6998a..b776255 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/PKIProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/PKIProfileImpl.java @@ -27,11 +27,21 @@ import iaik.pki.PKIProfile; import iaik.pki.pathvalidation.ValidationProfile; import iaik.pki.revocation.RevocationProfile; import iaik.pki.store.truststore.TrustStoreProfile; +import iaik.pki.store.truststore.TrustStoreTypes; + +import java.util.Arrays; + +import at.gv.egovernment.moa.sig.tsl.exception.TslPKIException; +import at.gv.egovernment.moa.sig.tsl.pki.TslTrustStoreProfile; +import at.gv.egovernment.moa.sig.tsl.pki.chaining.ChainingTrustStoreProfile; import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; +import at.gv.egovernment.moa.spss.server.config.TrustProfile; import at.gv.egovernment.moa.spss.server.iaik.pki.pathvalidation.ValidationProfileImpl; import at.gv.egovernment.moa.spss.server.iaik.pki.revocation.RevocationProfileImpl; import at.gv.egovernment.moa.spss.server.iaik.pki.store.truststore.TrustStoreProfileImpl; +import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; +import at.gv.egovernment.moaspss.logging.Logger; /** * Implementation of the <code>PKIProfile</code> interface containing @@ -70,10 +80,58 @@ public class PKIProfileImpl implements PKIProfile { this.config = config; setRevocationProfile(new RevocationProfileImpl(config)); - setTrustStoreProfile(new TrustStoreProfileImpl(config, trustProfileID)); setValidationProfile(new ValidationProfileImpl(config)); + + //generate TrustStoreProfile from TrustStore configuration + internalTrustProfileBuilder(trustProfileID); + } + + private void internalTrustProfileBuilder(String trustProfileId) throws MOAApplicationException { + TrustProfile tp = (TrustProfile) config.getTrustProfile(trustProfileId); + if (tp != null) { + //build directory based trust store as default + + + if (tp.isTSLEnabled()) { + //build TSL truststore if enabled + TslTrustStoreProfile tslTrustStore; + try { + tslTrustStore = TSLServiceFactory.getTSLServiceClient(). + buildTrustStoreProfile( + tp.getCountries(), + tp.getAllowedTspStatus(), + tp.getAllowedTspServiceTypes(), + trustProfileId + "_TSL"); + + //build Directory based TrustStore + TrustStoreProfileImpl directoryTrustStore = new TrustStoreProfileImpl(trustProfileId + "_Directory", tp.getUri()); + + //generate a virtual truststore that concatenates the TSL TrustStore and the directory TrustStore + ChainingTrustStoreProfile chainedProfile = new ChainingTrustStoreProfile( + Arrays.asList(tslTrustStore, directoryTrustStore), + trustProfileId); + + //set this virtual truststore + setTrustStoreProfile(chainedProfile); + + } catch (TslPKIException e) { + Logger.error("Virtual TSL based TrustProfile generation FAILED.", e); + throw new MOAApplicationException("2900", new Object[] { trustProfileId }); + + } + + } else + setTrustStoreProfile(new TrustStoreProfileImpl(trustProfileId, tp.getUri())); + + } else { + throw new MOAApplicationException("2203", new Object[] { trustProfileId }); + + } + + } + /** * @see iaik.pki.PKIProfile#autoAddCertificates() */ diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/store/truststore/TrustStoreProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/store/truststore/TrustStoreProfileImpl.java index 50f237a..c9f4f28 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/store/truststore/TrustStoreProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/store/truststore/TrustStoreProfileImpl.java @@ -60,6 +60,25 @@ public class TrustStoreProfileImpl implements TrustStoreProfile { /** The URI of the trust profile.*/ private String URI; + + /** + * Create a new <code>TrustStoreProfileImpl</code>. + * + * @param config The MOA configuration data, from which trust store + * configuration data is read. + * @param trustProfileId The trust profile id on which this + * <code>TrustStoreProfile</code> is based. + * @throws MOAApplicationException The <code>trustProfileId</code> could not + * be found in the MOA configuration. + */ + public TrustStoreProfileImpl(String trustProfileId, String trustProfileUri) + throws MOAApplicationException { + id_ = trustProfileId; + setURI(trustProfileUri); + setType(TrustStoreTypes.DIRECTORY); + + } + /** * Create a new <code>TrustStoreProfileImpl</code>. * @@ -70,6 +89,7 @@ public class TrustStoreProfileImpl implements TrustStoreProfile { * @throws MOAApplicationException The <code>trustProfileId</code> could not * be found in the MOA configuration. */ + @Deprecated public TrustStoreProfileImpl( ConfigurationProvider config, String trustProfileId) diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/SystemInitializer.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/SystemInitializer.java index 28f0645..8ff0b12 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/SystemInitializer.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/SystemInitializer.java @@ -36,13 +36,13 @@ import java.util.Timer; import org.slf4j.LoggerFactory; +import at.gv.egovernment.moa.sig.tsl.config.TslConfigurationImpl; import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.api.common.TSLConfiguration; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.iaik.config.IaikConfigurator; import at.gv.egovernment.moa.spss.server.service.RevocationArchiveCleaner; -import at.gv.egovernment.moa.spss.tsl.connector.MOATSLVerifier; -import at.gv.egovernment.moa.spss.tsl.connector.TSLConnector; +import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; import at.gv.egovernment.moa.spss.tsl.timer.TSLUpdaterTimerTask; import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moaspss.logging.LogMsg; @@ -55,10 +55,6 @@ import iaik.asn1.ObjectID; import iaik.pki.store.certstore.CertStoreException; import iaik.pki.store.truststore.TrustStoreException; import iaik.server.ConfigurationData; -import iaik.xml.crypto.tsl.SecuredSAXParserFactoryImpl; -import iaik.xml.crypto.tsl.ex.TSLEngineDiedException; -import iaik.xml.crypto.tsl.ex.TSLSearchException; -import iaik.xml.crypto.tsl.verify.ITSLVerifierFactory; /** * MOA SP/SS web service initialization. @@ -150,55 +146,33 @@ public class SystemInitializer { ConfigurationProvider config = ConfigurationProvider.getInstance(); Logger.info("Building ConfigurationData"); ConfigurationData configData = new IaikConfigurator().configure(config); - + //initialize TSL module - TSLConfiguration tslconfig = config.getTSLConfiguration(); - - TSLConnector tslconnector = new TSLConnector(); - if (tslconfig != null) { - //Logger.info(new LogMsg(msg.getMessage("init.01", null))); - SecuredSAXParserFactoryImpl.newInstance(); - Logger.info(new LogMsg(msg.getMessage("config.41", null))); - - ITSLVerifierFactory.setITSLVerifier(new MOATSLVerifier()); + TSLConfiguration moaSPTslConfig = config.getTSLConfiguration(); + if (moaSPTslConfig != null) { + TslConfigurationImpl tslConfig = new TslConfigurationImpl(); + tslConfig.setEuTslURL(moaSPTslConfig.getEuTSLUrl()); + tslConfig.setTslWorkingDirectory(moaSPTslConfig.getWorkingDirectory()); - tslconnector.initialize(tslconfig.getEuTSLUrl(), tslconfig.getWorkingDirectory(), null, null); - - } - - //start TSL Update - TSLUpdaterTimerTask.tslconnector_ = tslconnector; - TSLUpdaterTimerTask.configData_ = configData; - TSLUpdaterTimerTask.update(); - - //initialize TSL Update Task - initTSLUpdateTask(tslconfig); - - runInitializer(config); + Logger.info(new LogMsg(msg.getMessage("config.41", null))); + TSLServiceFactory.initialize(tslConfig); + Logger.info("TSL-Service client initialization finished"); + + //initialize TSL Update Task + initTSLUpdateTask(moaSPTslConfig); + + } - Logger.info(new LogMsg(msg.getMessage("init.01", null))); + runInitializer(config); + Logger.info(new LogMsg(msg.getMessage("init.01", null))); + } catch (MOAException e) { - Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - } - catch (TSLEngineDiedException e) { - Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - } - catch (TSLSearchException e) { - Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - } - catch (CertStoreException e) { - Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - } catch (TrustStoreException e) { - Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - } catch (FileNotFoundException e) { Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - } catch (IOException e) { - Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - } catch (CertificateException e) { - Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - } catch (Throwable e) { + + } catch (Throwable e) { Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); throw new RuntimeException(e); + } finally { logger.info("Configuration initialized"); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationInvoker.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationInvoker.java index ba0474c..1508b42 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationInvoker.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationInvoker.java @@ -42,6 +42,7 @@ import at.gv.egovernment.moa.spss.api.cmsverify.CMSDataObject; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; import at.gv.egovernment.moa.spss.api.common.ExtendedCertificateCheckResult; +import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.config.TrustProfile; import at.gv.egovernment.moa.spss.server.logging.IaikLog; import at.gv.egovernment.moa.spss.server.logging.TransactionId; @@ -304,7 +305,7 @@ public class CMSSignatureVerificationInvoker { i++; } - qcsscdresult = CertificateUtils.checkQCSSCD(chain, trustProfile.isTSLEnabled()); + qcsscdresult = CertificateUtils.checkQCSSCD(chain, cmsResult.getSigningTime(), trustProfile.isTSLEnabled(), ConfigurationProvider.getInstance()); // get signer certificate issuer country code issuerCountryCode = CertificateUtils.getIssuerCountry((X509Certificate) list.get(0)); @@ -312,7 +313,8 @@ public class CMSSignatureVerificationInvoker { } responseBuilder.addResult(cmsResult, trustProfile, qcsscdresult.isQC(), qcsscdresult.isQCSourceTSL(), - qcsscdresult.isSSCD(), qcsscdresult.isSSCDSourceTSL(), issuerCountryCode, adesResults, extCheckResult); + qcsscdresult.isSSCD(), qcsscdresult.isSSCDSourceTSL(), issuerCountryCode, adesResults, extCheckResult, + qcsscdresult.getTslInfos()); } private void handlePDFResult(Object resultObject, VerifyCMSSignatureResponseBuilder responseBuilder, @@ -371,7 +373,7 @@ public class CMSSignatureVerificationInvoker { i++; } - qcsscdresult = CertificateUtils.checkQCSSCD(chain, trustProfile.isTSLEnabled()); + qcsscdresult = CertificateUtils.checkQCSSCD(chain, cmsResult.getSigningTime(), trustProfile.isTSLEnabled(), ConfigurationProvider.getInstance()); // get signer certificate issuer country code issuerCountryCode = CertificateUtils.getIssuerCountry((X509Certificate) list.get(0)); @@ -380,7 +382,7 @@ public class CMSSignatureVerificationInvoker { responseBuilder.addResult(cmsResult, trustProfile, qcsscdresult.isQC(), qcsscdresult.isQCSourceTSL(), qcsscdresult.isSSCD(), qcsscdresult.isSSCDSourceTSL(), issuerCountryCode, adesResults, - extCheckResult); + extCheckResult, qcsscdresult.getTslInfos()); } /** diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/IaikExceptionMapper.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/IaikExceptionMapper.java index 1136ff2..6e8448b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/IaikExceptionMapper.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/IaikExceptionMapper.java @@ -84,8 +84,7 @@ public class IaikExceptionMapper { { iaik.server.modules.xmlverify.SupplementException.class, "2230", MOAApplicationException.class }, { iaik.server.modules.xmlverify.TransformationException.class, "2265", MOAApplicationException.class }, { iaik.server.modules.xmlverify.TransformationParsingException.class, "2269", MOAApplicationException.class }, - { iaik.xml.crypto.tsl.ex.TSLEngineDiedException.class, "2290", MOAApplicationException.class }, - { iaik.xml.crypto.tsl.ex.TSLSearchException.class, "2290", MOAApplicationException.class } , + { at.gv.egovernment.moa.sig.tsl.exception.TslException.class, "2290", MOAApplicationException.class }, { iaik.server.modules.cmssign.CMSSignatureCreationException.class, "2300", MOAApplicationException.class } , @@ -157,20 +156,9 @@ public class IaikExceptionMapper { * @return A <code>MOAException</code> containing the message for the * given <code>IAIKException</code>. */ - public MOAException map(iaik.xml.crypto.tsl.ex.TSLSearchException tslSearchException) { + public MOAException map(at.gv.egovernment.moa.sig.tsl.exception.TslException tslSearchException) { return mapImpl(tslSearchException); } - - /** - * Map an <code>iaik.xml.crypto.tsl.ex.TSLEngineDiedException</code> to a <code>MOAException</code>. - * - * @param tslEngineDiedException The <code>iaik.xml.crypto.tsl.ex.TSLEngineDiedException</code> to map. - * @return A <code>MOAException</code> containing the message for the - * given <code>IAIKException</code>. - */ - public MOAException map(iaik.xml.crypto.tsl.ex.TSLEngineDiedException tslEngineDiedException) { - return mapImpl(tslEngineDiedException); - } /** * Map an <code>IAIKException</code> to a <code>MOAException</code>. diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyCMSSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyCMSSignatureResponseBuilder.java index fe2a9ad..5ada287 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyCMSSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyCMSSignatureResponseBuilder.java @@ -39,6 +39,7 @@ import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponseElemen import at.gv.egovernment.moa.spss.api.common.CheckResult; import at.gv.egovernment.moa.spss.api.common.ExtendedCertificateCheckResult; import at.gv.egovernment.moa.spss.api.common.SignerInfo; +import at.gv.egovernment.moa.spss.api.common.TslInfos; import at.gv.egovernment.moa.spss.server.config.TrustProfile; /** @@ -82,7 +83,7 @@ public class VerifyCMSSignatureResponseBuilder { * @throws MOAException */ public void addResult(CMSSignatureVerificationResult result, TrustProfile trustProfile, boolean checkQC, boolean qcSourceTSL, boolean checkSSCD, boolean sscdSourceTSL, String issuerCountryCode, List adesResults, - ExtendedCertificateCheckResult extendedCertificateCheckResult) + ExtendedCertificateCheckResult extendedCertificateCheckResult, TslInfos tslInfos) throws MOAException { CertificateValidationResult certResult = @@ -109,7 +110,8 @@ public class VerifyCMSSignatureResponseBuilder { checkSSCD, sscdSourceTSL, issuerCountryCode, - result.getSigningTime()); + result.getSigningTime(), + tslInfos); // add SignatureCheck element signatureCheck = factory.createCheckResult(signatureCheckCode, null); @@ -142,7 +144,7 @@ public class VerifyCMSSignatureResponseBuilder { * @throws MOAException */ public void addResult(PDFSignatureVerificationResult result, TrustProfile trustProfile, boolean checkQC, boolean qcSourceTSL, boolean checkSSCD, boolean sscdSourceTSL, String issuerCountryCode, List adesResults, - ExtendedCertificateCheckResult extendedCertificateCheckResult) + ExtendedCertificateCheckResult extendedCertificateCheckResult, TslInfos tslInfos) throws MOAException { CertificateValidationResult certResult = @@ -169,7 +171,8 @@ public class VerifyCMSSignatureResponseBuilder { checkSSCD, sscdSourceTSL, issuerCountryCode, - result.getSigningTime()); + result.getSigningTime(), + tslInfos); // add SignatureCheck element signatureCheck = factory.createCheckResult(signatureCheckCode, null); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationInvoker.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationInvoker.java index c3ebda4..827728c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationInvoker.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationInvoker.java @@ -277,8 +277,8 @@ public class XMLSignatureVerificationInvoker { chain[i] = (X509Certificate) it.next(); i++; } - - qcsscdresult = CertificateUtils.checkQCSSCD(chain, tp.isTSLEnabled()); + + qcsscdresult = CertificateUtils.checkQCSSCD(chain, plainResult.getSigningTime(), tp.isTSLEnabled(), config); } // get signer certificate issuer country code @@ -303,7 +303,7 @@ public class XMLSignatureVerificationInvoker { // build the response responseBuilder.setResult(plainResult, profile, signatureManifestCheck, certificateCheck, qcsscdresult.isQC(), qcsscdresult.isQCSourceTSL(), qcsscdresult.isSSCD(), - qcsscdresult.isSSCDSourceTSL(), tp.isTSLEnabled(), issuerCountryCode); + qcsscdresult.isSSCDSourceTSL(), tp.isTSLEnabled(), issuerCountryCode, qcsscdresult.getTslInfos()); return responseBuilder.getResponse(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/TSLServiceFactory.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/TSLServiceFactory.java new file mode 100644 index 0000000..83bcf3a --- /dev/null +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/TSLServiceFactory.java @@ -0,0 +1,47 @@ +package at.gv.egovernment.moa.spss.tsl; + +import at.gv.egovernment.moa.sig.tsl.TslClientFactory; +import at.gv.egovernment.moa.sig.tsl.api.ITslService; +import at.gv.egovernment.moa.sig.tsl.config.TslConfigurationImpl; +import at.gv.egovernment.moa.sig.tsl.exception.TslException; +import at.gv.egovernment.moa.spss.util.MessageProvider; +import at.gv.egovernment.moaspss.logging.LogMsg; +import at.gv.egovernment.moaspss.logging.Logger; + +public class TSLServiceFactory { + + private static ITslService tslClient = null; + + + public static void initialize(TslConfigurationImpl config) { + if (tslClient == null) { + try { + tslClient = TslClientFactory.buildTslService(config ); + + } catch (TslException e) { + Logger.fatal(new LogMsg(MessageProvider.getInstance().getMessage("init.05", new Object[]{e.getMessage()})), e); + + } + + } else { + Logger.error("TSL-Service client can only be initialized once."); + throw new IllegalStateException("TSL-Service client can only be initialized once."); + + } + + } + + public static boolean isInitialized() { + if (tslClient == null) + return false; + else + return true; + + } + + public static ITslService getTSLServiceClient() { + return tslClient; + + } + +} diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/config/Configurator.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/config/Configurator.java deleted file mode 100644 index 53e023f..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/config/Configurator.java +++ /dev/null @@ -1,130 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.config;
-
-import iaik.util.logging.GeneralLog;
-import iaik.xml.crypto.tsl.ex.TSLEngineDiedException;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-
-public class Configurator {
-
- private static final String _TMPDBFILENAME = "temp_tsl.sqlite";
-
- private static boolean _sqlMultithreaded;
- private static boolean _throwExceptions;
- private static boolean _logExceptions;
- private static boolean _throwWarnings;
- private static boolean _logWarnings;
- private static boolean _nullRedundancies;
- private static URL _euTSLURL;
- private static String _TSLWorkingDirectoryPath;
- private static String _dbFile;
- private static String _euTrustAnchorsPath;
- private static String _msTrustAnchorsPath;
-
-
- private static boolean _isInitialised = false;
-
-
- /**
- *
- */
- public static void initial(String euTSLURL, String TSLWorkingDirectoryPath, String jdbcURL, String jdbcDriverClass)
- throws TSLEngineDiedException {
-
-
- if (!_isInitialised) {
- try {
- _euTSLURL = new URL(euTSLURL);
- } catch (MalformedURLException e) {
- GeneralLog.err("Bad TSL URL: " + euTSLURL, e);
- throw new TSLEngineDiedException(e);
- }
-
- if (!TSLWorkingDirectoryPath.endsWith("/"))
- TSLWorkingDirectoryPath += "/";
-
- Configurator._TSLWorkingDirectoryPath = TSLWorkingDirectoryPath;
-
- initialDefaultConfig();
-
- _isInitialised = true;
- }
- }
-
- public static String get_TSLWorkingDirectoryPath() {
- return _TSLWorkingDirectoryPath;
- }
-
- public static String get_dbFile() {
- return _dbFile;
- }
-
- public static void set_dbFileName(String _dbFile) {
- Configurator._dbFile = _TSLWorkingDirectoryPath + _dbFile;
- }
-
- public static String get_euTrustAnchorsPath() {
- return _euTrustAnchorsPath;
- }
-
- public static String get_msTrustAnchorsPath() {
- return _msTrustAnchorsPath;
- }
-
- public static boolean is_sqlMultithreaded() {
- return _sqlMultithreaded;
- }
-
- public static boolean is_throwExceptions() {
- return _throwExceptions;
- }
-
- public static boolean is_logExceptions() {
- return _logExceptions;
- }
-
- public static boolean is_throwWarnings() {
- return _throwWarnings;
- }
-
- public static boolean is_logWarnings() {
- return _logWarnings;
- }
-
- public static boolean is_nullRedundancies() {
- return _nullRedundancies;
- }
-
- public static URL get_euTSLURL() {
- return _euTSLURL;
- }
-
- public static boolean is_isInitialised() {
- return _isInitialised;
- }
-
- public static String get_TempdbFile() {
- return _TSLWorkingDirectoryPath + _TMPDBFILENAME;
- }
-
- public static void set_euTrustAnchorsPath(String _euTrustAnchorsPath) {
- Configurator._euTrustAnchorsPath = _euTrustAnchorsPath;
- }
-
- public static void set_msTrustAnchorsPath(String _msTrustAnchorsPath) {
- Configurator._msTrustAnchorsPath = _msTrustAnchorsPath;
- }
-
- private static void initialDefaultConfig() {
- _sqlMultithreaded = false;
- _throwExceptions = true;
- _logExceptions = true;
- _throwWarnings = false;
- _logWarnings = true;
- _nullRedundancies = false;
- _dbFile = _TSLWorkingDirectoryPath + "tsl.sqlite";
- _euTrustAnchorsPath = _TSLWorkingDirectoryPath + "trust/eu/";
- _msTrustAnchorsPath = "/trust/ms/";
- }
-}
diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/MOATSLVerifier.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/MOATSLVerifier.java deleted file mode 100644 index 39b2f8c..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/MOATSLVerifier.java +++ /dev/null @@ -1,265 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.connector;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.security.cert.X509Certificate;
-import java.util.Iterator;
-import java.util.ListIterator;
-
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBIntrospector;
-import javax.xml.crypto.Data;
-import javax.xml.crypto.MarshalException;
-import javax.xml.crypto.NodeSetData;
-import javax.xml.crypto.URIReferenceException;
-import javax.xml.crypto.dom.DOMCryptoContext;
-import javax.xml.crypto.dsig.Reference;
-import javax.xml.crypto.dsig.SignedInfo;
-import javax.xml.crypto.dsig.Transform;
-import javax.xml.crypto.dsig.XMLSignature;
-import javax.xml.crypto.dsig.XMLSignatureException;
-import javax.xml.crypto.dsig.XMLSignatureFactory;
-import javax.xml.crypto.dsig.dom.DOMValidateContext;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import iaik.server.modules.xml.MOAXSecProvider;
-import iaik.xml.crypto.tsl.TSLConstants;
-import iaik.xml.crypto.tsl.TSLContext;
-import iaik.xml.crypto.tsl.TSLEngine;
-import iaik.xml.crypto.tsl.ex.SeverityAspect.Severity;
-import iaik.xml.crypto.tsl.ex.TSLSecurityException;
-import iaik.xml.crypto.tsl.ex.TSLVerificationException;
-import iaik.xml.crypto.tsl.gen.TrustStatusListType;
-import iaik.xml.crypto.tsl.verify.ITSLVerifier;
-import iaik.xml.crypto.utils.URIDereferencerImpl;
-
-public class MOATSLVerifier implements ITSLVerifier {
-
- private static final Logger logger = LoggerFactory.getLogger(MOATSLVerifier.class);
-
- private static iaik.xml.crypto.xmldsig.gen.ObjectFactory dsOf = new iaik.xml.crypto.xmldsig.gen.ObjectFactory();
-
- private static JAXBIntrospector JI = TSLEngine.jc.createJAXBIntrospector();
-
- public Boolean verifyTSL(Document tslDoc, TSLContext tslContext,
- ListIterator<X509Certificate> euTslCertsHash) {
-
- boolean coreValidity = false;
-
- try {
- // Signature s = new Signature();
- // TrustServiceStatusList tssl = new TrustServiceStatusList();
- JAXBElement<iaik.xml.crypto.xmldsig.gen.SignatureType> s = dsOf.createSignature(new iaik.xml.crypto.xmldsig.gen.SignatureType());
-// _l.debug(""+JI.getElementName(s));
- JAXBElement<TrustStatusListType> tssl = TSLConstants.TSL_OF.createTrustServiceStatusList(new TrustStatusListType());
-// _l.debug(""+JI.getElementName(tssl));
-
- Element tsslE = tslDoc.getDocumentElement();
-
- if (tsslE == null) {
- tslContext.throwException(new TSLVerificationException("Empty XML File", Severity.xml_failed));
- // } else if (!tsslE.getNamespaceURI().equals(tssl.getName().getNamespaceURI())) {
- } else if (!tsslE.getNamespaceURI().equals(JI.getElementName(tssl).getNamespaceURI())) {
- tslContext.throwException(new TSLVerificationException("Incorrect Namespace", Severity.xml_failed));
- // } else if (!tsslE.getLocalName().equals(tssl.getName().getLocalPart())) {
- } else if (!tsslE.getLocalName().equals(JI.getElementName(tssl).getLocalPart())) {
- tslContext.throwException(new TSLVerificationException("Wrong Document Element in document "+tslDoc.getDocumentURI(), Severity.xml_failed));
- }
-
- //now we can be sure the right document element is in place, Schema validation does not assure this for us
- //Schema validation however assures that the internal Structure of TrustServicesStatus List is correct
-
- // B.6 1) It MUST be an enveloped signature.
-
- Node n = tsslE.getLastChild();
-
- while ( n != null && ! (n instanceof Element) ) {
- n = n.getPreviousSibling();
- }
-
- Element sig = (Element) n;
-
- if (sig == null ||
- // ! sig.getNamespaceURI().equals(s.getName().getNamespaceURI()) ||
- // ! sig.getLocalName().equals(s.getName().getLocalPart())) {
- ! sig.getNamespaceURI().equals(JI.getElementName(s).getNamespaceURI()) ||
- ! sig.getLocalName().equals(JI.getElementName(s).getLocalPart())) {
-
- tslContext.throwException(
- new TSLVerificationException(
- TSLSecurityException.Type.NO_TSL_SIGNATURE)
- );
-
- } else {
-
- NodeList cn = tsslE.getChildNodes();
-
- for (int j = 0; j < cn.getLength(); j++) {
- cn.item(j);
- }
-
- //TODO assure connection with the PKI Module
- DOMValidateContext valContext = new DOMValidateContext(
- new MOATslKeySelector(euTslCertsHash, tslContext),
- sig);
-
- if (valContext.getURIDereferencer() == null) {
- valContext.setURIDereferencer(new URIDereferencerImpl());
- }
-
- // valContext.setProperty("iaik.xml.crypto.debug.OutputStream", System.out);
- valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
-
- XMLSignatureFactory fac = MOAXSecProvider.getXMLSignatureFactory();
-
- // unmarshal the XMLSignature
- XMLSignature signature = fac.unmarshalXMLSignature(valContext);
-
- // Validate the XMLSignature (generated above)
- coreValidity = signature.validate(valContext);
- // Check core validation status
- if (coreValidity == false) {
- debug(valContext, "Signature failed core validation");
- boolean sv = signature.getSignatureValue().validate(valContext);
- debug(valContext, "signature validation status: " + sv);
- // check the validation status of each Reference
- Iterator it = signature.getSignedInfo().getReferences().iterator();
- for (int j = 0; it.hasNext(); j++) {
- boolean refValid = ((Reference) it.next()).validate(valContext);
- debug(valContext, "ref[" + j + "] validity status: " + refValid);
- }
-
- tslContext.throwException(new TSLVerificationException("Signature failed core validation", Severity.signature_failed));
- }
-
- SignedInfo si = signature.getSignedInfo();
- Iterator it = si.getReferences().iterator();
-
-
- // 2) Its ds:SignedInfo element MUST contain a ds:Reference element with the
- // URI attribute set to a value referencing the TrustServiceStatusList
- // element enveloping the signature itself. This ds:Reference element MUST
- // satisfy the following requirements:
- // a) It MUST contain only one ds:Transforms element.
- // b) This ds:Transforms element MUST contain two ds:Transform elements. The
- // first one will be one whose Algorithm attribute indicates the enveloped
- // transformation with the value:
- // "http://www.w3.org/2000/09/xmldsig#enveloped-signature". The second one
- // will be one whose Algorithm attribute instructs to perform the exclusive
- // canonicalization "http://www.w3.org/2001/10/xml-exc-c14n#"
-
- boolean found_proper_tsslE_reference = false;
-
- for (int j = 0; it.hasNext(); j++) {
- Reference ref = ((Reference) it.next());
- Data d = valContext.getURIDereferencer().dereference(ref, valContext);
-
- if(!(d instanceof NodeSetData)) {
- continue;
- } else {
- NodeSetData nsd = (NodeSetData) d;
-
-
- if (nsd.iterator().next() == tsslE) {
-
- //Assured by XMLSchema
- //throw new TSLException("B.6 2 a) It MUST contain only one ds:Transforms element.");
-
- if(ref.getTransforms().size() != 2) {
- tslContext.throwException(
- new TSLVerificationException(TSLSecurityException.Type.NON_CONFORMANT_TRANSFORMS_IN_TSL_SIGNATURE)
- );
- } else {
-
- Transform[] transforms = (Transform[]) ref.getTransforms().toArray(new Transform[2]);
-
- //TODO assign severity, code some heuristic showing the problems
- if (! transforms[0].getAlgorithm().equals("http://www.w3.org/2000/09/xmldsig#enveloped-signature")) {
- tslContext.throwException(
- new TSLVerificationException(TSLSecurityException.Type.NON_CONFORMANT_TRANSFORM_IN_TSL_SIGNATURE)
- );
-
- }
-
- //TODO assign severity, code some heuristic showing the problems
- if (! transforms[1].getAlgorithm().equals("http://www.w3.org/2001/10/xml-exc-c14n#")) {
- tslContext.throwException(
- new TSLVerificationException(TSLSecurityException.Type.NON_CONFORMANT_C14N_IN_TSL_SIGNATURE)
- );
- }
- }
-
- found_proper_tsslE_reference = true;
- }//if (nsd.iterator().next() == tsslE)
-
- }
- }
-
- if(!found_proper_tsslE_reference) {
- tslContext.throwException(
- new TSLVerificationException(TSLSecurityException.Type.NON_CONFORMANT_REFERENCE_IN_TSL_SIGNATURE)
- );
- }
-
- // 3) ds:CanonicalizationMethod MUST be
- // "http://www.w3.org/2001/10/xml-exc-c14n#".
- if (! si.getCanonicalizationMethod().getAlgorithm().equals("http://www.w3.org/2001/10/xml-exc-c14n#")){
- tslContext.throwException(
- new TSLVerificationException(TSLSecurityException.Type.NON_CONFORMANT_C14N_IN_CANONICALIZATION_METHOD)
- );
- }
-
- // 4) It MAY have other ds:Reference elements.
-
- }
- } catch (URIReferenceException e) {
- tslContext.throwException(new TSLVerificationException(e));
- } catch (MarshalException e) {
- tslContext.throwException(new TSLVerificationException(e));
- } catch (XMLSignatureException e) {
- logger.error("Failed to verify XML Signature for TSL!", e);
- return (Boolean) tslContext.throwException(
- new TSLSecurityException(TSLSecurityException.Type.ERRORS_IN_TSL_SIGNATURE),
- //we need an anonymous class to find the enclosing Method
- (new Object(){}).getClass().getEnclosingMethod(),
- null,
- new Object[] {tslDoc, tslContext, euTslCertsHash}
- );
- }
- return coreValidity;
- }
-
- public static void debug(DOMCryptoContext context, String message) {
-
- Object propDebug = context.getProperty("iaik.xml.crypto.debug.OutputStream");
-
- if ( propDebug == null) {
- return;
- }
-
- if (! (propDebug instanceof OutputStream)) {
- System.err.println("Failed to write to debug output stream. " +
- "DOMCryptoContext's Property (\"iaik.xml.crypto.debug.OutputStream\") " +
- "has to be of type OutputStream."
- );
- } else {
-
- OutputStream os = (OutputStream) propDebug;
- try {
- (new OutputStreamWriter(os)).write(message);
- } catch (IOException e) {
- System.err.println("Failed to write to debug output stream. " + e.getMessage());
- //TODO we cannot close the output stream here ...
- }
- }
-
- }
-
-}
diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/MOATslKeySelector.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/MOATslKeySelector.java deleted file mode 100644 index efdd877..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/MOATslKeySelector.java +++ /dev/null @@ -1,123 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.connector;
-
-import java.security.cert.X509Certificate;
-import java.util.List;
-import java.util.ListIterator;
-
-import javax.xml.crypto.AlgorithmMethod;
-import javax.xml.crypto.KeySelectorException;
-import javax.xml.crypto.KeySelectorResult;
-import javax.xml.crypto.XMLCryptoContext;
-import javax.xml.crypto.dsig.keyinfo.KeyInfo;
-import javax.xml.crypto.dsig.keyinfo.X509Data;
-
-import iaik.server.modules.xmlverify.MOAKeySelector;
-import iaik.xml.crypto.tsl.TSLContext;
-import iaik.xml.crypto.tsl.ex.TSLSecurityException;
-import iaik.xml.crypto.tsl.ex.TSLVerificationException;
-import iaik.xml.crypto.tsl.verify.TslKeyInfoHints;
-import iaik.xml.crypto.utils.X509KeySelectorResult;
-
-public class MOATslKeySelector extends MOAKeySelector {
-
- private final ListIterator<X509Certificate> tslSignerCerts_;
- private TSLContext tslContextI_;
-
- public MOATslKeySelector(ListIterator<X509Certificate> euTslCertsHash, TSLContext tslContext) {
- if(euTslCertsHash == null){
- tslContext.throwException(
- new TSLVerificationException(
- TSLSecurityException.Type.MISSING_INFO_ON_TSL_SIGNER)
- );
- }
- tslSignerCerts_ = euTslCertsHash;
- tslContextI_ = tslContext;
- tslContext.toString();
- }
-
- @Override
- protected KeyInfoHints newKeyInfoHints(KeyInfo keyInfo,
- XMLCryptoContext context)
- throws KeySelectorException {
-
- return new TslKeyInfoHints(keyInfo, context, tslContextI_, tslSignerCerts_);
-
- }
-
- @Override
- protected KeySelectorResult select(KeyInfoHints hints,
- KeySelectorResult[] results) {
-
- if (results.length > 1){
-
- return (KeySelectorResult) tslContextI_.throwException(
- new TSLSecurityException(TSLSecurityException.Type.UNTRUSTED_TSL_SIGNER),
- //we need an anonymous class to find the enclosing Method
- (new Object(){}).getClass().getEnclosingMethod(),
- this,
- new Object[] {hints, results}
- );
-
- } else {
- KeySelectorResult result = results[0];
- if (result instanceof X509KeySelectorResult) {
- result = new MOAX509KeySelectorResult((X509KeySelectorResult)result);
- } else {
- result = new MOAKeySelectorResult(result.getKey());
- }
- return result;
- }
- }
-
- @Override
- public KeySelectorResult select(X509Data x509Data,
- Purpose purpose,
- AlgorithmMethod method,
- XMLCryptoContext context) throws KeySelectorException {
-
- X509KeySelectorResult ksr;
- try {
- ksr = (X509KeySelectorResult) super.select(x509Data, purpose, method, context);
- } catch (ClassCastException e) {
- ksr = (X509KeySelectorResult) tslContextI_.throwException(
- e,
- //we need an anonymous class to find the enclosing Method
- (new Object(){}).getClass().getEnclosingMethod(),
- this,
- new Object[]{x509Data, purpose, method, context});
- }
-
- if (ksr == null){
- //there has been a Problem with the X509Data
- ksr = (X509KeySelectorResult) tslContextI_.throwException(
- new KeySelectorException(failReason_.replace(". ", ".\n")),
- //we need an anonymous class to find the enclosing Method
- (new Object(){}).getClass().getEnclosingMethod(),
- this,
- new Object[]{x509Data, purpose, method, context});
- }
-
- List l = ksr.getCertificates();
- tslContextI_.securityCheck(
- TSLSecurityException.Type.UNTRUSTED_TSL_SIGNER,
- (X509Certificate[]) l.toArray(new X509Certificate[l.size()]),
- tslSignerCerts_
- );
-
- return ksr;
- }
-
- @Override
- protected KeySelectorResult select(X509Certificate cert, Purpose purpose,
- AlgorithmMethod method, XMLCryptoContext context)
- throws KeySelectorException {
-
- tslContextI_.securityCheck(
- TSLSecurityException.Type.UNTRUSTED_TSL_SIGNER,
- cert,
- tslSignerCerts_
- );
-
- return super.select(cert, purpose, method, context);
- }
-}
\ No newline at end of file diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/TSLConnector.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/TSLConnector.java deleted file mode 100644 index 5620a20..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/TSLConnector.java +++ /dev/null @@ -1,972 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.connector;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.nio.channels.ByteChannel;
-import java.nio.channels.FileChannel;
-import java.security.Security;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import org.apache.log4j.Logger;
-
-import at.gv.egovernment.moa.spss.tsl.config.Configurator;
-import at.gv.egovernment.moa.spss.tsl.utils.TSLEUImportFromFileContext;
-import at.gv.egovernment.moa.spss.tsl.utils.TSLEvaluationContext;
-import at.gv.egovernment.moa.spss.tsl.utils.TSLImportFromFileContext;
-import iaik.asn1.ObjectID;
-import iaik.util.GeneralUtils15;
-import iaik.util.logging.GeneralLog;
-import iaik.utils.RFC2253NameParser;
-import iaik.xml.crypto.EccProviderAdapter;
-import iaik.xml.crypto.XSecProvider;
-import iaik.xml.crypto.tsl.DbTables;
-import iaik.xml.crypto.tsl.DbTables.MODE;
-import iaik.xml.crypto.tsl.DbTables.Service;
-import iaik.xml.crypto.tsl.TSLCertEvaluator;
-import iaik.xml.crypto.tsl.TSLCertsExporter;
-import iaik.xml.crypto.tsl.TSLEngine;
-import iaik.xml.crypto.tsl.TSLEngine.LocationAndCertHash;
-import iaik.xml.crypto.tsl.TSLEngine.TSLEngineEU;
-import iaik.xml.crypto.tsl.TSLImportContext;
-import iaik.xml.crypto.tsl.TSLResult;
-import iaik.xml.crypto.tsl.TSLResultEndEntity;
-import iaik.xml.crypto.tsl.TSLResultImpl;
-import iaik.xml.crypto.tsl.TslSqlConnectionWrapper;
-import iaik.xml.crypto.tsl.constants.Countries;
-import iaik.xml.crypto.tsl.ex.TSLEngineDiedException;
-import iaik.xml.crypto.tsl.ex.TSLEngineFatalException;
-import iaik.xml.crypto.tsl.ex.TSLEngineFatalRuntimeException;
-import iaik.xml.crypto.tsl.ex.TSLExceptionB;
-import iaik.xml.crypto.tsl.ex.TSLRuntimeException;
-import iaik.xml.crypto.tsl.ex.TSLSearchException;
-import iaik.xml.crypto.tsl.ex.TSLTransactionFailedRuntimeException;
-import iaik.xml.crypto.tsl.fetch.TLS;
-import iaik.xml.crypto.tsl.sie.gen.QualifierType;
-
-public class TSLConnector implements TSLConnectorInterface {
-
- static final String _QCSSCDURI = "http://uri.etsi.org/TrstSvc/eSigDir-1999-93-EC-TrustedList/SvcInfoExt/QCWithSSCD";
- static final String _STYPETEMPLATE_CAQC = "CA/QC";
- static final String _STYPETEMPLATE_TSAQTST = "TSA/QTST";
-
- private static final String DEFAULT_HASHCACHE_DIR = "./hashcache/";
-
- static final List<String> STYPETEMPLATES = Collections.unmodifiableList(new ArrayList<String>(){
- private static final long serialVersionUID = 1L;
- {
- add(_STYPETEMPLATE_CAQC);
- add(_STYPETEMPLATE_TSAQTST);
- }
- });
-
-
- static Logger log = Logger.getLogger(TSLConnector.class);
-
- public void initialize(String euTSLURL, String TSLWorkingDirectoryPath, String jdbcURL, String jdbcDriverClass)
- throws TSLEngineDiedException {
-
- Configurator.initial(euTSLURL, TSLWorkingDirectoryPath, jdbcURL, jdbcDriverClass);
-
- }
-
- public ArrayList<File> updateAndGetQualifiedCACertificates(Date dateTime,
- String[] serviceLevelStatus) throws TSLEngineDiedException, TSLSearchException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- return updateAndGetQualifiedCACertificates(dateTime, null, serviceLevelStatus);
- }
-
- public void updateTSLs(Date dateTime,
- String[] serviceLevelStatus) throws TSLEngineDiedException, TSLSearchException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- updateTSLs(dateTime, null, serviceLevelStatus);
- }
-
- public ArrayList<File> updateAndGetQualifiedCACertificates(Date dateTime,
- String[] countries, String[] serviceLevelStatus) throws TSLEngineDiedException, TSLSearchException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- String tsldownloaddir = Configurator.get_TSLWorkingDirectoryPath() + "TslDownload";
-
-// String hashcachedir = System.getProperty("iaik.xml.crypto.tsl.BinaryHashCache.DIR");
-// System.out.println("hashcachedir: " + hashcachedir);
-// if (hashcachedir==null)
-// hashcachedir = DEFAULT_HASHCACHE_DIR;
-
-// File hashcachefile = new File(hashcachedir);
-// File[] filelist = hashcachefile.listFiles();
-// if (filelist != null) {
-// for (File f : filelist)
-// f.delete();
-// }
-
- File tsldownloadfile = new File(tsldownloaddir);
- if (!tsldownloadfile.exists()) {
- tsldownloadfile.mkdir();
- }
- File[] tslfilelist = tsldownloadfile.listFiles();
- if (tslfilelist != null) {
- for (File f : tslfilelist)
- f.delete();
- }
-
- //create sqlLite database
- File dbFile = new File(Configurator.get_TempdbFile());
- try {
- dbFile.delete();
- dbFile.createNewFile();
- } catch (IOException e) {
- throw new TSLEngineDiedException("Could not create temporary data base file", e);
- }
-
- //the TSL library uses the iaik.util.logging environment.
- //iaik.util.logging.Log.setLogLevel(iaik.util.logging.LogLevels.WARN);
- iaik.util.logging.Log.setLogLevel(iaik.util.logging.LogLevels.OFF);
-
- log.info("Starting EU TSL import.");
-
- // Certificates in Germany, Estonia, Greece, Cyprus,
- // Lithuainia, Hungary, Poland, Finland, Norway use SURNAME
- log.debug("### SURNAME registered as " + ObjectID.surName + " ###");
- RFC2253NameParser.register("SURNAME", ObjectID.surName);
-
- XSecProvider.addAsProvider(false);
-
- TSLEngine tslEngine;
- TslSqlConnectionWrapper connection = null;
-
- try {
- // register the Https JSSE Wrapper
- TLS.register();
- log.trace("### Https JSSE Wrapper registered ###");
-
-
- log.debug("### Connect to Database.###");
- connection = DbTables.connectToDatabaBase(dbFile, MODE.AUTO_COMMIT_ON);
-
- log.trace("### Connected ###");
-
- // empty the database and recreate the tables
- tslEngine = new TSLEngine(dbFile, Configurator.get_TSLWorkingDirectoryPath(),
- connection, true, true);
-
- } catch (TSLEngineFatalException e1) {
- throw new TSLEngineDiedException(e1);
-
- }
-
- // H.2.2.1 Same-scheme searching
- // H.2.2.2 Known scheme searching
- // H.2.2.3 "Blind" (unknown) scheme searching
- Number tId = null;
- Countries euTerritory = Countries.EU;
- TSLImportContext topLevelTslContext = new TSLEUImportFromFileContext(
- euTerritory, Configurator.get_euTSLURL(), Configurator.get_TSLWorkingDirectoryPath(),
- Configurator.is_sqlMultithreaded(),
- Configurator.is_throwExceptions(), Configurator.is_logExceptions(),
- Configurator.is_throwWarnings(), Configurator.is_logWarnings(),
- Configurator.is_nullRedundancies());
-
- TSLEngineEU tslengineEU;
- try {
- tslengineEU = tslEngine.new TSLEngineEU();
-
- } catch (TSLEngineFatalException e1) {
- throw new TSLEngineDiedException(e1);
- }
-
- // establish EU TSL trust anchor
- ListIterator<java.security.cert.X509Certificate> expectedEuTslSignerCerts =
- tslEngine.loadCertificatesFromResource(
- Configurator.get_euTrustAnchorsPath(), topLevelTslContext);
-
- log.debug("Process EU TSL");
- // process the EU TSL to receive the pointers to the other TSLs
- // and the trust anchors for the TSL signers
- Set<Entry<Number, LocationAndCertHash>> pointersToMsTSLs = null;
-
- try {
-
- tId = tslengineEU.processEUTSL(topLevelTslContext, expectedEuTslSignerCerts);
- log.info("Process EU TSL finished");
-
- log.debug(Thread.currentThread() + " waiting for other threads ...");
-
- topLevelTslContext.waitForAllOtherThreads();
- log.debug(Thread.currentThread()
- + " reactivated after other threads finished ...");
-
-
- // get the TSLs pointed from the EU TSL
- LinkedHashMap<Number, LocationAndCertHash> tslMap = tslengineEU
- .getOtherTslMap(tId, topLevelTslContext);
-
- pointersToMsTSLs = tslMap.entrySet();
-
- //set Errors and Warrnings
-
- } catch (TSLEngineFatalRuntimeException e) {
- throw new TSLEngineDiedException(topLevelTslContext.dumpFatals());
-
- } catch (TSLTransactionFailedRuntimeException e) {
- throw new TSLEngineDiedException(topLevelTslContext.dumpTransactionFaliures());
- }
-
- //Backup implementation if the EU TSL includes a false signer certificate
- // establish additional trust anchors for member states
-// Countries[] countriesWithPotentiallyWrongCertsOnEuTsl = {
-// Countries.CZ,
-// Countries.LU,
-// Countries.ES,
-// Countries.AT,
-// };
- Countries[] countriesWithPotentiallyWrongCertsOnEuTsl = {};
-
- Map<Countries, java.util.ListIterator<java.security.cert.X509Certificate>>
- trustAnchorsWrongOnEuTsl = loadCertificatesFromResource(
- Configurator.get_msTrustAnchorsPath(), tslEngine, topLevelTslContext,
- countriesWithPotentiallyWrongCertsOnEuTsl);
-
- log.info("Starting EU member TSL import.");
-
- for (Entry<Number, LocationAndCertHash> entry : pointersToMsTSLs) {
-
- TSLImportContext msTslContext;
-
- Countries expectedTerritory = entry.getValue().getSchemeTerritory();
- try {
-
-// if (expectedTerritory.equals("RO"))
-// System.out.println("Stop");
-
- Number otpId = entry.getKey();
- LocationAndCertHash lac = entry.getValue();
-
- URL uriReference = null;
- try {
- uriReference = new URL(lac.getUrl());
-
- } catch (MalformedURLException e) {
- log.warn("Could not process: " + uriReference, e);
- continue;
- }
-
- String baseURI = uriReference == null ? "" : "" + uriReference;
-
- msTslContext = new TSLImportFromFileContext(
- expectedTerritory, uriReference, otpId, Configurator.get_TSLWorkingDirectoryPath(),
- Configurator.is_sqlMultithreaded(),
- Configurator.is_throwExceptions(), Configurator.is_logExceptions(),
- Configurator.is_throwWarnings(), Configurator.is_logWarnings(),
- Configurator.is_nullRedundancies(), baseURI, trustAnchorsWrongOnEuTsl,
- topLevelTslContext);
-
- ListIterator<X509Certificate> expectedTslSignerCerts = null;
- expectedTslSignerCerts = tslEngine.getCertificates(lac, msTslContext);
-
- if (expectedTslSignerCerts == null) {
-
- // no signer certificate on the EU TSL
- // ignore this msTSL and log a warning
- log.warn("NO signer certificate found on EU TSL! "
- + lac.getSchemeTerritory() + "TSL ignored.");
-
- }
- else {
- tslEngine.processMSTSL(topLevelTslContext, msTslContext, expectedTslSignerCerts);
- }
-
- } catch (TSLExceptionB e) {
- log.warn("Failed to process TSL. " + entry.getValue().getSchemeTerritory()
- + " TSL ignored.");
- log.debug("Failed to process TSL. " + entry, e);
- continue;
- } catch (TSLRuntimeException e) {
- log.warn("Failed to process TSL. " + entry.getValue().getSchemeTerritory()
- + " TSL ignored.");
- log.debug("Failed to process TSL. " + entry, e);
- continue;
- }
- }
-
- log.debug(Thread.currentThread() + " waiting for other threads ...");
- topLevelTslContext.waitForAllOtherThreads();
-
- log.debug(GeneralUtils15.dumpAllThreads());
- log.debug(Thread.currentThread() + " reactivated after other threads finished ...");
-
- connection = null;
- try {
- connection = DbTables.connectToDatabaBase(dbFile, MODE.AUTO_COMMIT_ON);
- tslEngine.recreateTablesInvalidatedByImport(connection);
-
-
- //TODO: implement database copy operation!
- File working_database = new File(Configurator.get_dbFile());
- working_database.delete();
- copy(dbFile, working_database);
-
-
- } catch (TSLEngineFatalException e) {
- throw new TSLEngineDiedException(e);
-
- } finally {
- try {
- connection.closeConnection();
-
- } catch (TSLEngineFatalException e) {
- throw new TSLEngineDiedException(e);
-
- }
- }
-
- return getQualifiedCACertificates(dateTime, countries, serviceLevelStatus);
- }
-
- public void updateTSLs(Date dateTime,
- String[] countries, String[] serviceLevelStatus) throws TSLEngineDiedException, TSLSearchException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- String tsldownloaddir = Configurator.get_TSLWorkingDirectoryPath() + "TslDownload";
-
-// String hashcachedir = System.getProperty("iaik.xml.crypto.tsl.BinaryHashCache.DIR");
-// System.out.println("hashcachedir: " + hashcachedir);
-// if (hashcachedir==null)
-// hashcachedir = DEFAULT_HASHCACHE_DIR;
-
-// File hashcachefile = new File(hashcachedir);
-// File[] filelist = hashcachefile.listFiles();
-// if (filelist != null) {
-// for (File f : filelist)
-// f.delete();
-// }
-
- File tsldownloadfile = new File(tsldownloaddir);
- if (!tsldownloadfile.exists()) {
- tsldownloadfile.mkdir();
- }
- File[] tslfilelist = tsldownloadfile.listFiles();
- if (tslfilelist != null) {
- for (File f : tslfilelist)
- f.delete();
- }
-
- //create sqlLite database
- File dbFile = new File(Configurator.get_TempdbFile());
- try {
- dbFile.delete();
- dbFile.createNewFile();
- } catch (IOException e) {
- throw new TSLEngineDiedException("Could not create temporary data base file", e);
- }
-
- //the TSL library uses the iaik.util.logging environment.
- //iaik.util.logging.Log.setLogLevel(iaik.util.logging.LogLevels.WARN);
- iaik.util.logging.Log.setLogLevel(iaik.util.logging.LogLevels.OFF);
-
- log.info("Starting EU TSL import.");
-
- // Certificates in Germany, Estonia, Greece, Cyprus,
- // Lithuainia, Hungary, Poland, Finland, Norway use SURNAME
- log.debug("### SURNAME registered as " + ObjectID.surName + " ###");
- RFC2253NameParser.register("SURNAME", ObjectID.surName);
-
- //XSecProvider.addAsProvider(false);
-
- TSLEngine tslEngine;
- TslSqlConnectionWrapper connection = null;
-
- try {
- // register the Https JSSE Wrapper
- TLS.register();
- log.trace("### Https JSSE Wrapper registered ###");
-
-
- log.debug("### Connect to Database.###");
- connection = DbTables.connectToDatabaBase(dbFile, MODE.AUTO_COMMIT_ON);
-
- log.trace("### Connected ###");
-
- // empty the database and recreate the tables
- tslEngine = new TSLEngine(dbFile, Configurator.get_TSLWorkingDirectoryPath(),
- connection, true, true);
-
- } catch (TSLEngineFatalException e1) {
- throw new TSLEngineDiedException(e1);
-
- }
-
- // H.2.2.1 Same-scheme searching
- // H.2.2.2 Known scheme searching
- // H.2.2.3 "Blind" (unknown) scheme searching
- Number tId = null;
- Countries euTerritory = Countries.EU;
- TSLImportContext topLevelTslContext = new TSLEUImportFromFileContext(
- euTerritory, Configurator.get_euTSLURL(), Configurator.get_TSLWorkingDirectoryPath(),
- Configurator.is_sqlMultithreaded(),
- Configurator.is_throwExceptions(), Configurator.is_logExceptions(),
- Configurator.is_throwWarnings(), Configurator.is_logWarnings(),
- Configurator.is_nullRedundancies());
-
- TSLEngineEU tslengineEU;
- try {
- tslengineEU = tslEngine.new TSLEngineEU();
-
- } catch (TSLEngineFatalException e1) {
- throw new TSLEngineDiedException(e1);
- }
-
- // establish EU TSL trust anchor
- ListIterator<java.security.cert.X509Certificate> expectedEuTslSignerCerts =
- tslEngine.loadCertificatesFromResource(
- Configurator.get_euTrustAnchorsPath(), topLevelTslContext);
-
- log.debug("Process EU TSL");
- // process the EU TSL to receive the pointers to the other TSLs
- // and the trust anchors for the TSL signers
- Set<Entry<Number, LocationAndCertHash>> pointersToMsTSLs = null;
-
- try {
-
- tId = tslengineEU.processEUTSL(topLevelTslContext, expectedEuTslSignerCerts);
- log.info("Process EU TSL finished");
-
- log.debug(Thread.currentThread() + " waiting for other threads ...");
-
- topLevelTslContext.waitForAllOtherThreads();
- log.debug(Thread.currentThread()
- + " reactivated after other threads finished ...");
-
-
- // get the TSLs pointed from the EU TSL
- LinkedHashMap<Number, LocationAndCertHash> tslMap = tslengineEU
- .getOtherTslMap(tId, topLevelTslContext);
-
- pointersToMsTSLs = tslMap.entrySet();
-
- //set Errors and Warrnings
-
- } catch (TSLEngineFatalRuntimeException e) {
- throw new TSLEngineDiedException(topLevelTslContext.dumpFatals());
-
- } catch (TSLTransactionFailedRuntimeException e) {
- throw new TSLEngineDiedException(topLevelTslContext.dumpTransactionFaliures());
- }
-
- //Backup implementation if the EU TSL includes a false signer certificate
- // establish additional trust anchors for member states
-// Countries[] countriesWithPotentiallyWrongCertsOnEuTsl = {
-// Countries.CZ,
-// Countries.LU,
-// Countries.ES,
-// Countries.AT,
-// };
- Countries[] countriesWithPotentiallyWrongCertsOnEuTsl = {};
-
- Map<Countries, java.util.ListIterator<java.security.cert.X509Certificate>>
- trustAnchorsWrongOnEuTsl = loadCertificatesFromResource(
- Configurator.get_msTrustAnchorsPath(), tslEngine, topLevelTslContext,
- countriesWithPotentiallyWrongCertsOnEuTsl);
-
- log.info("Starting EU member TSL import.");
-
- for (Entry<Number, LocationAndCertHash> entry : pointersToMsTSLs) {
-
- TSLImportContext msTslContext;
-
- Countries expectedTerritory = entry.getValue().getSchemeTerritory();
- try {
-
-// if (expectedTerritory.equals("RO"))
-// System.out.println("Stop");
-
- Number otpId = entry.getKey();
- LocationAndCertHash lac = entry.getValue();
-
- URL uriReference = null;
- try {
- uriReference = new URL(lac.getUrl());
-
- } catch (MalformedURLException e) {
- log.warn("Could not process: " + uriReference, e);
- continue;
- }
-
- String baseURI = uriReference == null ? "" : "" + uriReference;
-
- msTslContext = new TSLImportFromFileContext(
- expectedTerritory, uriReference, otpId, Configurator.get_TSLWorkingDirectoryPath(),
- Configurator.is_sqlMultithreaded(),
- Configurator.is_throwExceptions(), Configurator.is_logExceptions(),
- Configurator.is_throwWarnings(), Configurator.is_logWarnings(),
- Configurator.is_nullRedundancies(), baseURI, trustAnchorsWrongOnEuTsl,
- topLevelTslContext);
-
- ListIterator<X509Certificate> expectedTslSignerCerts = null;
- expectedTslSignerCerts = tslEngine.getCertificates(lac, msTslContext);
-
- if (expectedTslSignerCerts == null) {
-
- // no signer certificate on the EU TSL
- // ignore this msTSL and log a warning
- log.warn("NO signer certificate found on EU TSL! "
- + lac.getSchemeTerritory() + "TSL ignored.");
-
- }
- else {
- tslEngine.processMSTSL(topLevelTslContext, msTslContext, expectedTslSignerCerts);
- }
-
- } catch (TSLExceptionB e) {
- log.warn("Failed to process TSL. " + entry.getValue().getSchemeTerritory()
- + " TSL ignored.");
- log.debug("Failed to process TSL. " + entry, e);
- continue;
- } catch (TSLRuntimeException e) {
- log.warn("Failed to process TSL. " + entry.getValue().getSchemeTerritory()
- + " TSL ignored.");
- log.debug("Failed to process TSL. " + entry, e);
- continue;
- }
- }
-
- log.debug(Thread.currentThread() + " waiting for other threads ...");
- topLevelTslContext.waitForAllOtherThreads();
-
- log.debug(GeneralUtils15.dumpAllThreads());
- log.debug(Thread.currentThread() + " reactivated after other threads finished ...");
-
- connection = null;
- try {
- connection = DbTables.connectToDatabaBase(dbFile, MODE.AUTO_COMMIT_ON);
- tslEngine.recreateTablesInvalidatedByImport(connection);
-
-
- //TODO: implement database copy operation!
- File working_database = new File(Configurator.get_dbFile());
- working_database.delete();
- copy(dbFile, working_database);
-
-
- } catch (TSLEngineFatalException e) {
- throw new TSLEngineDiedException(e);
-
- } finally {
- try {
- connection.closeConnection();
-
- } catch (TSLEngineFatalException e) {
- throw new TSLEngineDiedException(e);
-
- }
- }
-
- //return getQualifiedCACertificates(dateTime, countries, serviceLevelStatus);
- }
-
- public ArrayList<File> getQualifiedCACertificates(Date dateTime,
- String[] serviceLevelStatus) throws TSLEngineDiedException,
- TSLSearchException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- return getQualifiedCACertificates(dateTime, null, serviceLevelStatus);
- }
-
- public ArrayList<File> getQualifiedCACertificates(Date dateTime,
- String[] countries, String[] serviceLevelStatus)
- throws TSLEngineDiedException, TSLSearchException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- //TODO: database
- File dbFile = new File(Configurator.get_TempdbFile());
- //File dbFile = new File(Configurator.get_dbFile());
- if(!dbFile.exists())
- throw new TSLEngineDiedException("Could not open data base file");
-
- log.debug("### Connect to Database ###");
- TslSqlConnectionWrapper readConnection = null;
-
- try {
- readConnection = DbTables.connectToDatabaBase(dbFile, MODE.READ_ONLY);
-
- TSLEngine tslEngine = new TSLEngine(dbFile, Configurator.get_TSLWorkingDirectoryPath(),
- readConnection, false, false);
-
- log.debug("### Connected ###");
- //TODO: maybe add "TSA/QTST for qualified timestamps
- try {
- TSLCertsExporter certsExporter;
- certsExporter = tslEngine.createCertsExporter(
- readConnection,
- countries,
- null,//new String[]{_STYPETEMPLATE_CAQC},
- serviceLevelStatus
- );
-
- return certsExporter.exportAsArray(dateTime, null);
-
- } catch (TSLEngineFatalException e) {
- e.printStackTrace();
- GeneralLog.err("could not export Certs", e);
- throw new TSLEngineDiedException(e);
- }
-
- } catch (TSLEngineFatalException e1) {
- throw new TSLEngineDiedException(e1);
-
- } finally {
- try {
- readConnection.closeConnection();
-
- } catch (TSLEngineFatalException e) {
- throw new TSLEngineDiedException(e);
- }
- }
- }
-
- public boolean checkQC(java.security.cert.X509Certificate[] chain)
- throws TSLSearchException, TSLEngineDiedException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- return checkQC(chain, 1);
- }
-
- public boolean checkSSCD(java.security.cert.X509Certificate[] chain)
- throws TSLSearchException, TSLEngineDiedException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- return checkSSCD(chain, 1);
- }
-
- public boolean checkQC(java.security.cert.X509Certificate[] chain, int cnt)
- throws TSLSearchException, TSLEngineDiedException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- LinkedHashMap<X509Certificate, TSLResult> tslResultC = checkchain(chain, cnt);
-
- //get first result
- java.util.Map.Entry<java.security.cert.X509Certificate, TSLResult> resultmap = tslResultC.entrySet().iterator().next();
- TSLResult tslresult = tslResultC.entrySet().iterator().next().getValue();
-
-
-
- if (tslresult == null) {
- log.info("Certificate: " + resultmap.getKey().getSubjectDN()
- + " not on the TSL");
- throw new TSLSearchException("Certificate: " + resultmap.getKey().getSubjectDN()
- + " not on the TSL");
- }
-
- if (tslresult instanceof TSLResultEndEntity) {
- TSLResultEndEntity ree = (TSLResultEndEntity) tslresult;
-
-
- String sType = (String) ree.get(Service.C.sType);
-
- log.info("Cert: " + resultmap.getKey().getSubjectDN() + " sType=" + sType);
-
- //TODO: maybe add "TSA/QTST for qualified timestamps
- if (sType.equals(_STYPETEMPLATE_CAQC))
- return true;
- else
- return false;
- }
-
- else if (tslresult instanceof TSLResultImpl) {
-
- //TODO: Certificate is not of Type EndEntity (equal to QCSSCD check)
- // Is FALSE the correct answer?
- return false;
- }
-
- throw new TSLEngineDiedException("TSL Result has an unknown Class type");
- }
-
- public boolean checkSSCD(java.security.cert.X509Certificate[] chain, int cnt)
- throws TSLSearchException, TSLEngineDiedException {
-
- if (Configurator.is_isInitialised() == false)
- new TSLEngineFatalException("The TSL Engine is not initialized!");
-
- LinkedHashMap<X509Certificate, TSLResult> tslResultC = checkchain(chain, cnt);
-
- //get first result
- java.util.Map.Entry<java.security.cert.X509Certificate, TSLResult> resultmap = tslResultC.entrySet().iterator().next();
- TSLResult tslresult = tslResultC.entrySet().iterator().next().getValue();
-
- if (tslresult == null) {
- log.info("Certificate: " + resultmap.getKey().getSubjectDN() + " not on the TSL");
- throw new TSLSearchException("Certificate: " + resultmap.getKey().getSubjectDN()
- + " not on the TSL");
- }
-
- if (tslresult instanceof TSLResultEndEntity) {
- TSLResultEndEntity ree = (TSLResultEndEntity) tslresult;
-
- List<QualifierType> qualifier = ree.getQualifierList();
-
- Iterator<QualifierType> qualifierlist = qualifier.iterator();
-
- String uri = "";
-
- while (qualifierlist.hasNext()) {
- uri = qualifierlist.next().getUri();
-
- log.debug("Cert: " + resultmap.getKey().getSubjectDN() + " SSCD=" + uri);
-
- if (uri.contains(_QCSSCDURI)) {
- return true;
- }
- else {
- return false;
- }
- }
- return false;
- }
-
- else if (tslresult instanceof TSLResultImpl) {
-
- //TODO: Certificate is not of Type EndEntity (equal to QC check)
- // Is FALSE the correct answer?
- return false;
- }
-
- throw new TSLEngineDiedException("TSL Result has an unknown Class type");
- }
-
-
-
- private LinkedHashMap<java.security.cert.X509Certificate, TSLResult> checkchain(java.security.cert.X509Certificate[] chain, int cnt)
- throws TSLSearchException, TSLEngineDiedException {
-
- File dbFile = new File(Configurator.get_dbFile());
- if(!dbFile.exists())
- throw new TSLEngineDiedException("Could not open data base file");
-
- try {
-
- log.debug("### Connect to Database ###");
- TslSqlConnectionWrapper readConnection;
- readConnection = DbTables.connectToDatabaBase(dbFile, MODE.READ_ONLY);
- log.debug("### Connected ###");
-
- TSLEngine tslEngine = new TSLEngine(dbFile, Configurator.get_TSLWorkingDirectoryPath(),
- readConnection, false, false);
-
- XSecProvider.addAsProvider(false);
- log.debug("### XSECT registered ###");
- // register the additional IAIK ECC provider
- Security.addProvider(EccProviderAdapter.getEccProvider());
- log.debug("### ECC registered ###");
-
-
- TSLEvaluationContext context = new TSLEvaluationContext(
- Configurator.get_TSLWorkingDirectoryPath(),
- Configurator.is_sqlMultithreaded(),
- Configurator.is_throwExceptions(),
- Configurator.is_logExceptions(),
- Configurator.is_throwWarnings(),
- Configurator.is_logWarnings());
-
- TSLCertEvaluator tslCertEvaluator = tslEngine.createEvaluator(context,
- readConnection);
-
- Date signingTime = new Date();
-
- // has to be later or equal
- Date now = new Date();
-
- LinkedHashMap<java.security.cert.X509Certificate, TSLResult> tslResultC = tslCertEvaluator
- .evaluate(TSLCertEvaluator.CHAIN_MODEL, chain, signingTime, now, context);
-
- return tslResultC;
-
- } catch (TSLEngineFatalException e1) {
- throw new TSLEngineDiedException(e1);
- }
-
-
- }
-
- private static Map<Countries, java.util.ListIterator<java.security.cert.X509Certificate>> loadCertificatesFromResource(
- final String msTrustAnchorsPath, TSLEngine tslEngine,
- TSLImportContext topLevelTslContext, Countries[] countriesWithNoCertsOnEuTsl)
- throws TSLEngineDiedException {
- Map<Countries, java.util.ListIterator<java.security.cert.X509Certificate>> trustAnchorsMissingOnEuTsl;
- trustAnchorsMissingOnEuTsl =
- new HashMap<Countries, java.util.ListIterator<java.security.cert.X509Certificate>>(
- countriesWithNoCertsOnEuTsl.length);
-
- for (int i = 0; i < countriesWithNoCertsOnEuTsl.length; i++) {
- Countries country = countriesWithNoCertsOnEuTsl[i];
-
- final String mspath = msTrustAnchorsPath + country + "/";
-
- ListIterator<java.security.cert.X509Certificate> msCerts =
- tslEngine.loadCertificatesFromResource(mspath, topLevelTslContext);
-
- trustAnchorsMissingOnEuTsl.put(country, msCerts);
- }
- return trustAnchorsMissingOnEuTsl;
- }
-
-
- private void copy(File source, File destination) throws TSLEngineDiedException {
- try {
- FileInputStream fileInputStream = new FileInputStream(source);
- FileOutputStream fileOutputStream = new FileOutputStream(destination);
- FileChannel inputChannel = fileInputStream.getChannel();
- FileChannel outputChannel = fileOutputStream.getChannel();
-
- transfer(inputChannel, outputChannel, source.length(), false);
-
- fileInputStream.close();
- fileOutputStream.close();
-
- destination.setLastModified(source.lastModified());
- } catch (Exception e) {
-
- throw new TSLEngineDiedException("Error during TSL database copy operation!.");
- }
- }
-
- private void transfer(FileChannel fileChannel, ByteChannel byteChannel, long lengthInBytes, boolean verbose)
- throws IOException {
-
- long overallBytesTransfered = 0L;
- long time = -System.currentTimeMillis();
-
- while (overallBytesTransfered < lengthInBytes) {
- long bytesTransfered = 0L;
- bytesTransfered = fileChannel.transferTo(overallBytesTransfered, Math.min(1024 * 1024, lengthInBytes - overallBytesTransfered), byteChannel);
- overallBytesTransfered += bytesTransfered;
- if (verbose) {
- System.out.println("overall bytes transfered: " + overallBytesTransfered + " progress " + (Math.round(overallBytesTransfered / ((double) lengthInBytes) * 100.0)) + "%");
- }
- }
- time += System.currentTimeMillis();
-
- if (verbose) {
- System.out.println("Transfered: " + overallBytesTransfered + " bytes in: " + (time / 1000) + " s -> " + (overallBytesTransfered / 1024.0) / (time / 1000.0) + " kbytes/s");
- }
- }
-
-
-// /**
-// * @param tslResultC
-// * @param context
-// */
-// private static void printResultDetails(
-// LinkedHashMap<java.security.cert.X509Certificate, TSLResult> tslResultC, TSLContext context) {
-//
-// for (java.util.Map.Entry<java.security.cert.X509Certificate, TSLResult> e : tslResultC
-// .entrySet()) {
-//
-// TSLResult r = e.getValue();
-//
-// if (r == null) {
-// log.info("Certificate: " + e.getKey().getSubjectDN()
-// + " not on the TSL");
-// continue;
-// }
-//
-// if (r instanceof TSLResultEndEntity) {
-// TSLResultEndEntity ree = (TSLResultEndEntity) r;
-//
-// String status = (String) ree.get(Service.C.status);
-//
-// Date startDate = context.getDate(ree.get(Service.C.startDate));
-// Long endDateL = (Long) ree.get(ServiceView.C.endDate);
-// Date endDate = endDateL == null ? null : new Date(endDateL);
-//
-// String sType = (String) ree.get(Service.C.sType);
-//
-// List<QualifierType> tslQual = ree.getQualifierList();
-//
-// StringBuilder qualList = new StringBuilder("");
-// if (!tslQual.isEmpty()) {
-// qualList.append("\n~~~~~~~~~~~~ TSL-Qualifiers ~~~~~~~~~~~~\n");
-// for (QualifierType qual : tslQual) {
-// qualList.append(qual.getUri() + "\n");
-// }
-// qualList.append("~~~~~~~~~~~~~~~~~ End ~~~~~~~~~~~~~~~~\n");
-// }
-//
-// log.info("############### EndEntity ###############\n"
-// + _.printCertificate(e.getKey()) + qualList + "\nServiceProvider: "
-// + ree.getSerivceProvider().getSubjectDN() + "\n" + Service.C.sType
-// + ": " + sType + "\n" + Service.C.status + ": " + status + "\n"
-// + Service.C.startDate + ": " + startDate + "\n"
-// + ServiceView.C.endDate + ": " + endDate);
-// log.info("############ ServiceProvider ############\n"
-// + _.printCertificate(ree.getSerivceProvider()));
-// log.info("################# END #################");
-//
-// continue;
-// }
-//
-// if (r instanceof TSLResultImpl) {
-// TSLResultImpl ri = (TSLResultImpl) r;
-// log.info("----------------- BEGIN -----------------\n"
-// + "Certificate: " + e.getKey().getSubjectDN() + "\n" + ri.toString());
-//
-// int i = 1;
-// for (Iterator iter = ri.getRows().iterator(); iter.hasNext();) {
-// Row row = (Row) iter.next();
-// // TSPServiceInformationType sInfo =
-// // ((JAXBElement<TSPServiceInformationType>)
-// // row.s_.get(Service.C.sInfo)).getValue();
-// String status = (String) row.s_.get(Service.C.status);
-//
-// Date startDate = context.getDate(row.s_.get(Service.C.startDate));
-//
-// Date endDate = context.getDate(row.s_.get(ServiceView.C.endDate));
-//
-// String sType = (String) row.s_.get(Service.C.sType);
-//
-// log.info("----------------- (" + (i++) + ") -----------------\n"
-// + Service.C.sType + ": " + sType + " " + Service.C.status + ": "
-// + status + "\n" + Service.C.startDate + ": " + startDate + "\n"
-// + ServiceView.C.endDate + ": " + endDate + "\n" + row.s_);
-//
-// row.s_.get(Service.C.sExt);
-// }
-// log.info("----------------- END -----------------");
-// }
-// }
-// }
-}
diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/TSLConnectorInterface.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/TSLConnectorInterface.java deleted file mode 100644 index 4992f75..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/connector/TSLConnectorInterface.java +++ /dev/null @@ -1,95 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.connector;
-
-import iaik.xml.crypto.tsl.ex.TSLEngineDiedException;
-import iaik.xml.crypto.tsl.ex.TSLSearchException;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Date;
-
-import java.security.cert.X509Certificate;
-
-public interface TSLConnectorInterface {
-
- /**
- * Initial the MOA TSL Connector.<br>
- * <b>The hashcache directory must be set via "System-Property "iaik.xml.crypto.tsl.BinaryHashCache.DIR"!!!</b>
- *
- * @author TLenz
- * @param euTSLURL - URL to TrustList
- * @param TSLWorkingDirectoryPath - Path to a folder which should be used by the TSL engine. (/A/B/.../)
- * @param jdbcURL - ...
- * @param jdbcDriverClass - ...
- */
- void initialize(String euTSLURL, String TSLWorkingDirectoryPath, String jdbcURL, String jdbcDriverClass) throws TSLEngineDiedException;
-
-
- /**
- * Perform an update of all certificates which are on EU TSL and all MS TSLs and create an locale TSL database.
- * The old locale TSL database is removed and a new database is created.
- *
- * @author TLenz
- * @param dateTime - ...
- * @param serviceLevelStatus - String Array of ServiceLevelStatus. For example new String[]{"accredited","undersupervision"}
- * @return List of certificates with the selected properties
- */
- ArrayList<File> updateAndGetQualifiedCACertificates(Date dateTime, String[] serviceLevelStatus)
- throws TSLEngineDiedException, TSLSearchException ;
-
- /**
- * Perform an update of all certificates which are on EU TSL and all MS TSLs and create an locale TSL database.
- * The old locale TSL database is removed and a new database is created.
- *
- * @author TLenz
- * @param dateTime - ...
- * @param countries - String Array of country codes. For example new Sting[]{"AT","IT","BE"}
- * @param serviceLevelStatus - String Array of ServiceLevelStatus. For example new String[]{"accredited","undersupervision"}
- * @return List of certificates with the selected properties
- */
- ArrayList<File> updateAndGetQualifiedCACertificates(Date dateTime, String[] countries, String[] serviceLevelStatus)
- throws TSLEngineDiedException, TSLSearchException ;
-
- /**
- * Check the http://uri.etis.org/TrstSvc/Svctype/CA/QC characteristic of a certificate by using the TSL information.
- * This method uses information from the local TSL database.
- *
- * @author TLenz
- * @param certificate - An X509 certificate.
- * @return Return true, if the certificate comprises the http://uri.etis.org/TrstSvc/Svctype/CA/QC characteristic.
- */
- boolean checkQC(X509Certificate[] certificate) throws TSLSearchException, TSLEngineDiedException;
-
- /**
- * Check the http://uri.etis.org/TrstSvc/eSigDir-1999-93-ECTrustedList/SvcInfoExt/QCWithSSCD characteristic of a certificate by using the TSL information.
- * This method uses information from the local TSL database.
- *
- * @author TLenz
- * @param certificate - An X509 certificate.
- * @return Return true, if the certificate comprises the http://uri.etis.org/TrstSvc/eSigDir-1999-93-ECTrustedList/SvcInfoExt/QCWithSSCD characteristic.
- */
- boolean checkSSCD(X509Certificate[] certificate) throws TSLSearchException, TSLEngineDiedException;
-
- /**
- * Get a list of certificates form the local TSL database with the selected properties.
- *
- * @author TLenz
- * @param dateTime - ...
- * @param serviceLevelStatus - String Array of ServiceLevelStatus. For example new String[]{"accredited","undersupervision"}
- * @return List of certificates with the selected properties
- */
- ArrayList<File> getQualifiedCACertificates(Date dateTime, String[] serviceLevelStatus)
- throws TSLEngineDiedException, TSLSearchException;
-
- /**
- * Get a list of certificates form the local TSL database with the selected properties.
- *
- * @author TLenz
- * @param dateTime - ...
- * @param countries - String Array of countrie codes. For example new Sting[]{"AT","IT","BE"}
- * @param serviceLevelStatus - String Array of ServiceLevelStatus. For example new String[]{"accredited","undersupervision"}
- * @return List of certificates with the selected properties
- */
- ArrayList<File> getQualifiedCACertificates(Date dateTime, String[] countries, String[] serviceLevelStatus)
- throws TSLEngineDiedException, TSLSearchException;
-
-}
diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/exception/MitigatedTSLSecurityException.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/exception/MitigatedTSLSecurityException.java deleted file mode 100644 index d580405..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/exception/MitigatedTSLSecurityException.java +++ /dev/null @@ -1,17 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.exception;
-
-import iaik.xml.crypto.tsl.ex.TSLSecurityException;
-
-import org.xml.sax.Locator;
-
-public final class MitigatedTSLSecurityException extends
- TSLSecurityException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- public MitigatedTSLSecurityException(Type t, Locator l) {
- super(t, l);
- }
-}
\ No newline at end of file diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/timer/TSLUpdaterTimerTask.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/timer/TSLUpdaterTimerTask.java index 61e305b..300bcae 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/timer/TSLUpdaterTimerTask.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/timer/TSLUpdaterTimerTask.java @@ -8,8 +8,6 @@ import iaik.pki.store.truststore.TrustStoreProfile; import iaik.pki.store.utils.StoreUpdater;
import iaik.server.ConfigurationData;
import iaik.x509.X509Certificate;
-import iaik.xml.crypto.tsl.ex.TSLEngineDiedException;
-import iaik.xml.crypto.tsl.ex.TSLSearchException;
import java.io.File;
import java.io.FileInputStream;
@@ -22,6 +20,8 @@ import java.util.Iterator; import java.util.Map;
import java.util.TimerTask;
+import at.gv.egovernment.moa.sig.tsl.exception.TslException;
+import at.gv.egovernment.moa.sig.tsl.exception.TslUpdateException;
import at.gv.egovernment.moa.spss.MOAApplicationException;
import at.gv.egovernment.moa.spss.api.common.TSLConfiguration;
import at.gv.egovernment.moa.spss.server.config.ConfigurationException;
@@ -30,7 +30,7 @@ import at.gv.egovernment.moa.spss.server.config.TrustProfile; import at.gv.egovernment.moa.spss.server.iaik.config.IaikConfigurator;
import at.gv.egovernment.moa.spss.server.iaik.pki.store.truststore.TrustStoreProfileImpl;
import at.gv.egovernment.moa.spss.server.logging.TransactionId;
-import at.gv.egovernment.moa.spss.tsl.connector.TSLConnector;
+import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory;
import at.gv.egovernment.moa.spss.util.MessageProvider;
import at.gv.egovernment.moaspss.logging.LogMsg;
import at.gv.egovernment.moaspss.logging.Logger;
@@ -38,177 +38,25 @@ import at.gv.egovernment.moaspss.util.StringUtils; public class TSLUpdaterTimerTask extends TimerTask {
-
- public static TSLConnector tslconnector_;
-
- public static ConfigurationData configData_ = null;
-
+
@Override
public void run() {
try {
Logger.info("Start TSL Update");
- update();
+ TSLServiceFactory.getTSLServiceClient().updateTSLInformation();
Logger.info("Finished TSL Update");
- } catch (TSLEngineDiedException e) {
- MessageProvider msg = MessageProvider.getInstance();
- Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e);
- } catch (TSLSearchException e) {
- MessageProvider msg = MessageProvider.getInstance();
- Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e);
- } catch (ConfigurationException e) {
- MessageProvider msg = MessageProvider.getInstance();
- Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e);
- } catch (MOAApplicationException e) {
- MessageProvider msg = MessageProvider.getInstance();
- Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e);
- } catch (CertStoreException e) {
- MessageProvider msg = MessageProvider.getInstance();
- Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e);
- } catch (TrustStoreException e) {
- MessageProvider msg = MessageProvider.getInstance();
- Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e);
- } catch (FileNotFoundException e) {
- MessageProvider msg = MessageProvider.getInstance();
- Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e);
- } catch (IOException e) {
+
+ } catch (TslUpdateException e) {
MessageProvider msg = MessageProvider.getInstance();
Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e);
- } catch (CertificateException e) {
+
+ } catch (TslException e) {
MessageProvider msg = MessageProvider.getInstance();
Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e);
- }
-
- }
-
- public static void update() throws TSLEngineDiedException, TSLSearchException, ConfigurationException, MOAApplicationException, CertStoreException, TrustStoreException, CertificateException, IOException {
- MessageProvider msg = MessageProvider.getInstance();
-
- //TrustProfile tp = null;
- TrustStoreProfile tsp = null;
- StoreUpdater storeUpdater = null;
- TransactionId tid = null;
-
- //get TSl configuration
- ConfigurationProvider config = ConfigurationProvider.getInstance();
- if (configData_ == null)
- configData_ = new IaikConfigurator().configure(config);
- TSLConfiguration tslconfig = config.getTSLConfiguration();
- if (tslconfig != null) {
-
- tslconnector_.updateTSLs(new Date(), new String[]{"granted","recognisedatnationallevel"});
-
- Logger.info(new LogMsg(msg.getMessage("config.42", null)));
-
- // get certstore parameters
- CertStoreParameters[] certStoreParameters = configData_.getPKIConfiguration().getCertStoreConfiguration().getParameters();
-
- // iterate over all truststores
- Map mapTrustProfiles = config.getTrustProfiles();
- Iterator it = mapTrustProfiles.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry pairs = (Map.Entry)it.next();
- TrustProfile tp = (TrustProfile) pairs.getValue();
- if (tp.isTSLEnabled()) {
- tsp = new TrustStoreProfileImpl(config, tp.getId());
- TrustStoreProfile[] trustStoreProfiles = new TrustStoreProfile[1];
- trustStoreProfiles[0] = tsp;
-
-
- Logger.debug(new LogMsg(msg.getMessage("config.43", new String[]{tp.getId()})));
-
- tid = new TransactionId("TSLConfigurator-" + tp.getId());
- ArrayList tsl_certs = null;
- if (StringUtils.isEmpty(tp.getCountries())) {
- Logger.debug(new LogMsg(msg.getMessage("config.44", null)));
-
- // get certificates from TSL from all countries
- tsl_certs = tslconnector_.getQualifiedCACertificates(new Date(), new String[]{"granted","recognisedatnationallevel"});
- }
- else {
- Logger.debug(new LogMsg(msg.getMessage("config.44", null)));
- // get selected countries as array
- String countries = tp.getCountries();
- String[] array = countries.split(",");
- for (int i = 0; i < array.length; i++)
- array[i] = array[i].trim();
-
- // get certificates from TSL from given countries
- tsl_certs = tslconnector_.getQualifiedCACertificates(new Date(), array, new String[]{"granted","recognisedatnationallevel"});
- }
-
- // create store updater for each TSL enabled truststore
- Logger.debug(new LogMsg(msg.getMessage("config.45", null)));
- storeUpdater = new StoreUpdater(certStoreParameters, trustStoreProfiles, tid);
-
- // delete files in trustprofile
-
- File ftp = new File(tp.getUri());
- File[] files = ftp.listFiles();
- X509Certificate[] removeCertificates = new X509Certificate[files.length];
- int i = 0;
- for (File file : files) {
- FileInputStream fis = new FileInputStream(file);
- removeCertificates[i] = new X509Certificate(fis);
- i++;
- fis.close();
- //file.delete();
- }
-
- // remove all certificates
- storeUpdater.removeCertificatesFromTrustStores(removeCertificates, tid);
- storeUpdater.removeCertificatesFromCertStores(removeCertificates, tid);
-
-
- // copy files from original trustAnchorsLocURI into tslworking trust profile
- File src = new File(tp.getUriOrig());
- files = src.listFiles();
- X509Certificate[] addCertificates = new X509Certificate[files.length];
- i = 0;
- for (File file : files) {
- FileInputStream fis = new FileInputStream(file);
- addCertificates[i] = new X509Certificate(fis);
- //FileUtils.copyFile(file, new File(tp.getUri(), file.getName()));
- i++;
- fis.close();
- }
-
- // convert ArrayList<File> to X509Certificate[]
- if (tsl_certs == null) {
- Logger.warn("No certificates from TSL imported.");
- //throw new TSLSearchException("No certificates from TSL imported.");
- }
- else {
-
- X509Certificate[] addCertificatesTSL = new X509Certificate[tsl_certs.size()];
- Iterator itcert = tsl_certs.iterator();
- i = 0;
- File f = null;
- while(itcert.hasNext()) {
- f = (File)itcert.next();
- FileInputStream fis = new FileInputStream(f);
- X509Certificate cert = new X509Certificate(fis);
- addCertificatesTSL[i] = cert;
-
- i++;
- fis.close();
- }
-
- Logger.info(new LogMsg("Add " + addCertificatesTSL.length + " certificates to " + tp.getId() + " from TSL."));
- storeUpdater.addCertificatesToTrustStores(addCertificatesTSL, tid);
- storeUpdater.addCertificatesToCertStores(addCertificatesTSL, tid);
-
- Logger.info(new LogMsg("Add " + addCertificates.length + " certificates to " + tp.getId() + "."));
- storeUpdater.addCertificatesToTrustStores(addCertificates, tid);
- storeUpdater.addCertificatesToCertStores(addCertificates, tid);
- }
- }
- }
- }
-
+ }
-
}
}
diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/Mitigation.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/Mitigation.java deleted file mode 100644 index a1635b8..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/Mitigation.java +++ /dev/null @@ -1,15 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.utils;
-
-public class Mitigation extends iaik.xml.crypto.tsl.ex.SeverityAspect.Mitigation {
-
- String report_;
-
- public Mitigation(String report) {
- report_ = report;
- }
-
- @Override
- public String getReport() {
- return report_;
- }
-}
\ No newline at end of file diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/TSLEUImportFromFileContext.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/TSLEUImportFromFileContext.java deleted file mode 100644 index e0fff56..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/TSLEUImportFromFileContext.java +++ /dev/null @@ -1,146 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.utils;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.sqlite.SQLiteErrorCode;
-
-import iaik.util.logging.Log;
-import iaik.util.logging.GeneralLog;
-import iaik.util.logging.Log.MultiThreadLoggingGroup;
-import iaik.xml.crypto.tsl.DbTables;
-import iaik.xml.crypto.tsl.TSLImportFromFileContext;
-import iaik.xml.crypto.tsl.TSLOpenURIException;
-import iaik.xml.crypto.tsl.constants.Countries;
-import iaik.xml.crypto.tsl.ex.TSLExceptionB;
-import iaik.xml.crypto.tsl.ex.ThrowableAndLocatorAndMitigation;
-import iaik.xml.crypto.tsl.ex.SeverityAspect.Severity;
-import iaik.xml.crypto.tsl.fetch.TopLevelTslFetchContext;
-
-public class TSLEUImportFromFileContext extends TopLevelTslFetchContext {
-
- public TSLEUImportFromFileContext(
- Countries euTerritory,
- URL euTslURL,
- String workingdirectory,
- boolean sqlMultithreaded,
- boolean throwExceptions,
- boolean logExceptions,
- boolean throwWarnings,
- boolean logWarnings,
- boolean nullRedundancies) {
-
- super(
- euTerritory,
- euTslURL,
- workingdirectory,
- sqlMultithreaded,
- throwExceptions,
- logExceptions,
- throwWarnings,
- logWarnings,
- nullRedundancies);
-
- }
-
- public List<ThrowableAndLocatorAndMitigation> getErrorsAndWarnings() {
- List<ThrowableAndLocatorAndMitigation> errorsAndWarnings = new ArrayList<ThrowableAndLocatorAndMitigation>();
- errorsAndWarnings.addAll(this.fatals_);
- errorsAndWarnings.addAll(this.faildTransactions_);
- errorsAndWarnings.addAll(this.warnings_);
-
- return errorsAndWarnings;
- }
-
- @Override
- public boolean normalizeXML() {
- return true;
- }
-
- @Override
- public Object throwException(Throwable e, Method enclosingMethod,
- Object thisObject, Object[] parameters) {
-
- if (enclosingMethod != null){
- if (
- e instanceof TSLOpenURIException &&
- enclosingMethod.getName().equals("processUrl") &&
- TSLImportFromFileContext.class.isAssignableFrom(enclosingMethod.getDeclaringClass()) &&
- parameters[1] instanceof File &&
- e.getCause() instanceof IOException &&
- parameters[0] instanceof URL
- ){
-
- GeneralLog.err("Ignoring download error using old: " + parameters[0],null);
- wrapException(e);
- return parameters[1];
- }
- }
-
- //we allow each and every funny stuff from the EU as long as it's not insecure
- if (e instanceof TSLExceptionB){
- TSLExceptionB ve = (TSLExceptionB) e;
- Severity s = ve.getSeverity();
- if ( s != null && s.ordinal() < Severity.insecure.ordinal()){
- GeneralLog.err("Ignored Exception: ",ve);
-// if(logExceptions_){
- warnings_.add(
- new ThrowableAndLocatorAndMitigation(
- ve, null, ve.getLocator(), ve.getMitigation()
- )
- );
-// }
- return null;
- }
- }
-
-
- return super.throwException(e, enclosingMethod, thisObject, parameters);
- }
-
- @Override
- public Boolean doesViolateRawHash(SQLException e, byte[] rawHash) {
-
- String msg = e.getMessage();
- return (
- msg.startsWith("["+SQLiteErrorCode.SQLITE_CONSTRAINT.name()+"]") &&
- msg.contains("column " + DbTables.TSLDownload.C.rawHash + " is not unique")
- );
- }
-
- public MultiThreadLoggingGroup getLoggingGroup() {
- return this;
- }
-
- StringBuilder log = new StringBuilder();
-
- public void flushLog() {
- if (log != null && log.length() > 0) {
- Thread currentThread = Thread.currentThread();
- String ncName = getNcName(currentThread);
-
- synchronized (log) {
- print(
- "<" + ncName + " state=\"" + currentThread.getState() + "\" " + " id=\"" + currentThread.getId() + "\">\n"
- + log.toString() + "</" + ncName + ">\n");
- log.setLength(0);
- }
- }
- }
-
- public void print(Object msg) {
- Log.print(msg);
- }
-
- @Override
- public FileFilter getCertificateFileFilter() {
- return null;
- }
-
-}
diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/TSLEvaluationContext.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/TSLEvaluationContext.java deleted file mode 100644 index f0723a1..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/TSLEvaluationContext.java +++ /dev/null @@ -1,134 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.utils;
-
-import iaik.util.logging.Log.MultiThreadLoggingGroup;
-import iaik.util.logging.Log;
-import iaik.util.logging.GeneralLog;
-import iaik.xml.crypto.tsl.BaseClass;
-import iaik.xml.crypto.tsl.SIEExtensionChecker;
-import iaik.xml.crypto.tsl.constants.Countries;
-import iaik.xml.crypto.tsl.ex.TSLSIEExtensionException;
-import iaik.xml.crypto.tsl.ex.SeverityAspect.Mitigation;
-import iaik.xml.crypto.tsl.sie.gen.CriteriaListType;
-import iaik.xml.crypto.tsl.sie.gen.KeyUsageBitType;
-import iaik.xml.crypto.tsl.sie.gen.KeyUsageType;
-import iaik.xml.crypto.tsl.sie.gen.ObjectFactory;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-public final class TSLEvaluationContext extends iaik.xml.crypto.tsl.TSLEvaluationContext {
-
- public TSLEvaluationContext(
- String workingdirectory,
- boolean sqlMultithreaded,
- boolean throwExceptions,
- boolean logExceptions,
- boolean throwWarnings,
- boolean logWarnings) {
- super(workingdirectory,
- sqlMultithreaded,
- throwExceptions,
- logExceptions,
- throwWarnings,
- logWarnings);
- }
-
- @Override
- public Object throwException(Throwable e, Method enclosingMethod,
- Object thisObject, Object[] parameters) {
-
- if (e instanceof TSLSIEExtensionException
- && e.getMessage() == TSLSIEExtensionException.NO_KEYUSEAGE_NOR_POLICYSET) {
-
- CriteriaListType criteriaList = (CriteriaListType) parameters[1];
-
- GeneralLog.warn(criteriaList.getDescription());
-
- String description = criteriaList.getDescription();
- if (description
- .trim()
- .equals(
- "This service issues qualified certificates for e-signing and "
- + "e-authentication within the same process. The Relaying Party shall "
- + "make distinction by inspection of keyUsage field contents - "
- + "e-signature certificates have non-repudation bit set exclusively.")) {
- criteriaList.setAssert(SIEExtensionChecker.Asssert.all.toString());
-
- ObjectFactory of = new ObjectFactory();
- KeyUsageType ku = of.createKeyUsageType();
- KeyUsageBitType kb = of.createKeyUsageBitType();
- kb.setName(SIEExtensionChecker.KeyUseageBit.nonRepudiation
- .toString());
- kb.setValue(true);
- ku.getKeyUsageBit().add(kb);
- criteriaList.getKeyUsage().add(ku);
-
- Object mitigatedResult = null;
- try {
- mitigatedResult = enclosingMethod.invoke(thisObject, parameters);
-
- } catch (IllegalAccessException e1) {
- wrapException(e1);
- } catch (InvocationTargetException e1) {
- wrapException(e1);
- }
-
- if (mitigatedResult != null) {
- wrapException(e, criteriaList.sourceLocation(), new Mitigation() {
- @Override
- public String getReport() {
- return "Fixed invalid criteria list";
- }
- });
- return mitigatedResult;
- }
-
- }
- }
- return super.throwException(e, enclosingMethod, thisObject, parameters);
- }
-
- @Override
- protected long howLongWaitForThreads() {
- return 10000;
- }
-
- @Override
- protected BaseClass getCurrentBaseClass() {
- //TODO check whether we can avoid by redesign to focus this only on import
- return null;
- }
-
- @Override
- public boolean normalizeXML() {
- return true;
- }
-
- public Countries getExpectedTerritory() {
- return null;
- }
-
- public MultiThreadLoggingGroup getLoggingGroup() {
- return this;
- }
-
- StringBuffer log = new StringBuffer();
-
- public void flushLog() {
- if (log != null && log.length() > 0) {
- synchronized (System.out) {
- Thread currentThread = Thread.currentThread();
- print("# # # " + getHint() + " Thread: "
- + currentThread.getName() + "(" + currentThread.getId()
- + ") collected logs - BEGIN # # #\n" + log.toString() + "# # # "
- + getHint() + " Thread: " + currentThread.getName()
- + "(" + currentThread.getId() + ") collected logs - END # # #\n");
- }
- log = null;
- }
- }
-
- public void print(Object msg) {
- Log.print(msg);
- }
-}
\ No newline at end of file diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/TSLImportFromFileContext.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/TSLImportFromFileContext.java deleted file mode 100644 index eda2b34..0000000 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/TSLImportFromFileContext.java +++ /dev/null @@ -1,855 +0,0 @@ -package at.gv.egovernment.moa.spss.tsl.utils;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.OutputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.security.InvalidKeyException;
-import java.security.KeyFactory;
-import java.security.NoSuchAlgorithmException;
-import java.security.PublicKey;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-
-import javax.xml.bind.Unmarshaller;
-import javax.xml.crypto.AlgorithmMethod;
-import javax.xml.crypto.KeySelectorException;
-
-import org.apache.log4j.Logger;
-import org.sqlite.SQLiteErrorCode;
-import org.w3c.dom.DOMError;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXParseException;
-
-import at.gv.egovernment.moa.spss.tsl.exception.MitigatedTSLSecurityException;
-import iaik.util.logging.Log.MultiThreadLoggingGroup;
-import iaik.util.logging.GeneralLog;
-import iaik.utils.RFC2253NameParserException;
-import iaik.utils.Util;
-import iaik.util.GeneralUtils15;
-import iaik.xml.crypto.dsig.keyinfo.X509DataImpl;
-import iaik.xml.crypto.tsl.DbTables;
-import iaik.xml.crypto.tsl.TSLConstants;
-import iaik.xml.crypto.tsl.TSLContext;
-import iaik.xml.crypto.tsl.TSLEngine;
-import iaik.xml.crypto.tsl.TSLImportContext;
-import iaik.xml.crypto.tsl.TSLOpenURIException;
-import iaik.xml.crypto.tsl.TSLThreadContext;
-import iaik.xml.crypto.tsl.ValidationFixupFilter;
-import iaik.xml.crypto.tsl.ValidationFixupFilter.AttributeValueFixup;
-import iaik.xml.crypto.tsl.ValidationFixupFilter.DeleteAttrFixup;
-import iaik.xml.crypto.tsl.ValidationFixupFilter.ElementStringValueFixup;
-import iaik.xml.crypto.tsl.ValidationFixupFilter.FixedSaxLevelValidationExcption;
-import iaik.xml.crypto.tsl.ValidationFixupFilter.Fixup;
-import iaik.xml.crypto.tsl.ValidationFixupFilter.LocalNameFixup;
-import iaik.xml.crypto.tsl.constants.Countries;
-import iaik.xml.crypto.tsl.ex.LocatorAspect;
-import iaik.xml.crypto.tsl.ex.TSLEngineFatalException;
-import iaik.xml.crypto.tsl.ex.TSLRuntimeWarning;
-import iaik.xml.crypto.tsl.ex.TSLSecurityException;
-import iaik.xml.crypto.tsl.ex.TSLSecurityException.Type;
-import iaik.xml.crypto.tsl.ex.TSLVerificationException;
-import iaik.xml.crypto.tsl.gen.DigitalIdentityType;
-import iaik.xml.crypto.tsl.verify.TSLDOMErrorHandler;
-import iaik.xml.crypto.tsl.verify.TSLValidationException;
-import iaik.xml.crypto.tsl.verify.TslKeySelector;
-import iaik.xml.crypto.utils.KeySelectorImpl.X509KeySelectorResultImpl;
-
-/**
- *
- */
-
-public class TSLImportFromFileContext extends iaik.xml.crypto.tsl.TSLImportFromFileContext {
-
- static Logger l = Logger.getLogger(TSLImportFromFileContext.class);
-
- public static final class ExceptionalMitigation extends Mitigation {
- public ExceptionalMitigation(String report) {
- super(report);
- }
- }
-
- public static final class FixedValidationMitigation extends Mitigation {
- public FixedValidationMitigation(String report) {
- super(report);
- }
- }
-
- private final String baseuri_;
- private Map<Countries, ListIterator<X509Certificate>>
- trustAnchorsWrongOnEuTsl_;
-
- public TSLImportFromFileContext(
- Countries expectedTerritory,
- URL url,
- Number otherTslPointerId,
- String workingdirectory,
- boolean sqlMultithreaded,
- boolean throwExceptions,
- boolean logExceptions,
- boolean throwWarnings,
- boolean logWarnings,
- boolean nullRedundancies,
- String baseuri,
- Map <Countries, ListIterator<X509Certificate>> trustAnchorsWrongOnEuTsl,
- TSLThreadContext parentContext) {
- super(
- expectedTerritory,
- url,
- otherTslPointerId,
- workingdirectory,
- sqlMultithreaded,
- throwExceptions,
- logExceptions,
- throwWarnings,
- logWarnings,
- nullRedundancies,
- parentContext);
- baseuri_ = baseuri;
- trustAnchorsWrongOnEuTsl_ = trustAnchorsWrongOnEuTsl;
- }
- /* (non-Javadoc)
- * @see iaik.xml.crypto.tsl.TSLImportFromFileContext#getbaseURI()
- */
- @Override
- public String getbaseURI() {
- return this.baseuri_;
- }
-
-
-
-
- //@Override
- protected RuntimeException wrapException(Throwable t, Locator l, Mitigation m) {
- return super.wrapException(t, l, m);
- }
-
- @Override
- public
- synchronized void throwException(Throwable e) {
-
- if (e instanceof TSLValidationException) {
- // we do not throw dom validation errors for testing
- // and just collect them
- wrapException(e);
- } else if (e instanceof TSLVerificationException) {
-
- boolean corrected = false;
- // we do not throw verification errors for testing
- // and just collect them
-
-// // NEVER DO THIS! unless you want to import TSLs without signatures.
-// if (Boolean.valueOf(_.getSysProperty(TSLSecurityException.Type.NO_TSL_SIGNATURE
-// .getClass().getName(), "true"))
-// && ((TSLVerificationException) e).getType() == TSLSecurityException.Type.NO_TSL_SIGNATURE) {
-// ((TSLVerificationException) e).setMitigation(Mitigation.IGNORED);
-// }
-//
-// if (Boolean.valueOf(_.getSysProperty(TSLSecurityException.Type.NON_CONFORMANT_REFERENCE_IN_TSL_SIGNATURE
-// .getClass().getName(), "true"))
-// && ((TSLVerificationException) e).getType() == TSLSecurityException.Type.NON_CONFORMANT_REFERENCE_IN_TSL_SIGNATURE) {
-// ((TSLVerificationException) e).setMitigation(Mitigation.IGNORED);
-// }
-
-// if (Boolean.valueOf(_.getSysProperty(TSLSecurityException.Type.NON_CONFORMANT_TRANSFORMS_IN_TSL_SIGNATURE
-// .getClass().getName(), "true"))
-// && ((TSLVerificationException) e).getType() == TSLSecurityException.Type.NON_CONFORMANT_TRANSFORMS_IN_TSL_SIGNATURE) {
-// ((TSLVerificationException) e).setMitigation(Mitigation.IGNORED);
-//
-// corrected = true;
-// }
-//
-//
-// if (Boolean.valueOf(_.getSysProperty(TSLSecurityException.Type.NON_CONFORMANT_TRANSFORM_IN_TSL_SIGNATURE
-// .getClass().getName(), "true"))
-// && ((TSLVerificationException) e).getType() == TSLSecurityException.Type.NON_CONFORMANT_TRANSFORM_IN_TSL_SIGNATURE) {
-// ((TSLVerificationException) e).setMitigation(Mitigation.IGNORED);
-//
-// corrected = true;
-// }
-//
-// if (Boolean.valueOf(_.getSysProperty(TSLSecurityException.Type.NON_CONFORMANT_C14N_IN_TSL_SIGNATURE
-// .getClass().getName(), "true"))
-// && ((TSLVerificationException) e).getType() == TSLSecurityException.Type.NON_CONFORMANT_C14N_IN_TSL_SIGNATURE) {
-// ((TSLVerificationException) e).setMitigation(Mitigation.IGNORED);
-//
-// corrected = true;
-// }
-//
-// if (corrected)
-// wrapException(e);
-// else
-// super.throwException(e);
-
- super.throwException(e);
-
- } else if (e instanceof FileNotFoundException) {
- // we do not stop and continue processing
- wrapException(e);
- } else if (e instanceof IllegalArgumentException) {
- // we do not stop and continue processing
- wrapException(e);
- } else {
- // all other errors are treated as per default
- super.throwException(e);
- }
- }
-
- /* (non-Javadoc)
- * @see iaik.xml.crypto.tsl.TSLContext#throwException(java.lang.Exception, java.lang.reflect.Method, java.lang.Object, java.lang.Object[])
- */
- @Override
- public Object throwException(
- Throwable e, Method enclosingMethod, Object thisObject, final Object[] parameters) {
-
- if (enclosingMethod != null){
-
- if(
- e instanceof FixedSaxLevelValidationExcption &&
- enclosingMethod.getDeclaringClass().equals(ValidationFixupFilter.class)){
- wrapException(e,
- ((LocatorAspect) e).getLocator(),
- new FixedValidationMitigation("Performed SAX Level Fixup."));
- return null;
- }
-
- if(e instanceof CertificateException &&
- enclosingMethod.getDeclaringClass().equals(TSLImportContext.class) &&
- enclosingMethod.getName().equals("parseCertificate")) {
-
- wrapException(e);
- // ((DigitalIdentityType)parameters[1]).sourceLocation();
-
- return null;
- }
-
- if (e instanceof TSLValidationException&&
- enclosingMethod.getDeclaringClass().equals(TSLDOMErrorHandler.class) &&
- enclosingMethod.getName().equals("handleError")) {
-
- if (parameters[0] instanceof DOMError) {
- DOMError domError = (DOMError) parameters[0];
-
- GeneralLog.warn(""+domError.getRelatedData());
-
- // domError.getRelatedData().getClass().getField("")
-
- wrapException(e);
- return Boolean.TRUE;
- }
- }
-
- if (e instanceof RFC2253NameParserException&&
- enclosingMethod.getDeclaringClass().equals(TSLImportContext.class) &&
- enclosingMethod.getName().equals("getNormalizedDN") &&
- parameters[0] instanceof DigitalIdentityType ) {
-
- DigitalIdentityType digitalId = (DigitalIdentityType) parameters[0];
-
- String subDN = digitalId.getX509SubjectName();
-
- // String openSslRdnRegExp = "/([^=]+)=?(([^/]+)|\"([^\"]+)\"";
-
- String openSslRdnRegExp = "/([^=]+)=(\"([^\"]*)\"|([^/\"][^/]*)|(.{0}))";
- // 1 2 3 4 5
- // 1 matches Attribute
- // 2 matches values
- // 2 greedy matches properly quoted values
- // 3 greedy matches values without quotes
- // 4 matches the empty value
- if (subDN.matches("^("+openSslRdnRegExp+")+$")){
- //trigger openSSL format error handling
-
- Object mitigatedResult = null;
-
- String[] rdns = subDN.substring(1, subDN.length()).split("/");
-
- rdns = (String[]) GeneralUtils15.reverseInPlace(rdns);
-
- subDN = "/"+GeneralUtils15.implode("/", rdns);
-
- //for now we only support properly quoted values or such without quotes
-
- subDN = subDN.replaceAll(openSslRdnRegExp, "$1=\"$2$3\",");
- subDN = subDN.substring(0, subDN.length()-1);
-
- digitalId.setX509SubjectName(subDN);
- try {
- mitigatedResult = enclosingMethod.invoke(thisObject, new Object[]{digitalId});
-
- } catch (IllegalAccessException e1) {
- wrapException(e1);
- } catch (InvocationTargetException e1) {
- wrapException(e1);
- }
-
- if (mitigatedResult != null){
- wrapException(e, digitalId.sourceLocation(), new iaik.xml.crypto.tsl.ex.SeverityAspect.Mitigation() {
- @Override
- public String getReport() {
- return "Converted OpenSSL SubjectDN";
- }
- });
- return mitigatedResult;
-
- }
- }
-
- wrapException(
- new TSLRuntimeWarning("Could not normalize :" + (digitalId).getX509SubjectName(), e),
- digitalId.sourceLocation());
-
- //if we cannot Normalize the DN we simply don't
- return (digitalId).getX509SubjectName();
- }
-
- //TODO check if this is really needed for ESP TSL
- if (e instanceof RFC2253NameParserException &&
- enclosingMethod.getDeclaringClass().equals(TSLImportContext.class) &&
- enclosingMethod.getName().equals("getNormalizedSubjectDN") &&
- parameters[0] instanceof X509Certificate ) {
-
- X509Certificate cert = (X509Certificate) parameters[0];
-
-
- wrapException(e, null);
- //if we cannot Normalize the DN we simply don't
- return cert.getSubjectDN().getName();
- }
-
- if (
- (expectedTerritory_ == Countries.MT || expectedTerritory_ == Countries.LT)&&
- e instanceof TSLOpenURIException &&
- enclosingMethod.getDeclaringClass().equals(TSLImportFromFileContext.class) &&
- enclosingMethod.getName().equals("processUrl") &&
- parameters[1] instanceof File){
-
- URL url = null;
- if (
- e.getCause() instanceof FileNotFoundException &&
- parameters[0] instanceof URL &&
- (url =((URL)parameters[0])).getProtocol().equalsIgnoreCase("http")
- ){
- try {
- //Malta just changed their URL ...
- if ("http://www.mca.org.mt/tsl/MT_TSL.xml".equalsIgnoreCase(url.toString())){
- url = new URL("http://www.mca.org.mt/sites/default/files/pageattachments/MT_TSL.xml");
- } else {
- url = new URL("https", url.getHost(), url.getFile());
- }
- } catch (MalformedURLException e1) {
- wrapException(e1);
- }
-
- Object mitigatedResult = null;
- try {
-
- mitigatedResult = enclosingMethod.invoke(thisObject, new Object[]{url,parameters[1]});
- } catch (IllegalAccessException e1) {
- wrapException(e1);
- } catch (InvocationTargetException e1) {
- wrapException(e1);
- }
-
- if (mitigatedResult != null){
- wrapException(e, null, new iaik.xml.crypto.tsl.ex.SeverityAspect.Mitigation() {
- @Override
- public String getReport() {
- return "Trying https:// ...";
- }
- });
- return mitigatedResult;
- }
- }
-
- GeneralLog.err("Ignoring download error using old: " + parameters[0], null);
- wrapException(e);
- return parameters[1];
- }
-
-// if (
-// expectedTerritory_ == Countries.PL &&(
-// (e.getCause() instanceof java.io.EOFException ||
-// e.getCause() instanceof iaik.security.ssl.SSLException) &&
-// parameters[0] instanceof URL &&
-// ((URL)parameters[0]).getProtocol().equalsIgnoreCase("https")
-// )){
-// File f = null;
-// System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
-// TLS.register("TLSv1");
-// try {
-// f = (File) enclosingMethod.invoke(thisObject, parameters);
-// } catch (IllegalAccessException e1) {
-// wrapException(e1);
-// } catch (InvocationTargetException e1) {
-// wrapException(e1);
-// }
-//
-// // System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", null);
-// TLS.register();
-//
-// if (f != null){
-// wrapException(e, null, new Mitigation() {
-// @Override
-// public String getReport() {
-// return "Trying TLSv1 and sun.security.ssl.allowUnsafeRenegotiation=true";
-// }
-// });
-// return f;
-// }
-// }
-
- if (
- e instanceof TSLSecurityException &&
- enclosingMethod.getDeclaringClass().equals(TSLContext.class) &&
- enclosingMethod.getName().equals("securityCheck") &&
- parameters[0] == TSLSecurityException.Type.UNTRUSTED_TSL_SIGNER &&
- trustAnchorsWrongOnEuTsl_.containsKey(expectedTerritory_) &&
- parameters[1] instanceof X509Certificate &&
- parameters[2] instanceof ListIterator<?>
- )
- {
- final ListIterator<X509Certificate> trustAnchorsWrongOnEuTsl =
- trustAnchorsWrongOnEuTsl_.get(expectedTerritory_);
-
- if (trustAnchorsWrongOnEuTsl != parameters[2]){ //prevents recursion
- try {
- enclosingMethod.invoke(thisObject,
- new Object[]{parameters[0],parameters[1], trustAnchorsWrongOnEuTsl});
- } catch (IllegalAccessException e1) {
- wrapException(e1);
- } catch (InvocationTargetException e1) {
- wrapException(e1);
- }
- wrapException(e, getLocator(),
- new iaik.xml.crypto.tsl.ex.SeverityAspect.Mitigation(){
- @Override
- public String getReport() {
- return "make an exception for " + expectedTerritory_ + " who have the wrong certificate in " +
- "the EU TSL and allow the certificate " +
- parameters[1];
- }
- });
- return null;
- }
- X509Certificate crt = (X509Certificate)parameters[1];
-
- File f = new File("./wrong/"+expectedTerritory_+"/",
- iaik.util.GeneralUtils15.toHexString(getFingerPrint(crt,
- new byte[TSLConstants.CertHash.LENGTH]))+".der");
- File parent = f.getParentFile();
- if(!parent.exists() && !parent.mkdirs()){
- throw new IllegalStateException("Couldn't create dir: " + parent);
- }
-
- if (!f.exists()){
- try {
- OutputStream os = new BufferedOutputStream(
- new FileOutputStream(f)
- );
- os.write(crt.getEncoded());
- os.close();
- } catch (Exception e1) {
- e1.printStackTrace();
- System.exit(1);
- }
- }
-
- //continue ...
- }
-
- if (
- ( expectedTerritory_ == Countries.SK ||
- expectedTerritory_ == Countries.SE ||
- expectedTerritory_ == Countries.NO ||
- expectedTerritory_ == Countries.PL) &&
- e instanceof KeySelectorException &&
- enclosingMethod.getDeclaringClass().equals(TslKeySelector.class) &&
- enclosingMethod.getName().equals("select") &&
- parameters[0] instanceof X509DataImpl){
-
- X509DataImpl x509Data = (X509DataImpl) parameters[0];
- AlgorithmMethod method = (AlgorithmMethod) parameters[2];
-
- List certificates = new ArrayList();
-
- Iterator x509content = x509Data.getContent().iterator();
- while (x509content.hasNext()) {
- Object element = x509content.next();
- if (element instanceof X509Certificate) {
- X509Certificate rawCert = (X509Certificate)element;
- certificates.add(rawCert);
- }
- }
-
- if (!certificates.isEmpty()) {
- X509Certificate[] rawCertificates = new X509Certificate[certificates.size()];
- certificates.toArray(rawCertificates);
- certificates.clear();
- Iterator certs = null;
- try {
- // convert the certificates to IAIK certifcates
- iaik.x509.X509Certificate[] iaikCertificates = Util.convertCertificateChain(rawCertificates);
- // sort the certificate chain
- iaik.x509.X509Certificate[] sortedChain = Util.arrangeCertificateChain(iaikCertificates, false);
- if (sortedChain == null) {
- // chain could not be sorted; maybe there are two different certificates
- // containing the same public key; use the unsorted chain
- certificates = Arrays.asList(iaikCertificates);
- certs = certificates.iterator();
- } else {
- certs = (Collections.nCopies(1, sortedChain[0])).iterator();
- certificates = Arrays.asList(sortedChain);
- }
- } catch (CertificateException e1) {
- //cannot handle this throw error
- return super.throwException(e, enclosingMethod, thisObject, parameters);
- }
-
- PublicKey oldPublicKey = null;
- while (certs.hasNext()) {
-
- iaik.x509.X509Certificate cert = (iaik.x509.X509Certificate)certs.next();
-
- boolean hit = false;
-
- PublicKey publicKey = cert.getPublicKey();
-
- // failReason_ = "";
-
- // Does the certificate provide a key for the requested algorithm?
- try {
- KeyFactory kfac = KeyFactory.getInstance(method.getAlgorithm());
- kfac.translateKey(publicKey);
- hit = true;
- if (oldPublicKey != null) {
- if (!publicKey.equals(oldPublicKey)) {
- //cannot handle this throw error
- return super.throwException(e, enclosingMethod, thisObject, parameters);
- }
- }
- oldPublicKey = publicKey;
- } catch (NoSuchAlgorithmException e1) {
- //cannot handle this throw error
- return super.throwException(e, enclosingMethod, thisObject, parameters);
- } catch (InvalidKeyException e1) {
- //cannot handle this throw error
- return super.throwException(e, enclosingMethod, thisObject, parameters);
- }
- if (hit) {
- //make an exception for SK, SE who violate XMLDSig ds:KeyInfo/ds:X509Data
- wrapException(e, getLocator(),
- new ExceptionalMitigation("make an exception for " + expectedTerritory_ + " who violate XMLDSig ds:KeyInfo"));
- return new X509KeySelectorResultImpl(publicKey, certificates, null);
- }
- }
- }
- }
-
- if ( expectedTerritory_ == Countries.DK &&
- e instanceof KeySelectorException &&
- parameters[0] instanceof X509DataImpl){
- if (e.getMessage().equals("KeyInfo X509SubjectName (CN=Adam Arndt Digst,serialNumber=CVR:34051178-RID:25902029,O=Digitaliseringsstyrelsen // CVR:34051178,C=DK) does not match SubjectDN (serialNumber=CVR:34051178-RID:25902029+CN=Adam Arndt Digst,O=Digitaliseringsstyrelsen // CVR:34051178,C=DK) of KeyInfo X509Certificate.\n"+
- "Any X509IssuerSerial, X509SKI, and X509SubjectName elements that appear MUST refer to the certificate or certificates containing the validation key.")) {
-
- X509DataImpl x509DataImpl = (X509DataImpl) parameters[0];
-
- ListIterator li = x509DataImpl.getContent().listIterator();
- li.next();
- String sn = (String) li.next();
-
- GeneralLog.err(sn, null);
-
- System.exit(1);
-
- Object mitigatedResult = null;
- try {
-
- mitigatedResult = enclosingMethod.invoke(thisObject, parameters);
- } catch (IllegalAccessException e1) {
- wrapException(e1);
- } catch (InvocationTargetException e1) {
- wrapException(e1);
- }
-
- if (mitigatedResult != null){
- wrapException(e, null, new iaik.xml.crypto.tsl.ex.SeverityAspect.Mitigation() {
- @Override
- public String getReport() {
- return "Deleted wrong X509SubjectName from XMLDSIG Signature.";
- }
- });
- return mitigatedResult;
-
- }
- }
- }
-
-
- } else {
- if (e instanceof MitigatedTSLSecurityException){
- // we allow to mitigate Security exceptions for testing
- // and collect them
- wrapException(e);
- return null;
- } else if (e instanceof FixedSaxLevelValidationExcption) {
- // we allow to mitigate Sax Level Fixup for testing
- // and collect them
- wrapException(e);
- return null;
- }
- }
-
- return super.throwException(e, enclosingMethod, thisObject, parameters);
- }
-
-
-
- @Override
- public Unmarshaller createTSLUnmarshaller()
- throws TSLEngineFatalException {
- if (expectedTerritory_ == Countries.FI){
- //we cannot fix FI at SAX Level and re-validate
- return TSLEngine.createTSLUnmarshaller(false);
- }
- return super.createTSLUnmarshaller();
- }
-
- @Override
- public String compressStatus(String status) {
- if(expectedTerritory_ == Countries.EL){
- //fix the whitespace in Greece TSL
- status = status.trim();
- }
- if (status != null && status.startsWith("http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/")) {
- status = status.substring("http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/".length());
- }
-
- return super.compressStatus(status);
- }
-
-
- @Override
- public String compressServiceType(String sType) {
- if(expectedTerritory_ == Countries.EL){
- //fix the whitespace in Greece TSL
- sType = sType.trim();
- }
- return super.compressServiceType(sType);
- }
-
-
- @Override
- public iaik.xml.crypto.tsl.ValidationFixupFilter.Fixup getSaxLevelValidationFixup(SAXParseException e) {
-
- if (expectedTerritory_ == Countries.AT){
- if (e.getMessage().equals("cvc-type.3.1.1: Element 'tsl:URI' is a simple type, so it cannot have attributes, excepting those whose namespace name is identical to 'http://www.w3.org/2001/XMLSchema-instance' and whose [local name] is one of 'type', 'nil', 'schemaLocation' or 'noNamespaceSchemaLocation'. However, the attribute, 'xml:lang' was found.")){
- return new DeleteAttrFixup("http://www.w3.org/XML/1998/namespace","lang", e, this);
- }
- }
-
- if (expectedTerritory_ == Countries.CZ){
- if (e.getMessage().equals("cvc-type.3.1.1: Element 'tsl:URI' is a simple type, so it cannot have attributes, excepting those whose namespace name is identical to 'http://www.w3.org/2001/XMLSchema-instance' and whose [local name] is one of 'type', 'nil', 'schemaLocation' or 'noNamespaceSchemaLocation'. However, the attribute, 'xml:lang' was found.")){
- return new DeleteAttrFixup("http://www.w3.org/XML/1998/namespace","lang", e, this);
- }
- }
-
- if (expectedTerritory_ == Countries.FR){
- if (e.getMessage().equals("cvc-type.3.1.1: Element 'tsl:URI' is a simple type, so it cannot have attributes, excepting those whose namespace name is identical to 'http://www.w3.org/2001/XMLSchema-instance' and whose [local name] is one of 'type', 'nil', 'schemaLocation' or 'noNamespaceSchemaLocation'. However, the attribute, 'xml:lang' was found.")){
- return new DeleteAttrFixup("http://www.w3.org/XML/1998/namespace","lang", e, this);
- }
- }
-
- if (expectedTerritory_ == Countries.NO){
- if (e.getMessage().equals("cvc-type.3.1.1: Element 'tsl:URI' is a simple type, so it cannot have attributes, excepting those whose namespace name is identical to 'http://www.w3.org/2001/XMLSchema-instance' and whose [local name] is one of 'type', 'nil', 'schemaLocation' or 'noNamespaceSchemaLocation'. However, the attribute, 'xml:lang' was found.")){
- return new DeleteAttrFixup("http://www.w3.org/XML/1998/namespace","lang", e, this);
- }
- }
-
- if (expectedTerritory_ == Countries.SK){
- if (e.getMessage().equals("cvc-type.3.1.1: Element 'tsl:URI' is a simple type, so it cannot have attributes, excepting those whose namespace name is identical to 'http://www.w3.org/2001/XMLSchema-instance' and whose [local name] is one of 'type', 'nil', 'schemaLocation' or 'noNamespaceSchemaLocation'. However, the attribute, 'xml:lang' was found.")){
- return new DeleteAttrFixup("http://www.w3.org/XML/1998/namespace","lang", e, this);
- }
- }
-
-
- if (expectedTerritory_ == Countries.ES && getDownloadLocation().toString().contains(".es/")){
- if (e.getMessage().equals("cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tslx:CertSubjectDNAttributeType'.")){
- return new LocalNameFixup("CertSubjectDNAttributeType","CertSubjectDNAttribute",e, this);
- }
- }
-
- if (expectedTerritory_ == Countries.MT && getDownloadLocation().toString().contains(".mt/")){
- if (e.getMessage().equals("cvc-complex-type.2.4.a: Invalid content was found starting with element 'tsl:TSLPolicy'. One of '{\"http://uri.etsi.org/02231/v2#\":TSLLegalNotice}' is expected.")){
- return new LocalNameFixup("TSLPolicy","TSLLegalNotice",e, this);
- }
- }
-
- if (e.getMessage().equals("cvc-complex-type.3.2.2: Attribute 'assert' is not allowed to appear in element 'ecc:otherCriteriaList'.")){
- return new LocalNameFixup("otherCriteriaList","CriteriaList",e, this);
- } else if (e.getMessage().startsWith("cvc-datatype-valid.1.2.1: '") && e.getMessage().endsWith("' is not a valid value for 'dateTime'.")){
- return new ElementStringValueFixup("-(.)-","-0$1-",e, this);
- } else if (e.getMessage().startsWith("cvc-type.3.1.3: The value '") && e.getMessage().endsWith("' of element 'tsl:ListIssueDateTime' is not valid.")){
- // return new DateTimeFixup();
- } else if (e.getMessage().startsWith("cvc-datatype-valid.1.2.1: '") && e.getMessage().endsWith("' is not a valid value for 'base64Binary'.")){
- return new ElementStringValueFixup("(\\s)=([^=]+)","$1$2",e, this);
- } else if (e.getMessage().startsWith("cvc-type.3.1.3: The value '") && e.getMessage().endsWith("' of element 'tsl:X509Certificate' is not valid.")){
- // return new Base64BinaryFixup();
- } else if (e.getMessage().startsWith("cvc-datatype-valid.1.2.1: '") && e.getMessage().endsWith("' is not a valid value for 'anyURI'.")){
-
- //TODO only for sweden and find a better discriminatory than the URI
-// if (expectedTerritory_ == Countries.SE){
-// return new ElementStringValueFixup(
-// "-http://www.pts.se/upload/Ovrigt/Internet/Branschinformation/Trusted%20List%20SE%20MR.xml",
-// "http://www.pts.se/upload/Ovrigt/Internet/Branschinformation/Trusted%20List%20SE%20MR.xml");
- return new ElementStringValueFixup("-http://www.pts.se/", "http://www.pts.se/", e, this);
-// }
-
-
- } else if (e.getMessage().startsWith("cvc-datatype-valid.1.2.1: '") && e.getMessage().endsWith("' is not a valid value for 'NCName'.")){
- if (expectedTerritory_ == Countries.CY || expectedTerritory_ == Countries.LV ||
- expectedTerritory_ == Countries.HR || expectedTerritory_ == Countries.NL){
- return new AttributeValueFixup("","Id","(.+)","x$1",e, this);
- }
- } else if (e.getMessage().startsWith("cvc-complex-type.2.3: Element '") && e.getMessage().endsWith("' cannot have character [children], because the type's content type is element-only.")) {
- //cvc-complex-type.2.3: Element 'tsl:ServiceDigitalIdentity' cannot have character [children], because the type's content type is element-only.
- if (expectedTerritory_ == Countries.FI){
-// return new ElementStringValueFixup("(\\s*)-(\\s*)","$1$2",e, this);
- return new Fixup(e, this){
- {
- changed_ = true;
- fixupPerformed();
- }
- @Override
- public String fixup(String input) {
- return null;
- }
-
- @Override
- public Mitigation getMitigation() {
- return new Mitigation("Ignored");
- }
-
- };
- }
- }
-
- if (e.getMessage().startsWith("cvc-elt")){
-
- } else if (e.getMessage().startsWith("cvc-type")) {
-
- } else if (e.getMessage().startsWith("cvc-complex-type")) {
-
- } else if (e.getMessage().startsWith("cvc-datatype-valid")) {
-
- } else if (e.getMessage().startsWith("cvc-attribute")) {
-
- }
- //cvc-complex-type.2.4.a: Invalid content was found starting with element 'tsl:TSLPolicy'. One of '{"http://uri.etsi.org/02231/v2#":TSLLegalNotice}' is expected.
-
- //cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'ecc:PolicySet'
- //cvc-complex-type.2.4.a: Invalid content was found starting with element 'ecc:Identifier'. One of '{"http://uri.etsi.org/02231/v2/additionaltypes#":AttributeOID}' is expected.
- //cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tsl:ExtensionOID'.
- //cvc-type.3.1.3: The value '-http://www.pts.se/upload/Ovrigt/Internet/Branschinformation/Trusted%20List%20SE%20MR.xml' of element 'tsl:URI' is not valid.,locator=[node=null,object=null,url=file:/C:/Gesichert/Development/projects/TSL/./hashcache/900BA6AB3702EC9518627496749AA28129C56100.tsl.xml,line=109,col=118,offset=-1]]
-
- return super.getSaxLevelValidationFixup(e);
- }
-
- @Override
- public void securityCheck(Type securityCheckType,
- java.security.cert.X509Certificate[] certs,
- ListIterator<java.security.cert.X509Certificate> expectedTslSignerCerts) {
-
- //TODO check whether we always want to do that to make sure we use the endentity
- try {
- certs = Util.convertCertificateChain(certs);
- } catch (CertificateException e) {
- throwException(e);
- }
- certs = Util.arrangeCertificateChain((iaik.x509.X509Certificate[]) certs, false);
- super.securityCheck(securityCheckType, certs, expectedTslSignerCerts);
- }
-
-
- @Override
- public boolean doRollback() {
- //accept each and every TSL ... even partially ... for testing
- return false;
-// return true;
- }
-
- @Override
- public Boolean doesViolateRawHash(SQLException e, byte[] rawHash) {
-
- String msg = e.getMessage();
-
- GeneralLog.info(msg);
- return(
- msg.startsWith("["+SQLiteErrorCode.SQLITE_CONSTRAINT.name()+"]") &&
- msg.contains("column " + DbTables.TSLDownload.C.rawHash + " is not unique")
- );
- }
-
- @Override
- protected File getLocalLastModified(File targetFile) {
- return super.getLocalLastModified(targetFile);
- }
- @Override
- protected long howLongWaitForThreads() {
- // TODO Auto-generated method stub
- return 100000;
- }
-
- @Override
- protected boolean normalizeXML() {
- return true;
- }
- public MultiThreadLoggingGroup getLoggingGroup() {
- return this;
- }
-
- StringBuilder log = new StringBuilder();
-
- public void flushLog() {
- if (log != null && log.length() > 0) {
- Thread currentThread = Thread.currentThread();
- String ncName = getNcName(currentThread);
- synchronized (log) {
- parentContext_.print("<" + ncName + " state=\"" + currentThread.getState()
- + "\" " + " id=\"" + currentThread.getId() + "\">\n" + log.toString() + "</"
- + ncName + ">" + GeneralUtils15.LB);
- parentContext_.flushLog();
- log.setLength(0);
- }
- }
- }
-
- /**
- * Collect all the logs for this context
- * @see iaik.util.logging.Log.MultiThreadLoggingGroup#print(java.lang.Object)
- */
- public void print(Object msg) {
- synchronized (log) {
- log.append(msg);
- }
- }
- @Override
- public FileFilter getCertificateFileFilter() {
- return null;
- }
-
-}
\ No newline at end of file diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertificateUtils.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertificateUtils.java index 358524d..0ea0677 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertificateUtils.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertificateUtils.java @@ -12,12 +12,19 @@ import iaik.x509.extensions.qualified.QCStatements; import iaik.x509.extensions.qualified.structures.QCStatement; import iaik.x509.extensions.qualified.structures.etsi.QcEuCompliance; import iaik.x509.extensions.qualified.structures.etsi.QcEuSSCD; -import iaik.xml.crypto.tsl.ex.TSLEngineDiedException; -import iaik.xml.crypto.tsl.ex.TSLSearchException; +import java.net.URI; import java.security.Principal; +import java.util.Arrays; +import java.util.Date; +import java.util.List; -import at.gv.egovernment.moa.spss.tsl.timer.TSLUpdaterTimerTask; +import at.gv.egovernment.moa.sig.tsl.engine.data.ITslEndEntityResult; +import at.gv.egovernment.moa.sig.tsl.exception.TslException; +import at.gv.egovernment.moa.spss.api.common.TslInfos; +import at.gv.egovernment.moa.spss.api.impl.TslInfosImpl; +import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; +import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; @@ -169,100 +176,142 @@ public class CertificateUtils { } - public static QCSSCDResult checkQCSSCD(X509Certificate[] chain, boolean isTSLenabledTrustprofile) { - - boolean qc = false; - boolean qcSourceTSL = false; - boolean sscd = false; - boolean sscdSourceTSL = false; - + public static QCSSCDResult checkQCSSCD(X509Certificate[] chain, Date signingTime, boolean isTSLenabledTrustprofile, ConfigurationProvider config) { + try { - if (isTSLenabledTrustprofile) { - // perform QC check via TSL - boolean checkQCFromTSL = TSLUpdaterTimerTask.tslconnector_.checkQC(chain); - if (!checkQCFromTSL) { - // if QC check via TSL returns false - // try certificate extensions QCP and QcEuCompliance - Logger.debug("QC check via TSL returned false - checking certificate extensions"); - boolean checkQCP = CertificateUtils.checkQCP(chain[0]); - boolean checkQcEuCompliance = CertificateUtils.checkQcEuCompliance(chain[0]); - - if (checkQCP || checkQcEuCompliance) { - Logger.debug("Certificate is QC (Source: Certificate)"); - qc = true; - } - - qcSourceTSL = false; - } - else { - // use TSL result - Logger.debug("Certificate is QC (Source: TSL)"); - qc = true; - qcSourceTSL = true; - } + if (signingTime == null) { + signingTime = new Date(); + Logger.debug("TSL check without signingTime --> use current time for evaluation"); + + } - // perform SSCD check via TSL - boolean checkSSCDFromTSL = TSLUpdaterTimerTask.tslconnector_.checkSSCD(chain); - if (!checkSSCDFromTSL) { - // if SSCD check via TSL returns false - // try certificate extensions QCP+ and QcEuSSCD - Logger.debug("SSCD check via TSL returned false - checking certificate extensions"); - boolean checkQCPPlus = CertificateUtils.checkQCPPlus(chain[0]); - boolean checkQcEuSSCD = CertificateUtils.checkQcEuSSCD(chain[0]); - - if (checkQCPPlus || checkQcEuSSCD) { - Logger.debug("Certificate is SSCD (Source: Certificate)"); - sscd = true; - } - - sscdSourceTSL = false; - } - else { - // use TSL result - Logger.debug("Certificate is SSCD (Source: TSL)"); - sscd = true; - sscdSourceTSL = true; - } - - } - else { - // Trustprofile is not TSL enabled - use certificate extensions only - - // perform QC check - // try certificate extensions QCP and QcEuCompliance - boolean checkQCP = CertificateUtils.checkQCP(chain[0]); - boolean checkQcEuCompliance = CertificateUtils.checkQcEuCompliance(chain[0]); - - if (checkQCP || checkQcEuCompliance) - qc = true; - - qcSourceTSL = false; - - // perform SSCD check - // try certificate extensions QCP+ and QcEuSSCD - boolean checkQCPPlus = CertificateUtils.checkQCPPlus(chain[0]); - boolean checkQcEuSSCD = CertificateUtils.checkQcEuSSCD(chain[0]); - - if (checkQCPPlus || checkQcEuSSCD) - sscd = true; - - sscdSourceTSL = false; - } + ITslEndEntityResult tslCheckResult = TSLServiceFactory.getTSLServiceClient().evaluate(Arrays.asList(chain), signingTime); + + if (tslCheckResult != null) { + URI tslServiceTypeIdentifier = tslCheckResult.getEvaluatedServiceTypeIdentifier(); + List<URI> tslCertificateQualifier = tslCheckResult.getEvaluatedQualifier(); + + boolean qc = false; + boolean qcSourceTSL = false; + boolean sscd = false; + boolean sscdSourceTSL = false; + + //check QC + List<URI> allowedQCQualifier = config.getTSLConfiguration().getQualifierForQC(); + for (URI el : allowedQCQualifier) { + if (el.equals(tslServiceTypeIdentifier)) { + qcSourceTSL = true; + qc = true; + + } + + } + if (qcSourceTSL) + Logger.debug("Certificate is QC (Source: TSL)"); + + else { + // if QC check via TSL returns false + // try certificate extensions QCP and QcEuCompliance + Logger.debug("QC check via TSL returned false - checking certificate extensions"); + boolean checkQCP = CertificateUtils.checkQCP(chain[0]); + boolean checkQcEuCompliance = CertificateUtils.checkQcEuCompliance(chain[0]); + + if (checkQCP || checkQcEuCompliance) { + Logger.debug("Certificate is QC (Source: Certificate)"); + qc = true; + + } + + } + + + //check SSCD + List<URI> allowedSSCDQualifier = config.getTSLConfiguration().getQualifierForSSCD(); + for (URI allowedSSCD : allowedSSCDQualifier) { + for (URI certSSCD : tslCertificateQualifier) { + if (allowedSSCD.equals(certSSCD)) { + sscdSourceTSL = true; + sscd = true; + + } + } + + } + if (sscdSourceTSL) + Logger.debug("Certificate is SSCD (Source: TSL)"); + + else { + // if SSCD check via TSL returns false + // try certificate extensions QCP+ and QcEuSSCD + Logger.debug("SSCD check via TSL returned false - checking certificate extensions"); + boolean checkQCPPlus = CertificateUtils.checkQCPPlus(chain[0]); + boolean checkQcEuSSCD = CertificateUtils.checkQcEuSSCD(chain[0]); + + if (checkQCPPlus || checkQcEuSSCD) { + Logger.debug("Certificate is SSCD (Source: Certificate)"); + sscd = true; + } + } + + //build basic result + QCSSCDResult result = new QCSSCDResult(qc, qcSourceTSL, sscd, sscdSourceTSL); + + //add additinal information + TslInfos extTslInfos = new TslInfosImpl( + tslCheckResult.getTerritory(), + tslCheckResult.getTspStatus(), + tslServiceTypeIdentifier.toString(), + tslCertificateQualifier); + result.setTslInfos(extTslInfos); + + return result; + + } else { + Logger.debug("Qualifier check via TSL return null - checking certificate extensions"); + return parseInfosFromCertificate(chain); + + } + + } else + return parseInfosFromCertificate(chain); } - catch (TSLEngineDiedException e) { - MessageProvider msg = MessageProvider.getInstance(); - Logger.error(new LogMsg(msg.getMessage("tsl.01", null)), e); - } catch (TSLSearchException e) { + catch (TslException e) { MessageProvider msg = MessageProvider.getInstance(); Logger.error(new LogMsg(msg.getMessage("tsl.01", null)), e); + + return new QCSSCDResult(); } - QCSSCDResult result = new QCSSCDResult(qc, qcSourceTSL, sscd, sscdSourceTSL); + } + + private static QCSSCDResult parseInfosFromCertificate(X509Certificate[] chain) { + boolean qc = false; + boolean sscd = false; + + // Trustprofile is not TSL enabled - use certificate extensions only + + // perform QC check + // try certificate extensions QCP and QcEuCompliance + boolean checkQCP = CertificateUtils.checkQCP(chain[0]); + boolean checkQcEuCompliance = CertificateUtils.checkQcEuCompliance(chain[0]); + + if (checkQCP || checkQcEuCompliance) + qc = true; + + // perform SSCD check + // try certificate extensions QCP+ and QcEuSSCD + boolean checkQCPPlus = CertificateUtils.checkQCPPlus(chain[0]); + boolean checkQcEuSSCD = CertificateUtils.checkQcEuSSCD(chain[0]); + + if (checkQCPPlus || checkQcEuSSCD) + sscd = true; + + return new QCSSCDResult(qc, false, sscd, false); - return result; } + /** * Gets the country from the certificate issuer * @param cert X509 certificate diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/QCSSCDResult.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/QCSSCDResult.java index 99af843..c00225d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/QCSSCDResult.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/QCSSCDResult.java @@ -1,5 +1,7 @@ package at.gv.egovernment.moa.spss.util; +import at.gv.egovernment.moa.spss.api.common.TslInfos; + public class QCSSCDResult { private boolean qc; @@ -8,6 +10,10 @@ public class QCSSCDResult { private boolean sscd; private boolean sscdSourceTSL; + private TslInfos tslInfos; + + + public QCSSCDResult() { this.qc = false; this.qcSourceTSL = false; @@ -34,4 +40,14 @@ public class QCSSCDResult { public boolean isSSCDSourceTSL() { return this.sscdSourceTSL; } + + public TslInfos getTslInfos() { + return tslInfos; + } + + public void setTslInfos(TslInfos tslInfos) { + this.tslInfos = tslInfos; + } + + } |