From 32d17447a258188b2d534bcb0bf65a659ba7b7d0 Mon Sep 17 00:00:00 2001 From: mcentner Date: Fri, 29 Aug 2008 12:11:34 +0000 Subject: Initial import. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@1 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../impl/CreateXMLSignatureCommandImpl.java | 229 +++++ .../impl/CreateXMLSignatureResultImpl.java | 138 +++ .../egiz/bku/slcommands/impl/ErrorResultImpl.java | 60 ++ .../slcommands/impl/InfoboxReadCommandImpl.java | 409 ++++++++ .../bku/slcommands/impl/InfoboxReadResultImpl.java | 171 ++++ .../slcommands/impl/NullOperationCommandImpl.java | 43 + .../slcommands/impl/NullOperationResultImpl.java | 47 + .../gv/egiz/bku/slcommands/impl/SLCommandImpl.java | 162 ++++ .../gv/egiz/bku/slcommands/impl/SLResultImpl.java | 117 +++ .../impl/xsect/AlgorithmMethodFactory.java | 79 ++ .../impl/xsect/AlgorithmMethodFactoryImpl.java | 125 +++ .../impl/xsect/ByteArrayDereferencer.java | 65 ++ .../egiz/bku/slcommands/impl/xsect/DataObject.java | 1006 ++++++++++++++++++++ .../bku/slcommands/impl/xsect/IdValueFactory.java | 37 + .../slcommands/impl/xsect/IdValueFactoryImpl.java | 127 +++ .../slcommands/impl/xsect/LocRefDereferencer.java | 113 +++ .../bku/slcommands/impl/xsect/STALPrivateKey.java | 122 +++ .../bku/slcommands/impl/xsect/STALProvider.java | 64 ++ .../bku/slcommands/impl/xsect/STALSignature.java | 165 ++++ .../impl/xsect/STALSignatureException.java | 92 ++ .../egiz/bku/slcommands/impl/xsect/Signature.java | 935 ++++++++++++++++++ .../slcommands/impl/xsect/SignatureContext.java | 129 +++ .../slcommands/impl/xsect/SignatureLocation.java | 235 +++++ .../impl/xsect/SimpleDOMErrorHandler.java | 98 ++ .../impl/xsect/URIDereferncerAdapter.java | 103 ++ .../bku/slcommands/impl/xsect/XSECTReference.java | 112 +++ .../bku/slcommands/impl/xsect/XSECTTransforms.java | 124 +++ 27 files changed, 5107 insertions(+) create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationCommandImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLCommandImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactory.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/ByteArrayDereferencer.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/IdValueFactory.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/IdValueFactoryImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureException.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureContext.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureLocation.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SimpleDOMErrorHandler.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/URIDereferncerAdapter.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/XSECTReference.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/XSECTTransforms.java (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java new file mode 100644 index 00000000..136fa6f3 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java @@ -0,0 +1,229 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import java.io.ByteArrayInputStream; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Collections; +import java.util.Date; + +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.URIReferenceException; +import javax.xml.crypto.dsig.XMLSignatureException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSSerializer; + +import at.buergerkarte.namespaces.securitylayer._1.CreateXMLSignatureRequestType; +import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; +import at.gv.egiz.bku.slcommands.CreateXMLSignatureCommand; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slcommands.SLResult; +import at.gv.egiz.bku.slcommands.impl.xsect.AlgorithmMethodFactory; +import at.gv.egiz.bku.slcommands.impl.xsect.AlgorithmMethodFactoryImpl; +import at.gv.egiz.bku.slcommands.impl.xsect.IdValueFactory; +import at.gv.egiz.bku.slcommands.impl.xsect.IdValueFactoryImpl; +import at.gv.egiz.bku.slcommands.impl.xsect.Signature; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLRequestException; +import at.gv.egiz.dom.DOMUtils; +import at.gv.egiz.stal.InfoboxReadRequest; +import at.gv.egiz.stal.InfoboxReadResponse; +import at.gv.egiz.stal.STALRequest; +import at.gv.egiz.stal.STALResponse; + +/** + * This class implements the security layer command CreateXMLSignatureRequest. + * + * @author mcentner + */ +public class CreateXMLSignatureCommandImpl extends SLCommandImpl implements + CreateXMLSignatureCommand { + + /** + * Logging facility. + */ + protected static Log log = LogFactory.getLog(CreateXMLSignatureCommandImpl.class); + + /** + * The signing certificate. + */ + protected X509Certificate signingCertificate; + + /** + * The keybox identifier of the key used for signing. + */ + protected String keyboxIdentifier; + + /** + * The to-be signed signature. + */ + protected Signature signature; + + @Override + public void init(SLCommandContext ctx, Object unmarshalledRequest) + throws SLCommandException { + super.init(ctx, unmarshalledRequest); + } + + @Override + public void prepareXMLSignature() throws SLCommandException, SLRequestException { + + CreateXMLSignatureRequestType request = getRequestValue(); + + // TODO: make configurable? + IdValueFactory idValueFactory = new IdValueFactoryImpl(); + + // TODO: make configurable? + AlgorithmMethodFactory algorithmMethodFactory; + try { + algorithmMethodFactory = new AlgorithmMethodFactoryImpl(signingCertificate); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } + + signature = new Signature(getCmdCtx().getURLDereferencerContext(), idValueFactory, algorithmMethodFactory); + + // SigningTime + signature.setSigningTime(new Date()); + + // SigningCertificate + signature.setSignerCeritifcate(signingCertificate); + + // SignatureInfo + if (request.getSignatureInfo() != null) { + signature.setSignatureInfo(request.getSignatureInfo()); + } + + // DataObjects + for (DataObjectInfoType dataObjectInfo : request.getDataObjectInfo()) { + signature.addDataObject(dataObjectInfo); + } + + signature.buildXMLSignature(); + + } + + /** + * Gets the signing certificate from STAL. + * + * @throws SLCommandException + * if getting the singing certificate fails + */ + private void getSigningCertificate() throws SLCommandException { + + CreateXMLSignatureRequestType request = getRequestValue(); + keyboxIdentifier = request.getKeyboxIdentifier(); + + InfoboxReadRequest stalRequest = new InfoboxReadRequest(); + stalRequest.setInfoboxIdentifier(keyboxIdentifier); + + requestSTAL(Collections.singletonList((STALRequest) stalRequest)); + + STALResponse stalResponse = stalResponses.next(); + + if (stalResponse instanceof InfoboxReadResponse) { + byte[] infobox = ((InfoboxReadResponse) stalResponse).getInfoboxValue(); + + try { + CertificateFactory certFactory = CertificateFactory.getInstance("X509"); + signingCertificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(infobox)); + } catch (CertificateException e) { + log.info("Failed to decode signing certificate.", e); + // TODO: issue appropriate error + throw new SLCommandException(4000); + } + + } else { + log.info("Failed to get signing certificate."); + // TODO: issue appropriate error + throw new SLCommandException(4000); + } + + } + + /** + * Signs the signature. + * + * @throws SLCommandException + * if signing the signature fails + */ + private void signXMLSignature() throws SLCommandException { + + try { + signature.sign(getCmdCtx().getSTAL(), keyboxIdentifier); + } catch (MarshalException e) { + log.error("Failed to marshall XMLSignature.", e); + throw new SLCommandException(4000); + } catch (XMLSignatureException e) { + if (e.getCause() instanceof URIReferenceException) { + URIReferenceException uriReferenceException = (URIReferenceException) e.getCause(); + if (uriReferenceException.getCause() instanceof SLCommandException) { + throw (SLCommandException) uriReferenceException.getCause(); + } + } + log.error("Failed to sign XMLSignature.", e); + throw new SLCommandException(4000); + } + + } + + @Override + public SLResult execute() { + try { + + // get certificate in order to select appropriate algorithms for hashing and signing + getSigningCertificate(); + + // prepare the XMLSignature for signing + prepareXMLSignature(); + + // sign the XMLSignature + signXMLSignature(); + + if (log.isTraceEnabled()) { + + DOMImplementationLS domImplLS = DOMUtils.getDOMImplementationLS(); + LSSerializer serializer = domImplLS.createLSSerializer(); + String debugString = serializer.writeToString(signature.getDocument()); + + log.trace(debugString); + + } + + return new CreateXMLSignatureResultImpl(signature.getDocument()); + + } catch (SLCommandException e) { + return new ErrorResultImpl(e); + } catch (SLRequestException e) { + return new ErrorResultImpl(e); + } + } + + @Override + public String getName() { + return "CreateXMLSignatureRequest"; + } + + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java new file mode 100644 index 00000000..d2d2e678 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java @@ -0,0 +1,138 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.transform.Result; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import at.buergerkarte.namespaces.securitylayer._1.CreateXMLSignatureResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.gv.egiz.bku.slcommands.SLCommandFactory; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; + +/** + * This calls implements the result of the security layer command CreateXMLSignature. + * + * @author mcentner + */ +public class CreateXMLSignatureResultImpl extends SLResultImpl { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(CreateXMLSignatureResultImpl.class); + + /** + * The document containing the XMLSignature. + */ + protected Document doc; + + /** + * Creates a new instance of this CreateXMLSignatureResultImpl with the given + * signature document. + * + * @param document the signature document + * + * @throws NullPointerException if document is null + */ + public CreateXMLSignatureResultImpl(Document document) { + super(); + + if (document == null) { + throw new NullPointerException("Argument 'document' must not be null."); + } + + this.doc = document; + + marshallCreateXMLSignatureResponse(); + } + + /** + * Marshalls the CreateXMLSignatureResponse. + */ + private void marshallCreateXMLSignatureResponse() { + + ObjectFactory factory = new ObjectFactory(); + + CreateXMLSignatureResponseType createCreateXMLSignatureResponseType = factory.createCreateXMLSignatureResponseType(); + JAXBElement createCreateXMLSignatureResponse = factory.createCreateXMLSignatureResponse(createCreateXMLSignatureResponseType); + + DocumentFragment fragment = doc.createDocumentFragment(); + + JAXBContext jaxbContext = SLCommandFactory.getJaxbContext(); + try { + Marshaller marshaller = jaxbContext.createMarshaller(); + marshaller.marshal(createCreateXMLSignatureResponse, fragment); + } catch (JAXBException e) { + log.error("Failed to marshall 'CreateXMLSignatureResponse'", e); + throw new SLRuntimeException(e); + } + + Node child = fragment.getFirstChild(); + if (child instanceof Element) { + Node node = doc.replaceChild(child, doc.getDocumentElement()); + child.appendChild(node); + } + + } + + @Override + public void writeTo(Result result) { + + try { + writeTo(result, null); + } catch (TransformerException e) { + log.error(e); + } + + } + + /* (non-Javadoc) + * @see at.gv.egiz.bku.slcommands.impl.SLResultImpl#writeTo(javax.xml.transform.Result, javax.xml.transform.Transformer) + */ + @Override + public void writeTo(Result result, Transformer transformer) throws TransformerException { + + if (transformer == null) { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + try { + transformer = transformerFactory.newTransformer(); + } catch (TransformerConfigurationException e) { + log.error("Failed to create Transformer.", e); + throw new SLRuntimeException(e); + } + } + transformer.transform(new DOMSource(doc), result); + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java new file mode 100644 index 00000000..555f83bd --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java @@ -0,0 +1,60 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import at.buergerkarte.namespaces.securitylayer._1.ErrorResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.gv.egiz.bku.slcommands.ErrorResult; +import at.gv.egiz.bku.slexceptions.SLException; + +import javax.xml.transform.Result; + +/** + * This class implements the security layer result ErrorResponse. + * + * @author mcentner + */ +public class ErrorResultImpl extends SLResultImpl implements ErrorResult { + + /** + * The exception containing information provided in the ErrorResponse. + */ + protected SLException slException; + + /** + * Creates a new instance of this ErrorResultImpl with the given + * slException containing information provided in the + * ErrorResponse. + * + * @param slException the exception + */ + public ErrorResultImpl(SLException slException) { + this.slException = slException; + } + + @Override + public void writeTo(Result result) { + + ObjectFactory factory = new ObjectFactory(); + ErrorResponseType responseType = factory.createErrorResponseType(); + responseType.setErrorCode(slException.getErrorCode()); + responseType.setInfo(slException.getDetailedMsg()); + + writeTo(factory.createErrorResponse(responseType), result); + + } +} \ No newline at end of file diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java new file mode 100644 index 00000000..93131cf4 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java @@ -0,0 +1,409 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import iaik.asn1.CodingException; +import iaik.asn1.DerCoder; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Result; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import at.buergerkarte.namespaces.personenbindung._20020506_.CompressedIdentityLinkType; +import at.buergerkarte.namespaces.securitylayer._1.AnyChildrenType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsBinaryFileType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; +import at.gv.egiz.bku.slcommands.InfoboxReadCommand; +import at.gv.egiz.bku.slcommands.SLCommand; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slcommands.SLResult; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLExceptionMessages; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import at.gv.egiz.idlink.CompressedIdentityLinkFactory; +import at.gv.egiz.idlink.IdentityLinkTransformer; +import at.gv.egiz.idlink.ans1.IdentityLink; +import at.gv.egiz.stal.InfoboxReadRequest; +import at.gv.egiz.stal.InfoboxReadResponse; +import at.gv.egiz.stal.STALRequest; + +/** + * This class implements the security layer command + * InfoboxReadRequest. + *

+ * NOTE: Currently the only supported infobox identifier is ' + * IdentityLink'. + *

+ * + * @author mcentner + */ +public class InfoboxReadCommandImpl extends SLCommandImpl implements + InfoboxReadCommand { + + /** + * Logging facility. + */ + protected static Log log = LogFactory.getLog(InfoboxReadCommandImpl.class); + + public static final String INFOBOX_IDENTIFIER_CERTIFICATES = "Certificates"; + + public static final String BOX_SPECIFIC_PARAMETER_IDENTITY_LINK_DOMAIN_IDENTIFIER = "IdentityLinkDomainIdentifier"; + + public static final String INFOBOX_IDENTIFIER_IDENTITY_LINK = "IdentityLink"; + + /** + * The InfoboxIdentifier + */ + protected String infoboxIdentifier; + + /** + * The IdentityLinkDomainIdentifier value of an IdentyLink infobox. + */ + protected String identityLinkDomainIdentifier; + + /** + * Is content XML entity? + */ + protected boolean isXMLEntity; + + @Override + public String getName() { + return "InfoboxReadRequest"; + } + + /** + * @return the infoboxIdentifier + */ + public String getInfoboxIdentifier() { + return infoboxIdentifier; + } + + @Override + public void init(SLCommandContext ctx, Object request) throws SLCommandException { + super.init(ctx, request); + + InfoboxReadRequestType req = getRequestValue(); + + infoboxIdentifier = req.getInfoboxIdentifier(); + + InfoboxReadParamsBinaryFileType binaryFileParameters = req.getBinaryFileParameters(); + if (binaryFileParameters != null) { + isXMLEntity = binaryFileParameters.isContentIsXMLEntity(); + log.debug("Got ContentIsXMLEntity=" + isXMLEntity + "."); + } + + if (INFOBOX_IDENTIFIER_IDENTITY_LINK.equals(infoboxIdentifier)) { + + if (req.getAssocArrayParameters() != null) { + log.info("Got AssocArrayParameters but Infobox type is BinaryFile."); + throw new SLCommandException(4010); + } + + + AnyChildrenType boxSpecificParameters = req.getBoxSpecificParameters(); + + if (boxSpecificParameters != null) { + // check BoxSpecificParameters + List parameter = boxSpecificParameters.getAny(); + JAXBElement element; + if (parameter != null + && parameter.size() == 1 + && parameter.get(0) instanceof JAXBElement + && SLCommand.NAMESPACE_URI.equals((element = (JAXBElement) parameter.get(0)).getName().getNamespaceURI()) + && BOX_SPECIFIC_PARAMETER_IDENTITY_LINK_DOMAIN_IDENTIFIER.equals(element.getName().getLocalPart()) + && element.getValue() instanceof String) { + identityLinkDomainIdentifier = (String) element.getValue(); + log.debug("Got sl:IdentityLinkDomainIdentifier: " + identityLinkDomainIdentifier); + } else { + log.info("Got invalid BoxSpecificParameters."); + throw new SLCommandException(4010); + } + } + + } else { + throw new SLCommandException(4002, + SLExceptionMessages.EC4002_INFOBOX_UNKNOWN, + new Object[] { infoboxIdentifier }); + } + + } + + @Override + public SLResult execute() { + try { + return readIdentityLink(); + } catch (SLCommandException e) { + return new ErrorResultImpl(e); + } + } + + /** + * Gets the IdentitiyLink form the next STAL response. + * + * @return the IdentityLink + * + * @throws SLCommandException if getting the IdentitiyLink fails + */ + private IdentityLink getIdentityLinkFromResponses() throws SLCommandException { + + // IdentityLink + InfoboxReadResponse response; + if (hasNextResponse()) { + response = (InfoboxReadResponse) nextResponse(InfoboxReadResponse.class); + byte[] idLink = response.getInfoboxValue(); + try { + return new IdentityLink(DerCoder.decode(idLink)); + } catch (CodingException e) { + log.info("Failed to decode infobox '" + INFOBOX_IDENTIFIER_IDENTITY_LINK + "'.", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, + new Object[] { INFOBOX_IDENTIFIER_IDENTITY_LINK }); + } + } else { + log.info("No infobox '" + INFOBOX_IDENTIFIER_IDENTITY_LINK + "' returned from STAL."); + throw new SLCommandException(4000); + } + + } + + /** + * Gets the list of certificates from the next STAL responses. + * + * @return the list of certificates + * + * @throws SLCommandException if getting the list of certificates fails + */ + private List getCertificatesFromResponses() throws SLCommandException { + + List certificates = new ArrayList(); + + CertificateFactory certFactory; + try { + certFactory = CertificateFactory.getInstance("X509"); + } catch (CertificateException e) { + // we should always be able to get an X509 certificate factory + log.error("CertificateFactory.getInstance(\"X509\") failed.", e); + throw new SLRuntimeException(e); + } + + InfoboxReadResponse response; + while(hasNextResponse()) { + response = (InfoboxReadResponse) nextResponse(InfoboxReadResponse.class); + byte[] cert = response.getInfoboxValue(); + try { + certificates.add((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(cert))); + } catch (CertificateException e) { + log.info("Failed to decode certificate.", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, + new Object[] { INFOBOX_IDENTIFIER_CERTIFICATES }); + } + } + + return certificates; + + } + + /** + * Uses STAL to read the IdentityLink. + * + * @return the corresponding security layer result + * + * @throws SLCommandException if reading the IdentityLink fails + */ + private SLResult readIdentityLink() throws SLCommandException { + + List stalRequests = new ArrayList(); + + InfoboxReadRequest infoboxReadRequest; + // get raw identity link + infoboxReadRequest = new InfoboxReadRequest(); + infoboxReadRequest.setInfoboxIdentifier(INFOBOX_IDENTIFIER_IDENTITY_LINK); + infoboxReadRequest.setDomainIdentifier(identityLinkDomainIdentifier); + stalRequests.add(infoboxReadRequest); + + // get certificates + infoboxReadRequest = new InfoboxReadRequest(); + infoboxReadRequest.setInfoboxIdentifier("SecureSignatureKeypair"); + stalRequests.add(infoboxReadRequest); + + infoboxReadRequest = new InfoboxReadRequest(); + infoboxReadRequest.setInfoboxIdentifier("CertifiedKeypair"); + stalRequests.add(infoboxReadRequest); + + requestSTAL(stalRequests); + + IdentityLink identityLink = getIdentityLinkFromResponses(); + List certificates = getCertificatesFromResponses(); + + + CompressedIdentityLinkFactory idLinkFactory = CompressedIdentityLinkFactory.getInstance(); + JAXBElement compressedIdentityLink = idLinkFactory + .createCompressedIdentityLink(identityLink, certificates, identityLinkDomainIdentifier); + + IdentityLinkTransformer identityLinkTransformer = IdentityLinkTransformer.getInstance(); + String issuerTemplate = identityLink.getIssuerTemplate(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db; + try { + db = dbf.newDocumentBuilder(); + } catch (ParserConfigurationException e) { + log.error("Failed to create XML document.", e); + throw new SLRuntimeException(e); + } + + Document document = db.newDocument(); + try { + idLinkFactory.marshallCompressedIdentityLink(compressedIdentityLink, document, null, true); + } catch (JAXBException e) { + log.info("Failed to marshall CompressedIdentityLink.", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, + new Object[] { INFOBOX_IDENTIFIER_IDENTITY_LINK }); + } + + InfoboxReadResultImpl result = new InfoboxReadResultImpl(); + ByteArrayOutputStream resultBytes = null; + Result xmlResult = (isXMLEntity || identityLinkDomainIdentifier != null) + ? result.getXmlResult(true) + : new StreamResult((resultBytes = new ByteArrayOutputStream())); + try { + identityLinkTransformer.transformIdLink(issuerTemplate, new DOMSource(document), xmlResult); + } catch (IOException e) { + // we should not get an IOException as we are writing into a DOMResult + throw new SLRuntimeException(e); + } catch (TransformerException e) { + log.info("Faild to transform CompressedIdentityLink.", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + + // TODO: Report BUG in IssuerTemplates + // Some IssuerTemplate stylesheets do not consider the pr:Type-Element of the CompressedIdentityLink ... + if (identityLinkDomainIdentifier != null) { + if (xmlResult instanceof DOMResult) { + Node node = ((DOMResult) xmlResult).getNode(); + Node nextSibling = ((DOMResult) xmlResult).getNextSibling(); + Node idLinkNode; + if (nextSibling != null) { + idLinkNode = nextSibling.getPreviousSibling(); + } else if (node != null) { + idLinkNode = node.getFirstChild(); + } else { + log + .error("An IdentityLinkDomainIdentifier of '" + + identityLinkDomainIdentifier + + "' has been given. However, it cannot be set, as the transformation result does not contain a node."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + IdentityLinkTransformer.setDomainIdentifier(idLinkNode, identityLinkDomainIdentifier); + } else { + log + .error("An IdentityLinkDomainIdentifier of '" + + identityLinkDomainIdentifier + + "' has been given. However, it cannot be set, as the transformation result is not of type DOM."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + } + + if (!isXMLEntity) { + if (resultBytes == null) { + resultBytes = new ByteArrayOutputStream(); + + if (xmlResult instanceof DOMResult) { + Node node = ((DOMResult) xmlResult).getNode(); + Node nextSibling = ((DOMResult) xmlResult).getNextSibling(); + + DOMSource xmlSource; + if (nextSibling != null) { + xmlSource = new DOMSource(nextSibling.getPreviousSibling()); + } else if (node != null) { + xmlSource = new DOMSource(node.getFirstChild()); + } else { + log + .error("IssuerTemplate transformation returned no node."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + try { + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(xmlSource, new StreamResult(resultBytes)); + } catch (TransformerConfigurationException e) { + log.error(e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } catch (TransformerException e) { + log.error(e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + } else if (xmlResult instanceof StreamResult) { + OutputStream outputStream = ((StreamResult) xmlResult).getOutputStream(); + if (outputStream instanceof ByteArrayOutputStream) { + result.setResultBytes(((ByteArrayOutputStream) outputStream).toByteArray()); + } else { + log.error("ContentIsXMLEntity is set to 'false'. However, an XMLResult has already been set."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + } + } else { + result.setResultBytes(resultBytes.toByteArray()); + } + } + + + return result; + + } +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java new file mode 100644 index 00000000..6f07338f --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java @@ -0,0 +1,171 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Result; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; + +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLContentType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.buergerkarte.namespaces.securitylayer._1.XMLContentType; +import at.gv.egiz.bku.slcommands.InfoboxReadResult; +import at.gv.egiz.bku.slcommands.SLCommand; +import at.gv.egiz.bku.slcommands.SLCommandFactory; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; + +/** + * This class implements the result of the security layer command InfoboxReadRequest. + * + * @author mcentner + */ +public class InfoboxReadResultImpl extends SLResultImpl implements + InfoboxReadResult { + + /** + * Logging facility. + */ + protected static Log log = LogFactory.getLog(InfoboxReadResultImpl.class); + + /** + * The XML document containing the infobox content. + */ + Document xmlDocument; + + /** + * Creates the response document from the given binaryContent. + * + * @param binaryContent the infobox content + * @param preserveSpace the value of the preserveSpace parameter + * + * @return the created response document + */ + private Document createResponseDocument(byte[] binaryContent, boolean preserveSpace) { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + Document doc; + try { + doc = dbf.newDocumentBuilder().newDocument(); + } catch (ParserConfigurationException e) { + // it should always be possible to create a new Document + log.error("Failed to create XML document.", e); + throw new SLRuntimeException(e); + } + + ObjectFactory factory = new ObjectFactory(); + + Base64XMLContentType base64XMLContentType = factory.createBase64XMLContentType(); + if (binaryContent == null) { + XMLContentType xmlContentType = factory.createXMLContentType(); + if (preserveSpace) { + xmlContentType.setSpace("preserve"); + } + base64XMLContentType.setXMLContent(xmlContentType); + } else { + base64XMLContentType.setBase64Content(binaryContent); + } + InfoboxReadResponseType infoboxReadResponseType = factory.createInfoboxReadResponseType(); + infoboxReadResponseType.setBinaryFileData(base64XMLContentType); + + JAXBElement infoboxReadResponse = factory.createInfoboxReadResponse(infoboxReadResponseType); + + JAXBContext context = SLCommandFactory.getJaxbContext(); + try { + Marshaller marshaller = context.createMarshaller(); + marshaller.marshal(infoboxReadResponse, doc); + } catch (JAXBException e) { + log.error("Failed to marshal 'InfoboxReadResponse' document.", e); + throw new SLRuntimeException(e); + } + + return doc; + + } + + + /** + * @return an XMLResult for marshalling the infobox to + */ + Result getXmlResult(boolean preserveSpace) { + + xmlDocument = createResponseDocument(null, preserveSpace); + + NodeList nodeList = xmlDocument.getElementsByTagNameNS(SLCommand.NAMESPACE_URI, "XMLContent"); + return new DOMResult(nodeList.item(0)); + + } + + /** + * Creates a new result document for this InfoboxReadResult + * and sets the given resultBytes as content. + * + * @param resultBytes + */ + void setResultBytes(byte[] resultBytes) { + + xmlDocument = createResponseDocument(resultBytes, false); + + } + + @Override + public void writeTo(Result result) { + + try { + writeTo(result, null); + } catch (TransformerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /* (non-Javadoc) + * @see at.gv.egiz.bku.slcommands.impl.SLResultImpl#writeTo(javax.xml.transform.Result, javax.xml.transform.Transformer) + */ + @Override + public void writeTo(Result result, Transformer transformer) throws TransformerException { + + if (transformer == null) { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + try { + transformer = transformerFactory.newTransformer(); + } catch (TransformerConfigurationException e) { + log.error("Failed to create Transformer.", e); + throw new SLRuntimeException(e); + } + } + transformer.transform(new DOMSource(xmlDocument), result); + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationCommandImpl.java new file mode 100644 index 00000000..1b6fb237 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationCommandImpl.java @@ -0,0 +1,43 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import at.buergerkarte.namespaces.securitylayer._1.NullOperationRequestType; +import at.gv.egiz.bku.slcommands.NullOperationCommand; +import at.gv.egiz.bku.slcommands.NullOperationResult; +import at.gv.egiz.bku.slcommands.SLResult; + +/** + * This class implements the security layer command NullOperation. + * + * @author mcentner + */ +public class NullOperationCommandImpl extends SLCommandImpl implements NullOperationCommand { + + protected static NullOperationResult RESULT = new NullOperationResultImpl(); + + @Override + public SLResult execute() { + return RESULT; + } + + @Override + public String getName() { + return "NullOperationRequest"; + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java new file mode 100644 index 00000000..ae1f91ce --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java @@ -0,0 +1,47 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import javax.xml.bind.JAXBElement; +import javax.xml.transform.Result; + +import at.buergerkarte.namespaces.securitylayer._1.NullOperationResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.gv.egiz.bku.slcommands.NullOperationResult; + +/** + * This class represents the result of the security layer command + * NullOperation. + * + * @author mcentner + */ +public class NullOperationResultImpl extends SLResultImpl implements NullOperationResult { + + protected static JAXBElement RESPONSE; + + static { + ObjectFactory factory = new ObjectFactory(); + NullOperationResponseType type = factory.createNullOperationResponseType(); + RESPONSE = factory.createNullOperationResponse(type); + } + + @Override + public void writeTo(Result result) { + writeTo(RESPONSE, result); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLCommandImpl.java new file mode 100644 index 00000000..9a3a2984 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLCommandImpl.java @@ -0,0 +1,162 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +import javax.xml.bind.JAXBElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.bku.slcommands.SLCommand; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.stal.ErrorResponse; +import at.gv.egiz.stal.STAL; +import at.gv.egiz.stal.STALRequest; +import at.gv.egiz.stal.STALResponse; + +/** + * This class serves as abstract base class for the implementation of a security + * layer command. + * + * @author mcentner + * + * @param + * the type of the corresponding request value + */ +public abstract class SLCommandImpl implements SLCommand { + + /** + * The SLCommandContext for this SLCommand. + */ + protected SLCommandContext cmdCtx; + + /** + * The request element of this command. + */ + protected JAXBElement request; + + /** + * An iterator over the STALResponses received in + * {@link SLCommandImpl#requestSTAL(List)}. + */ + protected Iterator stalResponses; + + @SuppressWarnings("unchecked") + @Override + public void init(SLCommandContext ctx, Object request) + throws SLCommandException { + + this.request = (JAXBElement) request; + + this.cmdCtx = ctx; + assert this.cmdCtx != null; + + } + + /** + * Returns the request value. + * + * It is a convenience method for request.getValue(). + * + * @see JAXBElement#getValue() + * @return the request value + */ + protected T getRequestValue() { + return request.getValue(); + } + + /** + * @return the corresponding SLCommandContext + */ + protected SLCommandContext getCmdCtx() { + return cmdCtx; + } + + /** + * Calls {@link STAL#handleRequest(List)} with the given + * stalRequests. + * + * @param stalRequests + * @throws SLCommandException + */ + protected void requestSTAL(List stalRequests) throws SLCommandException { + List responses = cmdCtx.getSTAL().handleRequest(stalRequests); + if (responses == null) { + Log log = LogFactory.getLog(this.getClass()); + log.info("Received no responses from STAL."); + throw new SLCommandException(4000); + } else if (responses.size() != stalRequests.size()) { + Log log = LogFactory.getLog(this.getClass()); + log.info("Received invalid count of responses from STAL. Expected " + + stalRequests.size() + ", but got " + responses.size() + "."); + // throw new SLCommandException(4000); + } + stalResponses = responses.iterator(); + } + + /** + * @return true if there are more {@link STALResponse}s to be + * fetched with {@link #nextResponse(Class)}, or false + * otherwise. + */ + protected boolean hasNextResponse() { + return (stalResponses != null) ? stalResponses.hasNext() : false; + } + + /** + * Returns the next response of type responseClass that has been + * received by {@link #requestSTAL(List)}. + * + * @param responseClass + * the response must be an instance of + * @return the next response of type responseClass + * + * @throws NoSuchElementException + * if there is no more response + * @throws SLCommandException + * if the next response is of type {@link ErrorResponse} or not of + * type responseClass + */ + protected STALResponse nextResponse( + Class responseClass) throws SLCommandException { + + if (stalResponses == null) { + throw new NoSuchElementException(); + } + + STALResponse response = stalResponses.next(); + + if (response instanceof ErrorResponse) { + throw new SLCommandException(((ErrorResponse) response).getErrorCode()); + } + + if (!(responseClass.isAssignableFrom(response.getClass()))) { + Log log = LogFactory.getLog(this.getClass()); + log.info("Received " + response.getClass() + " from STAL but expected " + + responseClass); + throw new SLCommandException(4000); + } + + return response; + + } +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java new file mode 100644 index 00000000..a79382b6 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java @@ -0,0 +1,117 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.transform.Result; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.bku.slcommands.SLCommandFactory; +import at.gv.egiz.bku.slcommands.SLResult; + +/** + * This class serves as an abstract base class for the implementation of a + * security layer result. + * + * @author mcentner + */ +public abstract class SLResultImpl implements SLResult { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(SLResult.class); + + /** + * The security layer result type (default = XML). + */ + protected SLResultType resultType = SLResultType.XML; + + /** + * The security layer result MIME-type (default = text/xml). + */ + protected String resultingMimeType = "text/xml"; + + /* (non-Javadoc) + * @see at.gv.egiz.bku.slcommands.SLResult#getResultType() + */ + public SLResultType getResultType() { + return resultType; + } + + /* (non-Javadoc) + * @see at.gv.egiz.bku.slcommands.SLResult#getMimeType() + */ + public String getMimeType() { + return resultingMimeType; + } + + /** + * Writes the given response to the result. + * + * @param response the security layer response element + * @param result the result to marshal the response to + */ + @SuppressWarnings("unchecked") + public void writeTo(JAXBElement response, Result result) { + + try { + JAXBContext context = SLCommandFactory.getJaxbContext(); + Marshaller marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + marshaller.marshal(response, result); + } catch (JAXBException e) { + // TODO Add throws clause to interface + log.fatal("Failed to marshall JAXBElement.", e); + throw new RuntimeException("Failed to marshall JAXBElement.", e); + } + + } + + /* (non-Javadoc) + * @see at.gv.egiz.bku.slcommands.SLResult#writeTo(javax.xml.transform.Result, javax.xml.transform.Transformer) + */ + @Override + public void writeTo(Result result, Transformer transformer) throws TransformerException { + // TODO Auto-generated method stub + // fixxme: wb added for testing purposes to be completed + // begin hack + if (transformer == null) { + writeTo(result); + return; + } + // just a quick hack to proceed with testing + ByteArrayOutputStream os = new ByteArrayOutputStream(); + writeTo(new StreamResult(os)); + ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); + transformer.transform(new StreamSource(is), result); + //end hack + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactory.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactory.java new file mode 100644 index 00000000..d6cbaefa --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactory.java @@ -0,0 +1,79 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.security.InvalidAlgorithmParameterException; +import java.security.NoSuchAlgorithmException; + +import javax.xml.crypto.AlgorithmMethod; +import javax.xml.crypto.dsig.CanonicalizationMethod; +import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.dsig.SignatureMethod; + +/** + * A factory for creating {@link AlgorithmMethod}s. + * + * @author mcentner + */ +public interface AlgorithmMethodFactory { + + /** + * Creates a new DigestMethod for the given signatureContext. + * + * @param signatureContext + * the signature context + * + * @return a DigestMethod for the given signatureContext + * + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + */ + public DigestMethod createDigestMethod(SignatureContext signatureContext) + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException; + + /** + * Creates a new SignatureMethod for the given signatureContext. + * + * @param signatureContext + * the signature context + * + * @return a SignatureMethod for the given signatureContext + * + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + */ + public SignatureMethod createSignatureMethod(SignatureContext signatureContext) + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException; + + /** + * Creates a new CanonicalizationMethod for the given + * signatureContext. + * + * @param signatureContext + * the signature context + * + * @return a CanonicalizationMethod for the given + * signatureContext + * + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + */ + public CanonicalizationMethod createCanonicalizationMethod( + SignatureContext signatureContext) throws NoSuchAlgorithmException, + InvalidAlgorithmParameterException; + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java new file mode 100644 index 00000000..6b963465 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java @@ -0,0 +1,125 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import iaik.xml.crypto.XmldsigMore; + +import java.security.InvalidAlgorithmParameterException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; + +import javax.xml.crypto.dsig.CanonicalizationMethod; +import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.dsig.SignatureMethod; +import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; +import javax.xml.crypto.dsig.spec.DigestMethodParameterSpec; +import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; + +/** + * An implementation of the AlgorithmMethod factory that uses the signing + * certificate to choose appropriate algorithms. + * + * @author mcentner + */ +public class AlgorithmMethodFactoryImpl implements AlgorithmMethodFactory { + + /** + * The signature algorithm URI. + */ + private String signatureAlgorithmURI; + + /** + * The algorithm parameters for the signature algorithm. + */ + private SignatureMethodParameterSpec signatureMethodParameterSpec; + + /** + * Creates a new AlgrithmMethodFactory with the given + * signingCertificate. + * + * @param siginingCertificate + * + * @throws NoSuchAlgorithmException + * if the public key algorithm of the given + * signingCertificate is not supported + */ + public AlgorithmMethodFactoryImpl(X509Certificate siginingCertificate) + throws NoSuchAlgorithmException { + + String algorithm = siginingCertificate.getPublicKey().getAlgorithm(); + + if ("DSA".equals(algorithm)) { + signatureAlgorithmURI = SignatureMethod.DSA_SHA1; + } else if ("RSA".equals(algorithm)) { + signatureAlgorithmURI = SignatureMethod.RSA_SHA1; + } else if (("EC".equals(algorithm)) || ("ECDSA".equals(algorithm))) { + signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA1; + } else { + throw new NoSuchAlgorithmException("Public key algorithm '" + algorithm + + "' not supported."); + } + + } + + /* + * (non-Javadoc) + * + * @seeat.gv.egiz.bku.slcommands.impl.xsect.AlgorithmMethodFactory# + * createCanonicalizationMethod + * (at.gv.egiz.bku.slcommands.impl.xsect.SignatureContext) + */ + @Override + public CanonicalizationMethod createCanonicalizationMethod( + SignatureContext signatureContext) throws NoSuchAlgorithmException, + InvalidAlgorithmParameterException { + + return signatureContext.getSignatureFactory().newCanonicalizationMethod( + CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); + + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egiz.bku.slcommands.impl.xsect.AlgorithmMethodFactory#createDigestMethod + * (at.gv.egiz.bku.slcommands.impl.xsect.SignatureContext) + */ + @Override + public DigestMethod createDigestMethod(SignatureContext signatureContext) + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { + + return signatureContext.getSignatureFactory().newDigestMethod( + DigestMethod.SHA1, (DigestMethodParameterSpec) null); + } + + /* + * (non-Javadoc) + * + * @seeat.gv.egiz.bku.slcommands.impl.xsect.AlgorithmMethodFactory# + * createSignatureMethod + * (at.gv.egiz.bku.slcommands.impl.xsect.SignatureContext) + */ + @Override + public SignatureMethod createSignatureMethod(SignatureContext signatureContext) + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { + + return signatureContext.getSignatureFactory().newSignatureMethod( + signatureAlgorithmURI, signatureMethodParameterSpec); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/ByteArrayDereferencer.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/ByteArrayDereferencer.java new file mode 100644 index 00000000..a6473a05 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/ByteArrayDereferencer.java @@ -0,0 +1,65 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.io.ByteArrayInputStream; + +import javax.xml.crypto.Data; +import javax.xml.crypto.OctetStreamData; +import javax.xml.crypto.URIDereferencer; +import javax.xml.crypto.URIReference; +import javax.xml.crypto.URIReferenceException; +import javax.xml.crypto.XMLCryptoContext; + +/** + * An URIDereferencer implementation that dereferences the given + * byte array. + * + * @author mcentner + */ +public class ByteArrayDereferencer implements URIDereferencer { + + /** + * The dereferenced data. + */ + protected byte[] dereferencedData; + + /** + * Creates a new instance of this ByteArrayDereferencer with + * the given dereferencedData. + * + * @param dereferencedData the octets to be returned by {@link #dereference(URIReference, XMLCryptoContext)} + * + * @throws NullPointerException if dereferencedData is null + */ + public ByteArrayDereferencer(byte[] dereferencedData) { + if (dereferencedData == null) { + throw new NullPointerException("Parameter 'dereferencedData' must not be null."); + } + this.dereferencedData = dereferencedData; + } + + /* (non-Javadoc) + * @see javax.xml.crypto.URIDereferencer#dereference(javax.xml.crypto.URIReference, javax.xml.crypto.XMLCryptoContext) + */ + @Override + public Data dereference(URIReference uriReference, XMLCryptoContext context) + throws URIReferenceException { + return new OctetStreamData(new ByteArrayInputStream(dereferencedData)); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java new file mode 100644 index 00000000..d25f2526 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java @@ -0,0 +1,1006 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import iaik.xml.crypto.dom.DOMCryptoContext; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.SequenceInputStream; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.net.URISyntaxException; +import java.nio.charset.Charset; +import java.security.InvalidAlgorithmParameterException; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.dom.DOMStructure; +import javax.xml.crypto.dsig.CanonicalizationMethod; +import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.dsig.Reference; +import javax.xml.crypto.dsig.Transform; +import javax.xml.crypto.dsig.XMLObject; +import javax.xml.crypto.dsig.spec.TransformParameterSpec; +import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec; +import javax.xml.crypto.dsig.spec.XPathType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.DOMConfiguration; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.Text; +import org.w3c.dom.bootstrap.DOMImplementationRegistry; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSException; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSParser; +import org.w3c.dom.ls.LSSerializer; + +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLLocRefOptRefContentType; +import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; +import at.buergerkarte.namespaces.securitylayer._1.MetaInfoType; +import at.buergerkarte.namespaces.securitylayer._1.TransformsInfoType; +import at.gv.egiz.bku.binding.HttpUtil; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLRequestException; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import at.gv.egiz.bku.utils.urldereferencer.StreamData; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; +import at.gv.egiz.dom.DOMUtils; +import at.gv.egiz.slbinding.impl.XMLContentType; + +/** + * This class represents a DataObject of an XML-Signature + * created by the security layer command CreateXMLSignature. + * + * @author mcentner + */ +public class DataObject { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(DataObject.class); + + /** + * DOM Implementation. + */ + private static final String DOM_LS_3_0 = "LS 3.0"; + + /** + * The array of the default preferred MIME type order. + */ + private static final String[] DEFAULT_PREFFERED_MIME_TYPES = + new String[] { + "application/xhtml+xml", + "text/plain" + }; + + /** + * The DOM implementation used. + */ + private DOMImplementationLS domImplLS; + + /** + * The signature context. + */ + private SignatureContext ctx; + + /** + * The Reference for this DataObject. + */ + private XSECTReference reference; + + /** + * The XMLObject for this DataObject. + */ + private XMLObject xmlObject; + + /** + * The MIME-Type of the digest input. + */ + private String mimeType; + + /** + * An optional description of the digest input. + */ + private String description; + + /** + * Creates a new instance. + * + * @param document the document of the target signature + */ + public DataObject(SignatureContext signatureContext) { + this.ctx = signatureContext; + + DOMImplementationRegistry registry; + try { + registry = DOMImplementationRegistry.newInstance(); + } catch (Exception e) { + log.error("Failed to get DOMImplementationRegistry.", e); + throw new SLRuntimeException("Failed to get DOMImplementationRegistry."); + } + + domImplLS = (DOMImplementationLS) registry.getDOMImplementation(DOM_LS_3_0); + if (domImplLS == null) { + log.error("Failed to get DOMImplementation " + DOM_LS_3_0); + throw new SLRuntimeException("Failed to get DOMImplementation " + DOM_LS_3_0); + } + + } + + /** + * @return the reference + */ + public Reference getReference() { + return reference; + } + + /** + * @return the xmlObject + */ + public XMLObject getXmlObject() { + return xmlObject; + } + + /** + * @return the mimeType + */ + public String getMimeType() { + return mimeType; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Configures this DataObject with the information provided within the given + * sl:DataObjectInfo. + * + * @param dataObjectInfo + * the sl:DataObjectInfo + * + * @throws SLCommandException + * if configuring this DataObject with the information provided in + * the sl:DataObjectInfo fails. + * @throws SLRequestException + * if the information provided in the sl:DataObjectInfo + * does not conform to the security layer specification. + * @throws NullPointerException + * if dataObjectInfo is null + */ + public void setDataObjectInfo(DataObjectInfoType dataObjectInfo) throws SLCommandException, SLRequestException { + + Base64XMLLocRefOptRefContentType dataObject = dataObjectInfo.getDataObject(); + String structure = dataObjectInfo.getStructure(); + + // select and unmarshal an appropriate transformation path if provided + // and set the final data meta information + XSECTTransforms transforms = createTransformsAndSetFinalDataMetaInfo(dataObjectInfo.getTransformsInfo()); + + if ("enveloping".equals(structure)) { + + // configure this DataObject as an enveloped DataObject + setEnvelopedDataObject(dataObject, transforms); + + } else if ("detached".equals(structure)) { + + // configure this DataObject as an detached DataObject + setDetachedDataObject(dataObject, transforms); + + } + // other values are not allowed by the schema and are therefore ignored + + } + + /** + * Configures this DataObject as an enveloped DataObject with the information + * provided within the given sl:DataObject. + * + * @param dataObject + * the sl:DataObject + * @param transforms + * an optional Transforms element (may be + * null) + * + * @throws SLCommandException + * if configuring this DataObject with the information provided in + * the sl:DataObject fails. + * @throws SLRequestException + * if the information provided in the sl:DataObject + * does not conform to the security layer specification. + * @throws NullPointerException + * if dataObject is null + */ + private void setEnvelopedDataObject( + Base64XMLLocRefOptRefContentType dataObject, XSECTTransforms transforms) + throws SLCommandException, SLRequestException { + + String reference = dataObject.getReference(); + if (reference == null) { + // + // case A + // + // The Reference attribute is not used; the content of sl:DataObject represents the data object. + // If the data object is XML-coded (the sl:XMLContent element is used in sl:DataObject), then it + // must be incorporated in the signature structure as parsed XML. + // + + if (dataObject.getBase64Content() != null) { + + log.debug("Adding DataObject (Base64Content) without a reference URI."); + + // create XMLObject + XMLObject xmlObject = createXMLObject(new ByteArrayInputStream(dataObject.getBase64Content())); + + setXMLObjectAndReferenceBase64(xmlObject, transforms); + + } else if (dataObject.getXMLContent() != null) { + + log.debug("Adding DataObject (XMLContent) without a reference URI."); + + // create XMLObject + DocumentFragment content = parseDataObject((XMLContentType) dataObject.getXMLContent()); + XMLObject xmlObject = createXMLObject(content); + + setXMLObjectAndReferenceXML(xmlObject, transforms); + + } else if (dataObject.getLocRefContent() != null) { + + log.debug("Adding DataObject (LocRefContent) without a reference URI."); + + setEnvelopedDataObject(dataObject.getLocRefContent(), transforms); + + } else { + + // not allowed + log.info("XML structure of the command request contains an " + + "invalid combination of optional elements or attributes. " + + "DataObject of structure='enveloped' without a reference must contain content."); + throw new SLRequestException(3003); + + } + + } else { + + if (dataObject.getBase64Content() == null && + dataObject.getXMLContent() == null && + dataObject.getLocRefContent() == null) { + + // + // case B + // + // The Reference attribute contains a URI that must be resolved by the + // Citizen Card Environment to obtain the data object. + // The content of sl:DataObject remains empty + // + + log.debug("Adding DataObject from reference URI '" + reference + "'."); + + setEnvelopedDataObject(reference, transforms); + + } else { + + // not allowed + log.info("XML structure of the command request contains an " + + "invalid combination of optional elements or attributes. " + + "DataObject of structure='enveloped' with reference must not contain content."); + throw new SLRequestException(3003); + + } + + + } + + } + + /** + * Configures this DataObject as an enveloped DataObject with the content to + * be dereferenced from the given reference. + * + * @param reference + * the reference URI + * @param transforms + * an optional Transforms element (may be + * null) + * + * @throws SLCommandException + * if dereferencing the given reference fails, or if + * configuring this DataObject with the data dereferenced from the + * given reference fails. + * @throws NullPointerException + * if reference is null + */ + private void setEnvelopedDataObject(String reference, XSECTTransforms transforms) throws SLCommandException { + + if (reference == null) { + throw new NullPointerException("Argument 'reference' must not be null."); + } + + // dereference URL + URLDereferencer dereferencer = URLDereferencer.getInstance(); + + StreamData streamData; + try { + streamData = dereferencer.dereference(reference, ctx.getDereferencerContext()); + } catch (IOException e) { + log.info("Failed to dereference XMLObject from '" + reference + "'.", e); + throw new SLCommandException(4110); + } + + Node childNode; + + String contentType = streamData.getContentType(); + if (contentType.startsWith("text/xml")) { + + // If content type is text/xml parse content. + String charset = HttpUtil.getCharset(contentType, true); + + Document doc = parseDataObject(streamData.getStream(), charset); + + childNode = doc.getDocumentElement(); + + if (childNode == null) { + log.info("Failed to parse XMLObject from '" + reference + "'."); + throw new SLCommandException(4111); + } + + XMLObject xmlObject = createXMLObject(childNode); + + setXMLObjectAndReferenceXML(xmlObject, transforms); + + } else { + + // Include content Base64 encoded. + XMLObject xmlObject = createXMLObject(streamData.getStream()); + + setXMLObjectAndReferenceBase64(xmlObject, transforms); + + } + + } + + /** + * Configures this DataObject as an detached DataObject with the information + * provided in the given sl:DataObject and optionally + * transforms. + * + * @param dataObject + * the sl:DataObject + * @param transforms + * an optional Transforms object, may be null + * + * @throws SLCommandException + * if configuring this DataObject with the information provided in + * the sl:DataObject fails. + * @throws SLRequestException + * if the information provided in the sl:DataObject + * does not conform to the security layer specification. + * @throws NullPointerException + * if dataObject is null + */ + private void setDetachedDataObject( + Base64XMLLocRefOptRefContentType dataObject, XSECTTransforms transforms) + throws SLCommandException, SLRequestException { + + String referenceURI = dataObject.getReference(); + + if (referenceURI == null) { + + // not allowed + log.info("XML structure of the command request contains an " + + "invalid combination of optional elements or attributes. " + + "DataObject of structure='detached' must contain a reference."); + throw new SLRequestException(3003); + + } else { + + DigestMethod dm; + try { + dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } + + String idValue = ctx.getIdValueFactory().createIdValue("Reference"); + + reference = new XSECTReference(referenceURI, dm, transforms, null, idValue); + + // case D: + // + // The Reference attribute contains a URI that is used by the Citizen Card + // Environment to code the reference to the data object as part of the XML + // signature (attribute URI in the dsig:Reference) element. The content of + // sl:DataObject represents the data object. + + if (dataObject.getLocRefContent() != null) { + String locRef = dataObject.getLocRefContent(); + try { + this.reference.setDereferencer(new LocRefDereferencer(ctx.getDereferencerContext(), locRef)); + } catch (URISyntaxException e) { + log.info("Invalid URI '" + locRef + "' in DataObject.", e); + throw new SLCommandException(4003); + } catch (IllegalArgumentException e) { + log.info("LocRef URI of '" + locRef + "' not supported in DataObject. ", e); + throw new SLCommandException(4003); + } + } else if (dataObject.getBase64Content() != null) { + byte[] base64Content = dataObject.getBase64Content(); + this.reference.setDereferencer(new ByteArrayDereferencer(base64Content)); + } else if (dataObject.getXMLContent() != null) { + XMLContentType xmlContent = (XMLContentType) dataObject.getXMLContent(); + byte[] bytes = xmlContent.getRedirectedStream().toByteArray(); + this.reference.setDereferencer(new ByteArrayDereferencer(bytes)); + } else { + + // case C: + // + // The Reference attribute contains a URI that must be resolved by the + // Citizen Card Environment to obtain the data object. The Reference + // attribute contains a URI that is used by the Citizen Card Environment + // to code the reference to the data object as part of the XML signature + // (attribute URI in the dsig:Reference) element. The content of + // sl:DataObject remains empty. + + } + + } + } + + /** + * Returns the preferred sl:TransformInfo from the given list of + * transformInfos, or null if none of the given + * transformInfos is preferred over the others. + * + * @param transformsInfos + * a list of sl:TransformInfos + * + * @return the selected sl:TransformInfo or null, if + * none is preferred over the others + */ + private TransformsInfoType selectPreferredTransformsInfo(List transformsInfos) { + + Map mimeTypes = new HashMap(); + + StringBuilder debugString = null; + if (log.isDebugEnabled()) { + debugString = new StringBuilder(); + debugString.append("Got " + transformsInfos.size() + " TransformsInfo(s):"); + } + + for (TransformsInfoType transformsInfoType : transformsInfos) { + MetaInfoType finalDataMetaInfo = transformsInfoType.getFinalDataMetaInfo(); + String mimeType = finalDataMetaInfo.getMimeType(); + String description = finalDataMetaInfo.getDescription(); + mimeTypes.put(mimeType, transformsInfoType); + if (debugString != null) { + debugString.append("\n FinalDataMetaInfo: MIME-Type="); + debugString.append(mimeType); + if (description != null) { + debugString.append(" "); + debugString.append(description); + } + } + } + + if (debugString != null) { + log.debug(debugString); + } + + // look for preferred transform + for (String mimeType : DEFAULT_PREFFERED_MIME_TYPES) { + if (mimeTypes.containsKey(mimeType)) { + return mimeTypes.get(mimeType); + } + } + + // no preferred transform + return null; + + } + + /** + * Create an instance of ds:Transforms from the given + * sl:TransformsInfo. + * + * @param transformsInfo + * the sl:TransformsInfo + * + * @return a corresponding unmarshalled ds:Transforms, or + * null if the given sl:TransformsInfo does + * not contain a dsig:Transforms element + * + * @throws SLRequestException + * if the ds:Transforms in the given + * transformsInfo are not valid or cannot be parsed. + * + * @throws MarshalException + * if the ds:Transforms in the given + * transformsInfo cannot be unmarshalled. + */ + private XSECTTransforms createTransforms(TransformsInfoType transformsInfo) throws SLRequestException, MarshalException { + + ByteArrayOutputStream redirectedStream = ((at.gv.egiz.slbinding.impl.TransformsInfoType) transformsInfo).getRedirectedStream(); + byte[] transformBytes = (redirectedStream != null) ? redirectedStream.toByteArray() : null; + + if (transformBytes != null && transformBytes.length > 0) { + + // debug + if (log.isTraceEnabled()) { + StringBuilder sb = new StringBuilder(); + sb.append("Trying to parse transforms:\n"); + sb.append(new String(transformBytes, Charset.forName("UTF-8"))); + log.trace(sb); + } + + DOMImplementationLS domImplLS = DOMUtils.getDOMImplementationLS(); + LSInput input = domImplLS.createLSInput(); + input.setByteStream(new ByteArrayInputStream(transformBytes)); + + LSParser parser = domImplLS.createLSParser( + DOMImplementationLS.MODE_SYNCHRONOUS, null); + DOMConfiguration domConfig = parser.getDomConfig(); + SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); + domConfig.setParameter("error-handler", errorHandler); + domConfig.setParameter("validate", Boolean.FALSE); + + Document document; + try { + document = parser.parse(input); + } catch (DOMException e) { + log.info("Failed to parse dsig:Transforms.", e); + throw new SLRequestException(3002); + } catch (LSException e) { + log.info("Failed to parse dsig:Transforms.", e); + throw new SLRequestException(3002); + } + + // adopt ds:Transforms + Element documentElement = document.getDocumentElement(); + Node adoptedTransforms = ctx.getDocument().adoptNode(documentElement); + + DOMCryptoContext context = new DOMCryptoContext(); + + // unmarshall ds:Transforms + return new XSECTTransforms(context, adoptedTransforms); + + } else { + return null; + } + + } + + /** + * Sets the mimeType and the description value + * for this DataObject. + * + * @param metaInfoType the sl:FinalMetaDataInfo + * + * @throws NullPointerException if metaInfoType is null + */ + private void setFinalDataMetaInfo(MetaInfoType metaInfoType) { + + this.mimeType = metaInfoType.getMimeType(); + this.description = metaInfoType.getDescription(); + + } + + /** + * Selects an appropriate transformation path (if present) from the given list + * of sl:TransformInfos, sets the corresponding final data meta info and + * returns the corresponding unmarshalled ds:Transforms. + * + * @param transformsInfos the sl:TransformInfos + * + * @return the unmarshalled ds:Transforms, or null if + * no transformation path has been selected. + * + * @throws SLRequestException if the given list ds:TransformsInfo contains + * an invalid ds:Transforms element, or no suitable transformation path + * can be found. + */ + private XSECTTransforms createTransformsAndSetFinalDataMetaInfo( + List transformsInfos) throws SLRequestException { + + TransformsInfoType preferredTransformsInfo = selectPreferredTransformsInfo(transformsInfos); + // try preferred transform + if (preferredTransformsInfo != null) { + + try { + XSECTTransforms transforms = createTransforms(preferredTransformsInfo); + setFinalDataMetaInfo(preferredTransformsInfo.getFinalDataMetaInfo()); + return transforms; + } catch (MarshalException e) { + + String mimeType = preferredTransformsInfo.getFinalDataMetaInfo().getMimeType(); + log.info("Failed to unmarshal preferred transformation path (MIME-Type=" + + mimeType + ").", e); + + } + + } + + // look for another suitable transformation path + for (TransformsInfoType transformsInfoType : transformsInfos) { + + try { + XSECTTransforms transforms = createTransforms(transformsInfoType); + setFinalDataMetaInfo(transformsInfoType.getFinalDataMetaInfo()); + return transforms; + } catch (MarshalException e) { + + String mimeType = transformsInfoType.getFinalDataMetaInfo().getMimeType(); + log.info("Failed to unmarshal transformation path (MIME-Type=" + + mimeType + ").", e); + } + + } + + // no suitable transformation path found + throw new SLRequestException(3003); + + } + + /** + * Create an XMLObject with the Base64 encoding of the given + * content. + * + * @param content + * the to-be Base64 encoded content + * @return an XMLObject with the Base64 encoded content + */ + private XMLObject createXMLObject(InputStream content) { + + Text textNode; + try { + textNode = at.gv.egiz.dom.DOMUtils.createBase64Text(content, ctx.getDocument()); + } catch (IOException e) { + log.error(e); + throw new SLRuntimeException(e); + } + + DOMStructure structure = new DOMStructure(textNode); + + String idValue = ctx.getIdValueFactory().createIdValue("Object"); + + return ctx.getSignatureFactory().newXMLObject(Collections.singletonList(structure), idValue, null, null); + + } + + /** + * Create an XMLObject with the given content node. + * + * @param content the content node + * + * @return an XMLObject with the given content + */ + private XMLObject createXMLObject(Node content) { + + String idValue = ctx.getIdValueFactory().createIdValue("Object"); + + List structures = Collections.singletonList(new DOMStructure(content)); + + return ctx.getSignatureFactory().newXMLObject(structures, idValue, null, null); + + } + + /** + * Sets the given xmlObject and creates and sets a corresponding + * Reference. + *

+ * A transform to Base64-decode the xmlObject's content is inserted at the top + * of to the optional transforms if given, or to a newly created + * Transforms element if transforms is + * null. + * + * @param xmlObject + * the XMLObject + * @param transforms + * an optional Transforms element (may be + * null) + * + * @throws SLCommandException + * if creating the Reference fails + * @throws NullPointerException + * if xmlObject is null + */ + private void setXMLObjectAndReferenceBase64(XMLObject xmlObject, XSECTTransforms transforms) throws SLCommandException { + + // create reference URI + // + // NOTE: the ds:Object can be referenced directly, as the Base64 transform + // operates on the text() of the input nodelist. + // + String referenceURI = "#" + xmlObject.getId(); + + // create Base64 Transform + Transform transform; + try { + transform = ctx.getSignatureFactory().newTransform(Transform.BASE64, (TransformParameterSpec) null); + } catch (NoSuchAlgorithmException e) { + // algorithm must be present + throw new SLRuntimeException(e); + } catch (InvalidAlgorithmParameterException e) { + // algorithm does not take parameters + throw new SLRuntimeException(e); + } + + if (transforms == null) { + transforms = new XSECTTransforms(Collections.singletonList(transform)); + } else { + transforms.insertTransform(transform); + } + + DigestMethod dm; + try { + dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } + String id = ctx.getIdValueFactory().createIdValue("Reference"); + + this.xmlObject = xmlObject; + this.reference = new XSECTReference(referenceURI, dm, transforms, null, id); + + } + + /** + * Sets the given xmlObject and creates and sets a corresponding + * Reference. + *

+ * A transform to select the xmlObject's content is inserted at the top of to + * the optional transforms if given, or to a newly created + * Transforms element if transforms is + * null. + *

+ * + * @param xmlObject + * the XMLObject + * @param transforms + * an optional Transforms element (may be + * null) + * + * @throws SLCommandException + * if creating the Reference fails + * @throws NullPointerException + * if xmlObject is null + */ + private void setXMLObjectAndReferenceXML(XMLObject xmlObject, XSECTTransforms transforms) throws SLCommandException { + + // create reference URI + String referenceURI = "#" + xmlObject.getId(); + + // create Transform to select ds:Object's children + Transform xpathTransform; + Transform c14nTransform; + try { + + XPathType xpath = new XPathType("id(\"" + xmlObject.getId() + "\")/node()", XPathType.Filter.INTERSECT); + List xpaths = Collections.singletonList(xpath); + XPathFilter2ParameterSpec params = new XPathFilter2ParameterSpec(xpaths); + + xpathTransform = ctx.getSignatureFactory().newTransform(Transform.XPATH2, params); + + // add exclusive canonicalization to avoid signing the namespace context of the ds:Object + c14nTransform = ctx.getSignatureFactory().newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); + + } catch (NoSuchAlgorithmException e) { + // algorithm must be present + throw new SLRuntimeException(e); + } catch (InvalidAlgorithmParameterException e) { + // params must be appropriate + throw new SLRuntimeException(e); + } + + if (transforms == null) { + List newTransfroms = new ArrayList(); + newTransfroms.add(xpathTransform); + newTransfroms.add(c14nTransform); + transforms = new XSECTTransforms(newTransfroms); + } else { + transforms.insertTransform(xpathTransform); + } + + DigestMethod dm; + try { + dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } + String id = ctx.getIdValueFactory().createIdValue("Reference"); + + this.xmlObject = xmlObject; + this.reference = new XSECTReference(referenceURI, dm, transforms, null, id); + + } + + /** + * Parses the given xmlContent and returns a corresponding + * document fragment. + * + *

+ * The to-be parsed content is surrounded by ... elements to + * allow for mixed (e.g. Text and Element) content in XMLContent. + *

+ * + * @param xmlContent + * the XMLContent to-be parsed + * + * @return a document fragment containing the parsed nodes + * + * @throws SLCommandException + * if parsing the given xmlContent fails + * + * @throws NullPointerException + * if xmlContent is null + */ + private DocumentFragment parseDataObject(XMLContentType xmlContent) throws SLCommandException { + + ByteArrayOutputStream redirectedStream = xmlContent.getRedirectedStream(); + + // Note: We can assume a fixed character encoding of UTF-8 for the + // content of the redirect stream as the content has already been parsed + // and serialized again to the redirect stream. + + List inputStreams = new ArrayList(); + try { + // dummy start element + inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); + + // content + inputStreams.add(new ByteArrayInputStream(redirectedStream.toByteArray())); + + // dummy end element + inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + throw new SLRuntimeException(e); + } + + SequenceInputStream inputStream = new SequenceInputStream(Collections.enumeration(inputStreams)); + + // parse DataObject + Document doc = parseDataObject(inputStream, "UTF-8"); + + Element documentElement = doc.getDocumentElement(); + + if (documentElement == null || + !"dummy".equals(documentElement.getLocalName())) { + log.info("Failed to parse DataObject XMLContent."); + throw new SLCommandException(4111); + } + + DocumentFragment fragment = doc.createDocumentFragment(); + while (documentElement.getFirstChild() != null) { + fragment.appendChild(documentElement.getFirstChild()); + } + + // log parsed document + if (log.isTraceEnabled()) { + + StringWriter writer = new StringWriter(); + + writer.write("DataObject:\n"); + + LSOutput output = domImplLS.createLSOutput(); + output.setCharacterStream(writer); + output.setEncoding("UTF-8"); + LSSerializer serializer = domImplLS.createLSSerializer(); + serializer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE); + serializer.write(fragment, output); + + log.trace(writer.toString()); + } + + return fragment; + + } + + /** + * Parses the given inputStream using the given + * encoding and returns the parsed document. + * + * @param inputStream + * the to-be parsed input + * + * @param encoding + * the encoding to be used for parsing the given + * inputStream + * + * @return the parsed document + * + * @throws SLCommandException + * if parsing the inputStream fails. + * + * @throws NullPointerException + * if inputStram is null + */ + private Document parseDataObject(InputStream inputStream, String encoding) throws SLCommandException { + + LSInput input = domImplLS.createLSInput(); + input.setByteStream(inputStream); + + if (encoding != null) { + input.setEncoding(encoding); + } + + LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); + DOMConfiguration domConfig = parser.getDomConfig(); + SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); + domConfig.setParameter("error-handler", errorHandler); + domConfig.setParameter("validate", Boolean.FALSE); + + Document doc; + try { + doc = parser.parse(input); + } catch (DOMException e) { + log.info("Existing XML document cannot be parsed.", e); + throw new SLCommandException(4111); + } catch (LSException e) { + log.info("Existing XML document cannot be parsed. ", e); + throw new SLCommandException(4111); + } + + if (errorHandler.hasErrors()) { + // log errors + if (log.isInfoEnabled()) { + List errorMessages = errorHandler.getErrorMessages(); + StringBuffer sb = new StringBuffer(); + for (String errorMessage : errorMessages) { + sb.append(" "); + sb.append(errorMessage); + } + log.info("Existing XML document cannot be parsed. " + sb.toString()); + } + throw new SLCommandException(4111); + } + + return doc; + + } + + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/IdValueFactory.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/IdValueFactory.java new file mode 100644 index 00000000..df42bd11 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/IdValueFactory.java @@ -0,0 +1,37 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +/** + * A factory for creating xsd:Id-attribute values. + * + * @author mcentner + */ +public interface IdValueFactory { + + /** + * Creates a new xsd:Id-attribute value for an Element of the + * given elementName. + * + * @param elementName + * the local name of the element to create the value for + * + * @return a xsd:Id-attribute value + */ + public String createIdValue(String elementName); + +} \ No newline at end of file diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/IdValueFactoryImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/IdValueFactoryImpl.java new file mode 100644 index 00000000..b9824655 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/IdValueFactoryImpl.java @@ -0,0 +1,127 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +/** + * An implementation of the IdValueFactory. + *

+ * This IdValueFactory creates xsd:Id-attribute values of the form + * '<elementName>-<random>-<sequenceNumber>', + * where + *

    + *
  • <elementName> is the name provided at + * {@link #createIdValue(String)},
  • + *
  • <random> is a random generated fixed value for an + * instance of this IdValueFactory and
  • + *
  • <sequenceNumber> is the sequence number of the value + * generated for a given elementName by an instance of this + * IdValueFactory.
  • + *
+ *

+ * + * @author mcentner + */ +public class IdValueFactoryImpl implements IdValueFactory { + + /** + * A generator for xsd:Id-attribute values. + * + * @author mcentner + */ + private class IdGenerator { + + /** + * The salt. + */ + private String salt; + + /** + * The element name. + */ + private String elementName; + + /** + * The sequence number. + */ + private int i = 0; + + /** + * Creates a new instance of this IdGenerator with the given + * elementName and salt value. + * + * @param elementName the element name + * @param salt the salt valeu + */ + private IdGenerator(String elementName, String salt) { + super(); + this.elementName = elementName; + this.salt = salt; + } + + /** + * @return returns the next xsd:Id-attribute value. + */ + public String getNextId() { + return elementName + "-" + salt + "-" + Integer.toString(++i); + } + + } + + /** + * A map of element names to xsd:Id-value generators. + */ + private Map generators = new HashMap(); + + /** + * The seed value. + */ + private String seed; + + /** + * Creates a new instance of this IdValueFactory. + */ + public IdValueFactoryImpl() { + + Random random = new Random(); + int rand = random.nextInt(); + seed = Integer.toHexString(rand); + + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egiz.bku.slcommands.impl.IdValueFactory#createIdValue(java.lang.String + * ) + */ + public String createIdValue(String elementName) { + + IdGenerator generator = generators.get(elementName); + if (generator == null) { + generator = new IdGenerator(elementName, seed); + generators.put(elementName, generator); + } + return generator.getNextId(); + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java new file mode 100644 index 00000000..a6399c9b --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java @@ -0,0 +1,113 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.xml.crypto.Data; +import javax.xml.crypto.OctetStreamData; +import javax.xml.crypto.URIDereferencer; +import javax.xml.crypto.URIReference; +import javax.xml.crypto.URIReferenceException; +import javax.xml.crypto.XMLCryptoContext; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.bku.utils.urldereferencer.StreamData; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; + +/** + * An URIDereferencer implementation that dereferences LocRef + * references. + * + * @author mcentner + */ +public class LocRefDereferencer implements URIDereferencer { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(LocRefDereferencer.class); + + /** + * The LocRef-reference to be dereferenced by + * {@link #dereference(URIReference, XMLCryptoContext)}. + */ + protected String locRef; + + /** + * The context to be used for dereferencing. + */ + protected URLDereferencerContext dereferencerContext; + + /** + * Creates a new instance of this LocRefDereferencer with the given + * dereferencerContext and locRef reference. + * + * @param dereferencerContext + * the context to be used for dereferencing + * @param locRef + * the LocRef-reference (must be an absolute URI) + * + * @throws URISyntaxException + * if LocRef is not an absolute URI + */ + public LocRefDereferencer(URLDereferencerContext dereferencerContext, + String locRef) throws URISyntaxException { + + this.dereferencerContext = dereferencerContext; + + URI locRefUri = new URI(locRef); + if (locRefUri.isAbsolute()) { + this.locRef = locRef; + } else { + throw new IllegalArgumentException( + "Parameter 'locRef' must be an absolut URI."); + } + } + + /* + * (non-Javadoc) + * + * @see + * javax.xml.crypto.URIDereferencer#dereference(javax.xml.crypto.URIReference, + * javax.xml.crypto.XMLCryptoContext) + */ + @Override + public Data dereference(URIReference uriReference, XMLCryptoContext context) + throws URIReferenceException { + + URLDereferencer dereferencer = URLDereferencer.getInstance(); + StreamData streamData; + try { + streamData = dereferencer.dereference(locRef, dereferencerContext); + } catch (IOException e) { + log.info("Failed to dereference URI'" + locRef + "'. " + e.getMessage(), + e); + throw new URIReferenceException("Failed to dereference URI '" + locRef + + "'. " + e.getMessage(), e); + } + + return new OctetStreamData(streamData.getStream(), locRef, streamData + .getContentType()); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java new file mode 100644 index 00000000..64c758c9 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java @@ -0,0 +1,122 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.security.PrivateKey; + +import at.gv.egiz.stal.STAL; +import at.gv.egiz.stal.HashDataInputCallback; + +/** + * This class implements a private key used by the {@link STALSignature} class. + * + * @author mcentner + */ +public class STALPrivateKey implements PrivateKey { + + private static final long serialVersionUID = 1L; + + /** + * The STAL implementation. + */ + private STAL stal; + + /** + * The callback interface for obtaining the hash input data. + */ + private HashDataInputCallback hashDataInputCallback; + + /** + * The keybox identifier. + */ + private String keyboxIdentifier; + + /** + * The signature algorithm. + */ + private String algorithm; + + /** + * Creates a new instance of this STALPrivateKey with the given + * stal implementation, signature algorithm, + * keyboxIdentifier and hashDataInputCallback + * interface. + * + * @param stal + * the STAL implementation + * @param algorithm + * the signature algorithm + * @param keyboxIdentifier + * the keybox identifier + * @param hashDataInputCallback + * the interface for obtaining the has input data + */ + public STALPrivateKey(STAL stal, + String algorithm, String keyboxIdentifier, HashDataInputCallback hashDataInputCallback) { + super(); + this.keyboxIdentifier = keyboxIdentifier; + this.hashDataInputCallback = hashDataInputCallback; + this.stal = stal; + this.algorithm = algorithm; + } + + /* (non-Javadoc) + * @see java.security.Key#getAlgorithm() + */ + @Override + public String getAlgorithm() { + return algorithm; + } + + /* (non-Javadoc) + * @see java.security.Key#getEncoded() + */ + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("STALPrivateKey does not support the getEncoded() method."); + } + + /* (non-Javadoc) + * @see java.security.Key#getFormat() + */ + @Override + public String getFormat() { + return null; + } + + /** + * @return the STAL implementation + */ + public STAL getStal() { + return stal; + } + + /** + * @return the interface for obtaining the hash data input + */ + public HashDataInputCallback getHashDataInputCallback() { + return hashDataInputCallback; + } + + /** + * @return the keybox identifier + */ + public String getKeyboxIdentifier() { + return keyboxIdentifier; + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java new file mode 100644 index 00000000..0ab30530 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java @@ -0,0 +1,64 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import iaik.xml.crypto.XmldsigMore; + +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.Provider; +import java.security.Signature; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.crypto.dsig.SignatureMethod; + +/** + * A security provider implementation that provides {@link Signature} implementations + * based on STAL. + * + * @author mcentner + */ +public class STALProvider extends Provider { + + private static final long serialVersionUID = 1L; + + private static String IMPL_PACKAGE_NAME = "at.gv.egiz.bku.slcommands.impl.xsect"; + + public STALProvider() { + + super("STAL", 1.0, "Security Token Abstraction Layer Provider"); + + final Map map = new HashMap(); + + // TODO: register further algorithms + map.put("Signature." + SignatureMethod.RSA_SHA1, + IMPL_PACKAGE_NAME + ".STALSignature"); + map.put("Signature." + XmldsigMore.SIGNATURE_ECDSA_SHA1, + IMPL_PACKAGE_NAME + ".STALSignature"); + + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Void run() { + putAll(map); + return null; + } + }); + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java new file mode 100644 index 00000000..f0fcb891 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java @@ -0,0 +1,165 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.io.ByteArrayOutputStream; +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SignatureException; +import java.security.SignatureSpi; +import java.util.Collections; +import java.util.List; + +import at.gv.egiz.stal.ErrorResponse; +import at.gv.egiz.stal.STAL; +import at.gv.egiz.stal.STALRequest; +import at.gv.egiz.stal.STALResponse; +import at.gv.egiz.stal.SignRequest; +import at.gv.egiz.stal.SignResponse; +import at.gv.egiz.stal.HashDataInputCallback; + +/** + * A signature service provider implementation that uses STAL to sign. + * + * @author mcentner + */ +public class STALSignature extends SignatureSpi { + + /** + * The private key. + */ + protected STALPrivateKey privateKey; + + /** + * The to-be signed data. + */ + protected ByteArrayOutputStream data = new ByteArrayOutputStream(); + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineGetParameter(java.lang.String) + */ + @Override + protected Object engineGetParameter(String param) + throws InvalidParameterException { + throw new InvalidParameterException(); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineInitSign(java.security.PrivateKey) + */ + @Override + protected void engineInitSign(PrivateKey privateKey) + throws InvalidKeyException { + + if (!(privateKey instanceof STALPrivateKey)) { + throw new InvalidKeyException("STALSignature supports STALKeys only."); + } + + this.privateKey = (STALPrivateKey) privateKey; + + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineInitVerify(java.security.PublicKey) + */ + @Override + protected void engineInitVerify(PublicKey publicKey) + throws InvalidKeyException { + + throw new UnsupportedOperationException("STALSignature does not support signature verification."); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineSetParameter(java.lang.String, java.lang.Object) + */ + @Override + protected void engineSetParameter(String param, Object value) + throws InvalidParameterException { + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineSign() + */ + @Override + protected byte[] engineSign() throws SignatureException { + + STAL stal = privateKey.getStal(); + + if (stal == null) { + throw new SignatureException("STALSignature requires the STALPrivateKey " + + "to provide a STAL implementation reference."); + } + + HashDataInputCallback signRefDataSupplier = privateKey.getHashDataInputCallback(); + + String keyboxIdentifier = privateKey.getKeyboxIdentifier(); + + if (keyboxIdentifier == null) { + throw new SignatureException("STALSignature requires the STALPrivateKey " + + "to provide a KeyboxIdentifier."); + } + + SignRequest signRequest = new SignRequest(); + signRequest.setKeyIdentifier(keyboxIdentifier); + signRequest.setSignedInfo(data.toByteArray()); + signRequest.setHashDataInput(signRefDataSupplier); + + List responses = stal.handleRequest(Collections.singletonList((STALRequest) signRequest)); + + if (responses == null || responses.size() != 1) { + throw new SignatureException("Failed to access STAL."); + } + + STALResponse response = responses.get(0); + if (response instanceof SignResponse) { + return ((SignResponse) response).getSignatureValue(); + } else if (response instanceof ErrorResponse) { + throw new STALSignatureException(((ErrorResponse) response).getErrorCode()); + } else { + throw new SignatureException("Failed to access STAL."); + } + + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineUpdate(byte) + */ + @Override + protected void engineUpdate(byte b) throws SignatureException { + data.write(b); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineUpdate(byte[], int, int) + */ + @Override + protected void engineUpdate(byte[] b, int off, int len) + throws SignatureException { + data.write(b, off, len); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineVerify(byte[]) + */ + @Override + protected boolean engineVerify(byte[] sigBytes) throws SignatureException { + throw new UnsupportedOperationException("STALSignature des not support signature verification."); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureException.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureException.java new file mode 100644 index 00000000..4e86b07c --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureException.java @@ -0,0 +1,92 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.security.SignatureException; + +/** + * A SignatureException thrown by the {@link STALSignature}. + * + * @author mcentner + */ +public class STALSignatureException extends SignatureException { + + private static final long serialVersionUID = 1L; + + /** + * The STAL error code. + */ + private int errorCode; + + /** + * Creates a new instance of this STALSignatureException. + */ + public STALSignatureException() { + } + + /** + * Creates a new instance of this STALSigantureException with + * the given errorCode. + * + * @param errorCode the error code + */ + public STALSignatureException(int errorCode) { + this.errorCode = errorCode; + } + + /** + * Creates a new instance of this STALSignatureException with + * the given error msg. + * + * @param msg the error message + * @see SignatureException#SignatureException(String) + */ + public STALSignatureException(String msg) { + super(msg); + } + + /** + * Creates a new instance of this STALSignatureException with + * the given root cause. + * + * @param cause the cause + * @see SignatureException#SignatureException(Throwable) + */ + public STALSignatureException(Throwable cause) { + super(cause); + } + + /** + * Creates a new instance of this STALSignautureException with + * the given error message and root cause. + * + * @param message the error message + * @param cause the cause + * @see SignatureException#SignatureException(String, Throwable) + */ + public STALSignatureException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @return the error code + */ + public int getErrorCode() { + return errorCode; + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java new file mode 100644 index 00000000..94a4a066 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java @@ -0,0 +1,935 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.security.InvalidAlgorithmParameterException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.dom.DOMStructure; +import javax.xml.crypto.dsig.CanonicalizationMethod; +import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.dsig.Reference; +import javax.xml.crypto.dsig.SignatureMethod; +import javax.xml.crypto.dsig.SignedInfo; +import javax.xml.crypto.dsig.XMLObject; +import javax.xml.crypto.dsig.XMLSignature; +import javax.xml.crypto.dsig.XMLSignatureException; +import javax.xml.crypto.dsig.XMLSignatureFactory; +import javax.xml.crypto.dsig.dom.DOMSignContext; +import javax.xml.crypto.dsig.keyinfo.KeyInfo; +import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; +import javax.xml.crypto.dsig.keyinfo.X509Data; +import javax.xml.stream.XMLStreamException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.etsi.uri._01903.v1_1.DataObjectFormatType; +import org.etsi.uri._01903.v1_1.QualifyingPropertiesType; +import org.w3c.dom.DOMConfiguration; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSException; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSParser; +import org.w3c.dom.ls.LSResourceResolver; +import org.w3c.dom.ls.LSSerializer; + +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLLocRefReqRefContentType; +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLOptRefContentType; +import at.buergerkarte.namespaces.securitylayer._1.DataObjectAssociationType; +import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; +import at.buergerkarte.namespaces.securitylayer._1.SignatureInfoCreationType; +import at.gv.egiz.bku.binding.HttpUtil; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLRequestException; +import at.gv.egiz.bku.utils.HexDump; +import at.gv.egiz.bku.utils.urldereferencer.StreamData; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; +import at.gv.egiz.dom.DOMUtils; +import at.gv.egiz.slbinding.impl.XMLContentType; +import at.gv.egiz.stal.HashDataInputCallback; +import at.gv.egiz.stal.STAL; +import at.gv.egiz.xades.QualifyingPropertiesException; +import at.gv.egiz.xades.QualifyingPropertiesFactory; + +/** + * This class represents an XML-Signature as to be created by the + * security layer command CreateXMLSignatureRequest. + * + * @author mcentner + */ +public class Signature implements HashDataInputCallback { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(Signature.class); + + /** + * The DOM implementation used. + */ + private DOMImplementationLS domImplLS; + + /** + * The SignatureContext for the XMLSignature. + */ + private SignatureContext ctx; + + /** + * The list of {@link DataObject}s for this signature. + */ + private List dataObjects = new ArrayList(); + + /** + * A mapping from the Id-attribute values of this signature's + * ds:References to the corresponding {@link DataObject}s. + */ + private Map dataObjectReferencIds = new HashMap(); + + /** + * The SignatureEnvironment for this signature. + */ + private SignatureLocation signatureLocation; + + /** + * The XML signature. + */ + private XMLSignature xmlSignature; + + /** + * A list of attributes of type xsd:ID to be registered in the {@link DOMSignContext}. + */ + private List idAttributes = new ArrayList(); + + /** + * The signer's X509 certificate. + */ + private X509Certificate signerCertificate; + + /** + * The signing time. + */ + private Date signingTime; + + /** + * Creates a new SLXMLSignature instance. + */ + public Signature(URLDereferencerContext dereferencerContext, + IdValueFactory idValueFactory, + AlgorithmMethodFactory algorithmMethodFactory) { + + domImplLS = DOMUtils.getDOMImplementationLS(); + + ctx = new SignatureContext(); + + ctx.setSignatureFactory(XMLSignatureFactory.getInstance()); + + ctx.setDereferencerContext(dereferencerContext); + ctx.setIdValueFactory(idValueFactory); + ctx.setAlgorithmMethodFactory(algorithmMethodFactory); + + } + + /** + * @return the Document containing this Signature + */ + public Document getDocument() { + return ctx.getDocument(); + } + + /** + * @return the parent Node for this Signature + */ + public Node getParent() { + return (signatureLocation != null) ? signatureLocation.getParent() : null; + } + + /** + * @return the next sibling Node for this Signature + */ + public Node getNextSibling() { + return (signatureLocation != null) ? signatureLocation.getNextSibling() : null; + } + + /** + * @return the XMLSignature + */ + public XMLSignature getXMLSignature() { + return xmlSignature; + } + + /** + * @return the list of {@link Reference}s of this Signature + */ + @SuppressWarnings("unchecked") + public List getReferences() { + return (xmlSignature != null) ? xmlSignature.getSignedInfo().getReferences() : null; + } + + /** + * @return the list of {@link XMLObject}s of this Signature + */ + @SuppressWarnings("unchecked") + public List getXMLObjects() { + return (xmlSignature != null) ? xmlSignature.getObjects() : null; + } + + /** + * Prepares the signature document with the information given by the + * signatureInfo provided. + * + * @param signatureInfo + * the SignatureInfo + * + * @throws SLCommandException + * if processing fails for any reason + * @throws IllegalStateException + * if the parent node has already been set + * @throws NullPointerException + * if signatureInfo is null + */ + public void setSignatureInfo(SignatureInfoCreationType signatureInfo) throws SLCommandException { + + if (signatureLocation != null) { + throw new IllegalStateException("SignatureEnvironment already set."); + } + + Base64XMLOptRefContentType signatureEnvironment = signatureInfo.getSignatureEnvironment(); + + if (signatureEnvironment == null) { + + // no SignatureEnvironment, so we use an empty document and the document as parent + ensureSignatureLocation(); + + } else { + + // parse SignatureEnvrionment and use as document + Document document = parseSignatureEnvironment(signatureEnvironment, signatureInfo.getSupplement()); + ctx.setDocument(document); + + signatureLocation = new SignatureLocation(ctx); + signatureLocation.setSignatureInfo(signatureInfo); + + } + + } + + /** + * Ensures a SignatureLocation for this Signature. + */ + private void ensureSignatureLocation() { + + if (signatureLocation == null) { + Document document = DOMUtils.createDocument(); + ctx.setDocument(document); + + signatureLocation = new SignatureLocation(ctx); + signatureLocation.setParent(document); + } + + } + + /** + * Adds a DataObject with the information given by the + * dataObjectInfo provided to this Signature. + * + * @param dataObjectInfo + * the DataObjectInfo element + * + * @throws SLCommandException + * if adding the DataObject fails + * @throws SLRequestException + * if the information provided by the given + * dataObjectInfo does not conform to the security + * layer specification + * @throws NullPointerException + * if dataObjectInfo is null + */ + public void addDataObject(DataObjectInfoType dataObjectInfo) throws SLCommandException, SLRequestException { + + ensureSignatureLocation(); + + DataObject dataObject = new DataObject(ctx); + dataObject.setDataObjectInfo(dataObjectInfo); + + dataObjects.add(dataObject); + + dataObjectReferencIds.put(dataObject.getReference().getId(), dataObject); + + } + + /** + * Sets the SigningTime qualifying property of this Signature. + * + * @param signingTime the signing time to set + */ + public void setSigningTime(Date signingTime) { + this.signingTime = signingTime; + } + + /** + * Sets the SignerCertificate qualifying property of this Signature. + * + * @param certificate the signer's certificate + */ + public void setSignerCeritifcate(X509Certificate certificate) { + this.signerCertificate = certificate; + } + + /** + * Builds the XMLSignature data structure of this Signature as configured by + * the various setter methods. + * + * @throws SLCommandException if building this signature fails + */ + public void buildXMLSignature() throws SLCommandException { + + List objects = new ArrayList(); + List references = new ArrayList(); + + // add all data objects + for (DataObject dataObject : dataObjects) { + if (dataObject.getXmlObject() != null) { + objects.add(dataObject.getXmlObject()); + } + if (dataObject.getReference() != null) { + references.add(dataObject.getReference()); + } + } + + addXAdESObjectAndReference(objects, references); + + XMLSignatureFactory signatureFactory = ctx.getSignatureFactory(); + AlgorithmMethodFactory algorithmMethodFactory = ctx.getAlgorithmMethodFactory(); + + CanonicalizationMethod cm; + SignatureMethod sm; + try { + cm = algorithmMethodFactory.createCanonicalizationMethod(ctx); + sm = algorithmMethodFactory.createSignatureMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get Canonicalization or Signature algorithm.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get Canonicalization or Signature algorithm.", e); + throw new SLCommandException(4006); + } + + String siId = ctx.getIdValueFactory().createIdValue("SignedInfo"); + + SignedInfo si = signatureFactory.newSignedInfo(cm, sm, references, siId); + + KeyInfo ki = null; + if (signerCertificate != null) { + KeyInfoFactory kif = KeyInfoFactory.getInstance(); + X509Data x509Data = kif.newX509Data(Collections.singletonList(signerCertificate)); + ki = kif.newKeyInfo(Collections.singletonList(x509Data)); + } + + String signatureId = ctx.getIdValueFactory().createIdValue("Signature"); + String signatureValueId = ctx.getIdValueFactory().createIdValue("SignatureValue"); + + xmlSignature = signatureFactory.newXMLSignature(si, ki, objects, signatureId, signatureValueId); + + } + + /** + * Sign this Signature using the given signContext. + *

+ * Call's {@link #buildXMLSignature()} if it has not been called yet. + *

+ * + * @param signContext + * the signing context + * + * @throws MarshalException + * if marshalling the XMLSignature fails + * @throws XMLSignatureException + * if signing the XMLSignature fails + * @throws SLCommandException + * if building the XMLSignature fails + * @throws NullPointerException + * if signContext is null + */ + public void sign(DOMSignContext signContext) throws MarshalException, XMLSignatureException, SLCommandException { + + if (xmlSignature == null) { + buildXMLSignature(); + } + + for (IdAttribute idAttribute : idAttributes) { + signContext.setIdAttributeNS(idAttribute.element, idAttribute.namespaceURI, idAttribute.localName); + } + + // DO NOT USE: + // signContext.setProperty("iaik.xml.crypto.dsig.sign-over", Boolean.TRUE); + + signContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); + + signContext.putNamespacePrefix(XMLSignature.XMLNS, "dsig"); + + signContext.setURIDereferencer(new URIDereferncerAdapter(ctx.getDereferencerContext())); + + try { + xmlSignature.sign(signContext); + } catch (XMLSignatureException e) { + Throwable cause = e.getCause(); + while (cause != null) { + if (cause instanceof STALSignatureException) { + int errorCode = ((STALSignatureException) cause).getErrorCode(); + SLCommandException commandException = new SLCommandException(errorCode); + log.info("Failed to sign signature.", commandException); + throw commandException; + } else { + cause = cause.getCause(); + } + } + throw e; + } + + // debug + if (log.isTraceEnabled()) { + for (DataObject dataObject : dataObjects) { + Reference reference = dataObject.getReference(); + InputStream digestInputStream = reference.getDigestInputStream(); + if (digestInputStream != null) { + String mimeType = dataObject.getMimeType(); + StringBuilder sb = new StringBuilder(); + sb.append("DigestInput for Reference with id='"); + sb.append(reference.getId()); + sb.append("' (MIME-Type="); + sb.append(dataObject.getMimeType()); + sb.append("):\n"); + try { + if (mimeType != null && ( + mimeType.startsWith("text") || + "application/xhtml+xml".equals(mimeType))) { + byte[] b = new byte[512]; + for (int l; (l = digestInputStream.read(b)) != -1;) { + sb.append(new String(b, 0, l)); + } + } else { + sb.append(HexDump.hexDump(digestInputStream)); + } + } catch (IOException e) { + log.error(e); + } + log.trace(sb.toString()); + } else { + log.trace("Reference caching is not enabled."); + } + } + } + + } + + /** + * Sign this Signature using the given stal implementation and + * keyboxIdentifier. + *

+ * This method configures an appropriate {@link DOMSignContext} and calls + * {@link #sign(DOMSignContext)}. If {@link #buildXMLSignature()} has not been + * called yet, it is called by this method. + *

+ * + * @param stal + * the STAL implementation to use + * @param keyboxIdentifier + * the KeyboxIdentifier to use + * + * @throws MarshalException + * if marshalling this Signature fails + * @throws XMLSignatureException + * if signing this Signature fails + * @throws SLCommandException + * if building this Signature fails + * @throws NullPointerException + * if stal or keyboxIdentifier is + * null + */ + public void sign(STAL stal, String keyboxIdentifier) throws MarshalException, XMLSignatureException, SLCommandException { + + if (stal == null) { + throw new NullPointerException("Argument 'stal' must not be null."); + } + + if (keyboxIdentifier == null) { + throw new NullPointerException("Argument 'keyboxIdentifier' must not be null."); + } + + if (xmlSignature == null) { + buildXMLSignature(); + } + + SignatureMethod signatureMethod = xmlSignature.getSignedInfo().getSignatureMethod(); + String algorithm = signatureMethod.getAlgorithm(); + + PrivateKey privateKey = new STALPrivateKey(stal, algorithm, keyboxIdentifier, this); + + DOMSignContext signContext; + if (getNextSibling() == null) { + signContext = new DOMSignContext(privateKey, getParent()); + } else { + signContext = new DOMSignContext(privateKey, getParent(), getNextSibling()); + } + + sign(signContext); + } + + @Override + public InputStream getHashDataInput(String referenceId) { + + DataObject dataObject = dataObjectReferencIds.get(referenceId); + if (dataObject != null) { + return dataObject.getReference().getDigestInputStream(); + } else { + return null; + } + } + + /** + * Adds the XAdES QualifyingProperties as an + * ds:Object and a corresponding ds:Reference to + * it's SignedProperties element to this Signature. + * + * @param objects + * the list of ds:Objects to add the created + * ds:Object to + * @param references + * the list of ds:References to add the created + * ds:Reference to + * + * @throws SLCommandException + * if creating and adding the XAdES + * QualifyingProperties fails + * @throws NullPointerException + * if objects or references is + * null + */ + private void addXAdESObjectAndReference(List objects, List references) throws SLCommandException { + + QualifyingPropertiesFactory factory = QualifyingPropertiesFactory.getInstance(); + + String idValue = ctx.getIdValueFactory().createIdValue("SignedProperties"); + + Date date = (signingTime != null) ? signingTime : new Date(); + + List signingCertificates; + if (signerCertificate != null) { + signingCertificates = Collections.singletonList(signerCertificate); + } else { + signingCertificates = Collections.emptyList(); + } + + // TODO: report MOA-SP bug + // + // The security layer specification mandates the use of version 1.2.2. of the + // XAdES QualifyingProperties. However MOA-SP supports only version 1.1.1. Therefore, + // the version 1.1.1 is used in order to be compatible with current MOA-SP versions. + + List dataObjectFormats = new ArrayList(); + for (DataObject dataObject : dataObjects) { + if (dataObject.getMimeType() != null && dataObject.getReference() != null) { + Reference reference = dataObject.getReference(); + if (reference.getId() != null) { + String objectReference = "#" + reference.getId(); + dataObjectFormats.add(factory.createDataObjectFormatType( + objectReference, dataObject.getMimeType(), dataObject + .getDescription())); + } + } + } + + JAXBElement qualifyingProperties; + try { + qualifyingProperties = factory.createQualifyingProperties111(date, signingCertificates, idValue, dataObjectFormats); + } catch (QualifyingPropertiesException e) { + log.error("Failed to create QualifyingProperties.", e); + throw new SLCommandException(4000); + } + + DocumentFragment fragment = ctx.getDocument().createDocumentFragment(); + + try { + factory.marshallQualifyingProperties(qualifyingProperties, fragment); + } catch (JAXBException e) { + log.error("Failed to marshal QualifyingProperties.", e); + throw new SLCommandException(4000); + } + + List content = Collections.singletonList(new DOMStructure(fragment.getFirstChild())); + + String objectIdValue = ctx.getIdValueFactory().createIdValue("Object"); + + XMLObject object = ctx.getSignatureFactory().newXMLObject(content, objectIdValue, null, null); + + objects.add(object); + + // TODO: Report MOA-SP Bug + // + // Direct referencing of the SignedPorperties Id-attribute is not supported by MOA-SP + // because the QualifyingProperties are parsed without the XAdES schema. Therefore, + // the shorthand XPointer could not be resolved. + // + // The following workaround uses an XPointer to select the SignedProperties in order + // to allow the signature to be verified with MOA-SP. + + String referenceURI = "#xmlns(xades=http://uri.etsi.org/01903/v1.1.1%23)%20xpointer(id('" + + objectIdValue + + "')/child::xades:QualifyingProperties/child::xades:SignedProperties)"; + DigestMethod dm; + try { + dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod algorithm.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get DigestMethod algorithm.", e); + throw new SLCommandException(4006); + } + + String referenceIdValue = ctx.getIdValueFactory().createIdValue("Reference"); + String referenceType = QualifyingPropertiesFactory.SIGNED_PROPERTIES_REFERENCE_TYPE_V1_1_1; + + Reference reference = ctx.getSignatureFactory().newReference(referenceURI, dm, null, referenceType, referenceIdValue); + + references.add(reference); + + Node child = fragment.getFirstChild(); + if (child instanceof Element) { + NodeList nodes = ((Element) child).getElementsByTagNameNS(QualifyingPropertiesFactory.NS_URI_V1_1_1, "SignedProperties"); + if (nodes.getLength() > 0) { + IdAttribute idAttribute = new IdAttribute(); + idAttribute.element = (Element) nodes.item(0); + idAttribute.namespaceURI = null; + idAttribute.localName = "Id"; + idAttributes.add(idAttribute); + } + } + + } + + /** + * Parse the SignatureEnvironment. + * + * @param signatureEnvironment + * the SignatureEnvironment element + * @param supplements + * an optional list of Supplements (may be + * null) + * + * @return the parsed SignatureEnvironment document + * + * @throws SLCommandException + * if parsing the SignatureEnvironment fails + * @throws NullPointerException + * if signatureEnvironment is null + */ + private Document parseSignatureEnvironment( + Base64XMLOptRefContentType signatureEnvironment, + List supplements) throws SLCommandException { + + if (signatureEnvironment == null) { + throw new NullPointerException("Argument 'signatureEnvironment' must not be null."); + } + + LSInput input; + try { + if (signatureEnvironment.getReference() != null) { + log.debug("SignatureEnvironment contains Reference " + signatureEnvironment.getReference() + "."); + input = createLSInput(signatureEnvironment.getReference()); + } else if (signatureEnvironment.getBase64Content() != null) { + log.debug("SignatureEnvironment contains Base64Content."); + input = createLSInput(signatureEnvironment.getBase64Content()); + } else if (signatureEnvironment.getXMLContent() != null) { + log.debug("SignatureEnvironment contains XMLContent."); + input = createLSInput((XMLContentType) signatureEnvironment.getXMLContent()); + } else { + // the schema does not allow us to reach this point + throw new SLCommandException(4000); + } + } catch (IOException e) { + log.info("XML document in which the signature is to be integrated cannot be resolved.", e); + throw new SLCommandException(4100); + } catch (XMLStreamException e) { + log.info("XML document in which the signature is to be integrated cannot be resolved.", e); + throw new SLCommandException(4100); + } + + LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); + DOMConfiguration domConfig = parser.getDomConfig(); + SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); + domConfig.setParameter("error-handler", errorHandler); + LSResourceResolverAdapter resourceResolver = new LSResourceResolverAdapter(supplements); + domConfig.setParameter("resource-resolver", resourceResolver); + domConfig.setParameter("validate", Boolean.TRUE); + + Document doc; + try { + doc = parser.parse(input); + } catch (DOMException e) { + log.info("XML document in which the signature is to be integrated cannot be parsed.", e); + throw new SLCommandException(4101); + } catch (LSException e) { + log.info("XML document in which the signature is to be integrated cannot be parsed.", e); + throw new SLCommandException(4101); + } + + if (resourceResolver.getError() != null) { + log.info("Failed to resolve resource while parsing SignatureEnvironment document.", resourceResolver.getError()); + // we don't stop here, as we only _try_ to parse validating + } + + if (errorHandler.hasFatalErrors()) { + // log fatal errors + if (log.isInfoEnabled()) { + List errorMessages = errorHandler.getErrorMessages(); + StringBuffer sb = new StringBuffer(); + for (String errorMessage : errorMessages) { + sb.append(" "); + sb.append(errorMessage); + } + log.info("XML document in which the signature is to be integrated cannot be parsed." + sb.toString()); + } + throw new SLCommandException(4101); + } + + // log parsed document + if (log.isTraceEnabled()) { + + StringWriter writer = new StringWriter(); + + writer.write("SignatureEnvironment:\n"); + + LSOutput output = domImplLS.createLSOutput(); + output.setCharacterStream(writer); + output.setEncoding("UTF-8"); + LSSerializer serializer = domImplLS.createLSSerializer(); + serializer.write(doc, output); + + log.trace(writer.toString()); + } + + return doc; + + } + + /** + * Creates an LSInput from the given reference URI. + * + * @param reference + * the reference URL + * + * @return an LSInput from the given reference URI + * + * @throws IOException + * if dereferencing the given reference fails + */ + private LSInput createLSInput(String reference) throws IOException { + + URLDereferencer urlDereferencer = URLDereferencer.getInstance(); + StreamData streamData = urlDereferencer.dereference(reference, ctx.getDereferencerContext()); + + String contentType = streamData.getContentType(); + String charset = HttpUtil.getCharset(contentType, true); + InputStreamReader streamReader; + try { + streamReader = new InputStreamReader(streamData.getStream(), charset); + } catch (UnsupportedEncodingException e) { + log.info("Charset " + charset + " not supported. Using default."); + streamReader = new InputStreamReader(streamData.getStream()); + } + + LSInput input = domImplLS.createLSInput(); + input = domImplLS.createLSInput(); + input.setCharacterStream(streamReader); + + return input; + + } + + /** + * Creates an LSInput from the given content bytes. + * + * @param content + * the content bytes + * + * @return an LSInput from the givne content bytes + */ + private LSInput createLSInput(byte[] content) { + + ByteArrayInputStream inputStream = new ByteArrayInputStream(content); + LSInput input = domImplLS.createLSInput(); + input.setByteStream(inputStream); + + return input; + + } + + /** + * Creates an LSInput from the given XML content. + * + * @param content + * the XML content + * @return an LSInput from the given XML content + * + * @throws XMLStreamException + * if reading the XMLStream from the given XML content fails + */ + private LSInput createLSInput(XMLContentType content) throws XMLStreamException { + + ByteArrayOutputStream redirectedStream = content.getRedirectedStream(); + if (redirectedStream != null) { + LSInput input = domImplLS.createLSInput(); + input.setByteStream(new ByteArrayInputStream(redirectedStream.toByteArray())); + return input; + } else { + return null; + } + + } + + /** + * Represents an xsd:Id-attribute value. + * + * @author mcentner + */ + private class IdAttribute { + + private Element element; + + private String namespaceURI; + + private String localName; + + } + + /** + * An implementation of the LSResourceResolver that uses a list of supplements + * to resolve resources. + * + * @author mcentner + */ + private class LSResourceResolverAdapter implements LSResourceResolver { + + List supplements; + + private LSResourceResolverAdapter( + List supplements) { + this.supplements = supplements; + } + + private Exception error; + + /** + * @return the error + */ + public Exception getError() { + return error; + } + + @Override + public LSInput resolveResource(String type, String namespaceURI, + String publicId, String systemId, String baseURI) { + + if (log.isTraceEnabled()) { + log.trace("Resolve resource :" + + "\n type=" + type + + "\n namespaceURI=" + namespaceURI + + "\n publicId=" + publicId + + "\n systemId=" + systemId + + "\n baseURI=" + baseURI); + } + + if (systemId != null) { + + log.debug("Resolve resource '" + systemId + "'."); + + for (DataObjectAssociationType supplement : supplements) { + + Base64XMLLocRefReqRefContentType content = supplement.getContent(); + if (content != null) { + + String reference = content.getReference(); + if (systemId.equals(reference)) { + + try { + if (content.getLocRefContent() != null) { + log.trace("Resolved resource '" + reference + "' to supplement with LocRefContent."); + return createLSInput(content.getLocRefContent()); + } else if (content.getBase64Content() != null) { + log.trace("Resolved resource '" + reference + "' to supplement with Base64Content."); + return createLSInput(content.getBase64Content()); + } else if (content.getXMLContent() != null) { + log.trace("Resolved resource '" + reference + "' to supplement with XMLContent."); + return createLSInput((XMLContentType) content.getXMLContent()); + } else { + return null; + } + } catch (IOException e) { + log.info("Failed to resolve resource '" + systemId + "' to supplement.", e); + error = e; + return null; + } catch (XMLStreamException e) { + log.info("Failed to resolve resource '" + systemId + "' to supplement.", e); + error = e; + return null; + } + + } + + } + + } + + log.info("Failed to resolve resource '" + systemId + "' to supplement. No such supplement."); + + } + + return null; + + } + + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureContext.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureContext.java new file mode 100644 index 00000000..0925f2fd --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureContext.java @@ -0,0 +1,129 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.dsig.XMLSignatureFactory; + +import org.w3c.dom.Document; + +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; + +/** + * An instance of this class carries context information for a XML-Signature + * created by the security layer command CreateXMLSignature. + * + * @author mcentner + */ +public class SignatureContext { + + /** + * The document going to contain the XML signature. + */ + private Document document; + + /** + * The IdValueFactory used to create xsd:ID-attribute values. + */ + private IdValueFactory idValueFactory; + + /** + * The XMLSignatureFactory to create XML signature objects. + */ + private XMLSignatureFactory signatureFactory; + + /** + * The URLDereferencerContext for dereferencing URLs. + */ + private URLDereferencerContext dereferencerContext; + + /** + * The DigestMethodFactory to create {@link DigestMethod} objects. + */ + private AlgorithmMethodFactory digestMethodFactory; + + /** + * @return the document + */ + public Document getDocument() { + return document; + } + + /** + * @param document the document to set + */ + public void setDocument(Document document) { + this.document = document; + } + + /** + * @return the idValueFactory + */ + public IdValueFactory getIdValueFactory() { + return idValueFactory; + } + + /** + * @param idValueFactory the idValueFactory to set + */ + public void setIdValueFactory(IdValueFactory idValueFactory) { + this.idValueFactory = idValueFactory; + } + + /** + * @return the signatureFactory + */ + public XMLSignatureFactory getSignatureFactory() { + return signatureFactory; + } + + /** + * @param signatureFactory the signatureFactory to set + */ + public void setSignatureFactory(XMLSignatureFactory signatureFactory) { + this.signatureFactory = signatureFactory; + } + + /** + * @return the dereferencerContext + */ + public URLDereferencerContext getDereferencerContext() { + return dereferencerContext; + } + + /** + * @param dereferencerContext the dereferencerContext to set + */ + public void setDereferencerContext(URLDereferencerContext dereferencerContext) { + this.dereferencerContext = dereferencerContext; + } + + /** + * @return the digestMethodFactory + */ + public AlgorithmMethodFactory getAlgorithmMethodFactory() { + return digestMethodFactory; + } + + /** + * @param digestMethodFactory the digestMethodFactory to set + */ + public void setAlgorithmMethodFactory(AlgorithmMethodFactory digestMethodFactory) { + this.digestMethodFactory = digestMethodFactory; + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureLocation.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureLocation.java new file mode 100644 index 00000000..5ec02893 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureLocation.java @@ -0,0 +1,235 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.util.Iterator; + +import javax.xml.XMLConstants; +import javax.xml.namespace.NamespaceContext; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import at.buergerkarte.namespaces.securitylayer._1.SignatureInfoCreationType; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.slbinding.impl.SignatureLocationType; + +/** + * This class implements the SignatureLocation of an XML-Signature + * to be created by the security layer command CreateXMLSignature. + * + * @author mcentner + */ +public class SignatureLocation { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(SignatureLocation.class); + + /** + * The SignatureContext for the XML signature + */ + private SignatureContext ctx; + + /** + * The parent node for the XML signature. + */ + private Node parent; + + /** + * The next sibling node for the XML signature. + */ + private Node nextSibling; + + /** + * Creates a new SignatureLocation with the given signatureContext + * + * @param signatureContext the context for the XML signature creation + */ + public SignatureLocation(SignatureContext signatureContext) { + this.ctx = signatureContext; + } + + /** + * @return the parent node for the XML signature + */ + public Node getParent() { + return parent; + } + + /** + * @param parent the parent for the XML signature + */ + public void setParent(Node parent) { + this.parent = parent; + } + + /** + * @return the next sibling node for the XML signature + */ + public Node getNextSibling() { + return nextSibling; + } + + /** + * @param nextSibling the next sibling node for the XML signature + */ + public void setNextSibling(Node nextSibling) { + this.nextSibling = nextSibling; + } + + /** + * Configures this SignatureLocation with the information provided by the + * given SignatureInfo element. + * + * @param signatureInfo + * the SignatureInfo element + * + * @throws SLCommandException + * if configuring this SignatureLocation with given + * signatureInfofails + */ + public void setSignatureInfo(SignatureInfoCreationType signatureInfo) + throws SLCommandException { + + // evaluate signature location XPath ... + SignatureLocationType signatureLocation = (SignatureLocationType) signatureInfo + .getSignatureLocation(); + + NamespaceContext namespaceContext = new MOAIDWorkaroundNamespaceContext( + signatureLocation.getNamespaceContext()); + + parent = evaluateSignatureLocation(signatureInfo.getSignatureLocation() + .getValue(), namespaceContext, ctx.getDocument().getDocumentElement()); + + // ... and index + nextSibling = findNextSibling(parent, signatureInfo.getSignatureLocation() + .getIndex().intValue()); + + } + + /** + * Evaluates the given xpath with the document element as context node + * and returns the resulting node. + * + * @param xpath the XPath expression + * @param nsContext the namespace context of the XPath expression + * @param contextNode the context node for the XPath evaluation + * + * @return the result of evaluating the XPath expression + * + * @throws SLCommandException + */ + private Node evaluateSignatureLocation(String xpath, NamespaceContext nsContext, Node contextNode) throws SLCommandException { + + Node node = null; + try { + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xPath = xpathFactory.newXPath(); + xPath.setNamespaceContext(nsContext); + XPathExpression xpathExpr = xPath.compile(xpath); + node = (Node) xpathExpr.evaluate(contextNode, XPathConstants.NODE); + } catch (XPathExpressionException e) { + log.info("Failed to evaluate SignatureLocation XPath expression '" + xpath + "' on context node.", e); + throw new SLCommandException(4102); + } + + if (node == null) { + log.info("Failed to evaluate SignatureLocation XPath expression '" + xpath + "'. Result is empty."); + throw new SLCommandException(4102); + } + + return node; + + } + + /** + * Finds the next sibling node of the parent's n-th child node + * or null if there is no next sibling. + * + * @param parent the parent node + * @param n the index of the child node + * + * @return the next sibling node of the node specified by parent and index n, + * or null if there is no next sibling node. + * + * @throws SLCommandException if the n-th child of parent does not exist + */ + private Node findNextSibling(Node parent, int n) throws SLCommandException { + + NodeList childNodes = parent.getChildNodes(); + Node childNode = childNodes.item(n); + if (childNode == null) { + log.info("SingatureLocation Index '" + n + "' not found in document."); + throw new SLCommandException(4102); + } else { + return childNode.getNextSibling(); + } + + } + + /** + * Workaround for a missing namespace prefix declaration in MOA-ID. + * + * @author mcentner + */ + private class MOAIDWorkaroundNamespaceContext implements NamespaceContext { + + private NamespaceContext namespaceContext; + + public MOAIDWorkaroundNamespaceContext(NamespaceContext namespaceContext) { + super(); + this.namespaceContext = namespaceContext; + } + + @Override + public String getNamespaceURI(String prefix) { + + String namespaceURI = namespaceContext.getNamespaceURI(prefix); + + if ((namespaceURI == null || XMLConstants.NULL_NS_URI.equals(namespaceURI)) && "saml".equals(prefix)) { + namespaceURI = "urn:oasis:names:tc:SAML:1.0:assertion"; + log.debug("Namespace prefix '" + prefix + "' resolved to '" + namespaceURI + "' (MOA-ID Workaround)."); + } else { + log.trace("Namespace prefix '" + prefix + "' resolved to '" + namespaceURI + "'."); + } + + return namespaceURI; + } + + @Override + public String getPrefix(String namespaceURI) { + return namespaceContext.getPrefix(namespaceURI); + } + + @SuppressWarnings("unchecked") + @Override + public Iterator getPrefixes(String namespaceURI) { + return namespaceContext.getPrefixes(namespaceURI); + } + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SimpleDOMErrorHandler.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SimpleDOMErrorHandler.java new file mode 100644 index 00000000..0d54adce --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SimpleDOMErrorHandler.java @@ -0,0 +1,98 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.util.ArrayList; +import java.util.List; + +import org.w3c.dom.DOMError; +import org.w3c.dom.DOMErrorHandler; + +/** + * A simple DOMErrorHandler implementation. + * + * @author mcentner + */ +public class SimpleDOMErrorHandler implements DOMErrorHandler { + + /** + * Have there been errors reported? + */ + private boolean errors = false; + + /** + * Have there been fatal error reported? + */ + private boolean fatalErrors = false; + + /** + * The list of error messages of reported errors. + */ + private List errorMessages = new ArrayList(); + + /** + * @return true if errors have been reported, or false otherwise + */ + public boolean hasErrors() { + return errors; + } + + /** + * @return true if fatal errors have been reported, or false otherwise + */ + public boolean hasFatalErrors() { + return fatalErrors; + } + + /** + * @return a list of error messages that have been reported + */ + public List getErrorMessages() { + return errorMessages; + } + + /* (non-Javadoc) + * @see org.w3c.dom.DOMErrorHandler#handleError(org.w3c.dom.DOMError) + */ + @Override + public boolean handleError(DOMError error) { + + switch (error.getSeverity()) { + + case DOMError.SEVERITY_WARNING : +// log.debug("[warning] " + error.getMessage()); + return true; + + case DOMError.SEVERITY_ERROR : +// log.debug("[error] " + error.getMessage()); + errorMessages.add(error.getMessage()); + errors = true; + return false; + + case DOMError.SEVERITY_FATAL_ERROR : +// log.debug("[fatal error] " + error.getMessage()); + errorMessages.add(error.getMessage()); + fatalErrors = true; + return false; + + default: + return false; + } + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/URIDereferncerAdapter.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/URIDereferncerAdapter.java new file mode 100644 index 00000000..c94937be --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/URIDereferncerAdapter.java @@ -0,0 +1,103 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import iaik.xml.crypto.utils.URIDereferencerImpl; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.xml.crypto.Data; +import javax.xml.crypto.OctetStreamData; +import javax.xml.crypto.URIDereferencer; +import javax.xml.crypto.URIReference; +import javax.xml.crypto.URIReferenceException; +import javax.xml.crypto.XMLCryptoContext; + +import at.gv.egiz.bku.utils.urldereferencer.StreamData; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; + +/** + * An URIDereferencer implementation that uses an {@link URLDereferencer} to + * dereference. + * + * @author mcentner + */ +public class URIDereferncerAdapter implements URIDereferencer { + + /** + * The context for dereferencing. + */ + protected URLDereferencerContext urlDereferencerContext; + + /** + * Creates a new URIDereferencerAdapter instance with the given + * urlDereferencerContext. + * + * @param urlDereferencerContext the context to be used for dereferencing + */ + public URIDereferncerAdapter(URLDereferencerContext urlDereferencerContext) { + super(); + this.urlDereferencerContext = urlDereferencerContext; + } + + /* (non-Javadoc) + * @see javax.xml.crypto.URIDereferencer#dereference(javax.xml.crypto.URIReference, javax.xml.crypto.XMLCryptoContext) + */ + @Override + public Data dereference(URIReference uriReference, XMLCryptoContext context) + throws URIReferenceException { + + String uriString = uriReference.getURI(); + if (uriString == null) { + return null; + } + + URI uri; + try { + uri = new URI(uriString); + } catch (URISyntaxException e) { + throw new URIReferenceException(e.getMessage(), e); + } + + if (uri.isAbsolute()) { + + URLDereferencer dereferencer = URLDereferencer.getInstance(); + StreamData streamData; + try { + streamData = dereferencer.dereference(uriString, urlDereferencerContext); + } catch (IOException e) { + throw new URIReferenceException(e.getMessage(), e); + } + return new OctetStreamData(streamData.getStream(), uriString, streamData.getContentType()); + + } else { + + URIDereferencer uriDereferencer = context.getURIDereferencer(); + if (uriDereferencer == null || uriDereferencer == this) { + uriDereferencer = new URIDereferencerImpl(); + } + + return uriDereferencer.dereference(uriReference, context); + + } + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/XSECTReference.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/XSECTReference.java new file mode 100644 index 00000000..6b388f2a --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/XSECTReference.java @@ -0,0 +1,112 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import iaik.xml.crypto.dsig.DigestMethodImpl; +import iaik.xml.crypto.dsig.DigestValueImpl; +import iaik.xml.crypto.dsig.ReferenceImpl; +import iaik.xml.crypto.dsig.TransformImpl; +import iaik.xml.crypto.dsig.TransformsImpl; + +import javax.xml.crypto.Data; +import javax.xml.crypto.URIDereferencer; +import javax.xml.crypto.URIReferenceException; +import javax.xml.crypto.XMLCryptoContext; +import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.dsig.TransformException; + +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLExceptionMessages; + +/** + * This class extends the XSECT ReferenceImpl to allow for the use + * of already marshalled ds:Transforms elements for initialization. + * + * @author mcentner + */ +public class XSECTReference extends ReferenceImpl { + + /** + * The URIDereferencer to be used for dereferencing. + */ + protected URIDereferencer dereferencer; + + /** + * Creates a new instance of this XSECTReference with the given + * uri, digest method, transforms, type + * and id value. + * + * @param uri + * the URI-attribute value (may be null) + * @param dm + * the digest method + * @param transforms + * a TransformsImpl element (may be null) + * @param type + * the Type-attribute value (may be null) + * @param id + * the Id-attribute value (may be null) + * + * @throws NullPointerException + * if digestMethod is null + * @throws IllegalArgumentException + * if uri is not RFC 2396 compliant + * @throws ClassCastException + * if any of the transforms is not of type + * {@link TransformImpl} + */ + public XSECTReference(String uri, DigestMethod dm, TransformsImpl transforms, String type, + String id) { + super(uri, transforms, type, id); + digestMethod_ = (DigestMethodImpl) dm; + digestValue_ = new DigestValueImpl(); + } + + /* (non-Javadoc) + * @see iaik.xml.crypto.dsig.ReferenceType#dereference(javax.xml.crypto.XMLCryptoContext) + */ + @Override + public Data dereference(XMLCryptoContext context) throws TransformException, + URIReferenceException { + if (dereferencer != null) { + return dereferencer.dereference(this, context); + } else { + try { + return super.dereference(context); + } catch (URIReferenceException e) { + SLCommandException commandException = new SLCommandException(4003, + SLExceptionMessages.EC4003_NOT_RESOLVED, new Object[] { getURI() }); + throw new URIReferenceException("Failed to dereference data to-be signed.", commandException); + } + } + } + + /** + * @return the dereferencer to be used for dereferencing this reference + */ + public URIDereferencer getDereferencer() { + return dereferencer; + } + + /** + * @param dereferencer the dereferencer to be used for dereferencing this reference + */ + public void setDereferencer(URIDereferencer dereferencer) { + this.dereferencer = dereferencer; + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/XSECTTransforms.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/XSECTTransforms.java new file mode 100644 index 00000000..a98e4236 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/XSECTTransforms.java @@ -0,0 +1,124 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl.xsect; + +import iaik.xml.crypto.dsig.TransformImpl; +import iaik.xml.crypto.dsig.TransformsImpl; + +import java.util.List; + +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.dom.DOMCryptoContext; +import javax.xml.crypto.dsig.Transform; + +import org.w3c.dom.Node; + +/** + * This class extends the XSECT TransformsImpl to allow for the use of an + * unmarshalled ds:Transforms element for initalization. + * + * @author mcentner + */ +public class XSECTTransforms extends TransformsImpl { + + /** + * Creates a new XSECTTransforms with the given list of transforms. + * + * @param transforms a list of {@link TransformImpl}s + * @see TransformsImpl#TransformsImpl(List) + */ + @SuppressWarnings("unchecked") + public XSECTTransforms(List transforms) { + super(transforms); + } + + /** + * Creates a new XSECTTransforms and initializes it from the given + * ds:Transforms node. + * + * @param context the context used for unmarshalling + * @param node the ds:Transforms node + * + * @throws MarshalException if unmarshalling the ds:Transforms fails + */ + public XSECTTransforms(DOMCryptoContext context, Node node) + throws MarshalException { + super(context, node); + } + + /** + * Inserts the given transform at the top of the + * transform list. + * + * @param transform the ds:Transform to instert + */ + @SuppressWarnings("unchecked") + public void insertTransform(Transform transform) { + if (transform == null) { + throw new NullPointerException("Parameter 'transform' must not be null."); + } + if (!(transform instanceof TransformImpl)) { + throw new ClassCastException("Transform 'transform' must be of type '" + TransformImpl.class.getName() + "'."); + } + transforms_.add(0, transform); + } + + /** + * @return + */ + @SuppressWarnings("unchecked") + private List getTransformImpls() { + return transforms_; + } + + /* (non-Javadoc) + * @see iaik.xml.crypto.dsig.TransformsType#marshal(javax.xml.crypto.dom.DOMCryptoContext, org.w3c.dom.Node, org.w3c.dom.Node) + */ + @Override + public Node marshal(DOMCryptoContext context, Node parent, Node nextSibling) + throws MarshalException { + + if (getNode() != null) { + // If this TransformsImpl has been unmarshalled from exiting nodes, + // we don't want to re-marshal ... + state_ = STATE_MARSHALED; + + // ... but append the existing node to the parent ... + Node transformsNode = parent.insertBefore(getNode(), nextSibling); + + // ... and marshal any Transforms not yet marshalled (e.g. that + // have been added via insertTransform(). + Node transformNextSibling = transformsNode.getFirstChild(); + List transforms = getTransformImpls(); + for (int i = 0; i < transforms.size(); i++) { + TransformImpl transform = transforms.get(i); + Node transformNode = transform.getNode(); + if (transformNode == null) { + // marshall TransformImpl + transformNode = transform.marshal(context, transformsNode, transformNextSibling); + } + transformNextSibling = transformNode.getNextSibling(); + } + + return transformsNode; + } else { + return super.marshal(context, parent, nextSibling); + } + + } + +} -- cgit v1.2.3 From e0f2c64ad6360e2ecec983cb5e0a60f812672106 Mon Sep 17 00:00:00 2001 From: wbauer Date: Thu, 4 Sep 2008 14:56:54 +0000 Subject: finished access controller, accessed it from command invoker and configured everything within onlinebku git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@14 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java index 93131cf4..b6745e1f 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java @@ -405,5 +405,10 @@ public class InfoboxReadCommandImpl extends SLCommandImpl Date: Fri, 5 Sep 2008 13:38:52 +0000 Subject: HashDataInput git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@20 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../bku/slcommands/impl/HashDataInputImpl.java | 42 + .../bku/slcommands/impl/xsect/STALPrivateKey.java | 218 +-- .../bku/slcommands/impl/xsect/STALSignature.java | 310 ++-- .../egiz/bku/slcommands/impl/xsect/Signature.java | 1855 ++++++++++---------- 4 files changed, 1251 insertions(+), 1174 deletions(-) create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java new file mode 100644 index 00000000..49d3c63f --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java @@ -0,0 +1,42 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package at.gv.egiz.bku.slcommands.impl; + +import at.gv.egiz.bku.slcommands.impl.xsect.DataObject; +import at.gv.egiz.stal.HashDataInput; +import java.io.InputStream; + +/** + * + * @author clemens + */ +public class HashDataInputImpl implements HashDataInput { + + String refId; + String mimeType; + InputStream hashDataInput; + + public HashDataInputImpl(DataObject dataObject) { + refId = dataObject.getReference().getId(); + mimeType = dataObject.getMimeType(); + hashDataInput = dataObject.getReference().getDigestInputStream(); + } + + @Override + public String getReferenceId() { + return refId; + } + + @Override + public String getMimeType() { + return mimeType; + } + + @Override + public InputStream getHashDataInput() { + return hashDataInput; + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java index 64c758c9..25e2d4e5 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java @@ -14,109 +14,115 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package at.gv.egiz.bku.slcommands.impl.xsect; - -import java.security.PrivateKey; - -import at.gv.egiz.stal.STAL; -import at.gv.egiz.stal.HashDataInputCallback; - -/** - * This class implements a private key used by the {@link STALSignature} class. - * - * @author mcentner - */ -public class STALPrivateKey implements PrivateKey { - - private static final long serialVersionUID = 1L; - - /** - * The STAL implementation. - */ - private STAL stal; - - /** - * The callback interface for obtaining the hash input data. - */ - private HashDataInputCallback hashDataInputCallback; - - /** - * The keybox identifier. - */ - private String keyboxIdentifier; - - /** - * The signature algorithm. - */ - private String algorithm; - - /** - * Creates a new instance of this STALPrivateKey with the given - * stal implementation, signature algorithm, - * keyboxIdentifier and hashDataInputCallback - * interface. - * - * @param stal - * the STAL implementation - * @param algorithm - * the signature algorithm - * @param keyboxIdentifier - * the keybox identifier - * @param hashDataInputCallback - * the interface for obtaining the has input data - */ - public STALPrivateKey(STAL stal, - String algorithm, String keyboxIdentifier, HashDataInputCallback hashDataInputCallback) { - super(); - this.keyboxIdentifier = keyboxIdentifier; - this.hashDataInputCallback = hashDataInputCallback; - this.stal = stal; - this.algorithm = algorithm; - } - - /* (non-Javadoc) - * @see java.security.Key#getAlgorithm() - */ - @Override - public String getAlgorithm() { - return algorithm; - } - - /* (non-Javadoc) - * @see java.security.Key#getEncoded() - */ - @Override - public byte[] getEncoded() { - throw new UnsupportedOperationException("STALPrivateKey does not support the getEncoded() method."); - } - - /* (non-Javadoc) - * @see java.security.Key#getFormat() - */ - @Override - public String getFormat() { - return null; - } - - /** - * @return the STAL implementation - */ - public STAL getStal() { - return stal; - } - - /** - * @return the interface for obtaining the hash data input - */ - public HashDataInputCallback getHashDataInputCallback() { - return hashDataInputCallback; - } - - /** - * @return the keybox identifier - */ - public String getKeyboxIdentifier() { - return keyboxIdentifier; - } - -} +package at.gv.egiz.bku.slcommands.impl.xsect; + +import at.gv.egiz.stal.HashDataInput; +import java.security.PrivateKey; + +import at.gv.egiz.stal.STAL; +//import at.gv.egiz.stal.HashDataInputCallback; +import java.util.List; + +/** + * This class implements a private key used by the {@link STALSignature} class. + * + * @author mcentner + */ +public class STALPrivateKey implements PrivateKey { + + private static final long serialVersionUID = 1L; + + /** + * The STAL implementation. + */ + private STAL stal; + + /** + * The callback interface for obtaining the hash input data. + */ +// private HashDataInputCallback hashDataInputCallback; + + + private List dataObjects; + + /** + * The keybox identifier. + */ + private String keyboxIdentifier; + + /** + * The signature algorithm. + */ + private String algorithm; + + /** + * Creates a new instance of this STALPrivateKey with the given + * stal implementation, signature algorithm, + * keyboxIdentifier and hashDataInputCallback + * interface. + * + * @param stal + * the STAL implementation + * @param algorithm + * the signature algorithm + * @param keyboxIdentifier + * the keybox identifier + * @param hashDataInputCallback + * the interface for obtaining the has input data + */ + public STALPrivateKey(STAL stal, + String algorithm, String keyboxIdentifier, List dataObjects) { + super(); + this.keyboxIdentifier = keyboxIdentifier; + this.dataObjects = dataObjects; + this.stal = stal; + this.algorithm = algorithm; + } + + /* (non-Javadoc) + * @see java.security.Key#getAlgorithm() + */ + @Override + public String getAlgorithm() { + return algorithm; + } + + /* (non-Javadoc) + * @see java.security.Key#getEncoded() + */ + @Override + public byte[] getEncoded() { + throw new UnsupportedOperationException("STALPrivateKey does not support the getEncoded() method."); + } + + /* (non-Javadoc) + * @see java.security.Key#getFormat() + */ + @Override + public String getFormat() { + return null; + } + + /** + * @return the STAL implementation + */ + public STAL getStal() { + return stal; + } + + /** + * @return the interface for obtaining the hash data input + */ + public List getDataObjects() { + + return dataObjects; + } + + /** + * @return the keybox identifier + */ + public String getKeyboxIdentifier() { + return keyboxIdentifier; + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java index f0fcb891..eba1d96d 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java @@ -14,152 +14,164 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package at.gv.egiz.bku.slcommands.impl.xsect; - -import java.io.ByteArrayOutputStream; -import java.security.InvalidKeyException; -import java.security.InvalidParameterException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SignatureException; -import java.security.SignatureSpi; -import java.util.Collections; -import java.util.List; - -import at.gv.egiz.stal.ErrorResponse; -import at.gv.egiz.stal.STAL; -import at.gv.egiz.stal.STALRequest; -import at.gv.egiz.stal.STALResponse; -import at.gv.egiz.stal.SignRequest; -import at.gv.egiz.stal.SignResponse; -import at.gv.egiz.stal.HashDataInputCallback; - -/** - * A signature service provider implementation that uses STAL to sign. - * - * @author mcentner - */ -public class STALSignature extends SignatureSpi { - - /** - * The private key. - */ - protected STALPrivateKey privateKey; - - /** - * The to-be signed data. - */ - protected ByteArrayOutputStream data = new ByteArrayOutputStream(); - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineGetParameter(java.lang.String) - */ - @Override - protected Object engineGetParameter(String param) - throws InvalidParameterException { - throw new InvalidParameterException(); - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineInitSign(java.security.PrivateKey) - */ - @Override - protected void engineInitSign(PrivateKey privateKey) - throws InvalidKeyException { - - if (!(privateKey instanceof STALPrivateKey)) { - throw new InvalidKeyException("STALSignature supports STALKeys only."); - } - - this.privateKey = (STALPrivateKey) privateKey; - - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineInitVerify(java.security.PublicKey) - */ - @Override - protected void engineInitVerify(PublicKey publicKey) - throws InvalidKeyException { - - throw new UnsupportedOperationException("STALSignature does not support signature verification."); - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineSetParameter(java.lang.String, java.lang.Object) - */ - @Override - protected void engineSetParameter(String param, Object value) - throws InvalidParameterException { - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineSign() - */ - @Override - protected byte[] engineSign() throws SignatureException { - - STAL stal = privateKey.getStal(); - - if (stal == null) { - throw new SignatureException("STALSignature requires the STALPrivateKey " + - "to provide a STAL implementation reference."); - } - - HashDataInputCallback signRefDataSupplier = privateKey.getHashDataInputCallback(); - - String keyboxIdentifier = privateKey.getKeyboxIdentifier(); - - if (keyboxIdentifier == null) { - throw new SignatureException("STALSignature requires the STALPrivateKey " + - "to provide a KeyboxIdentifier."); - } - - SignRequest signRequest = new SignRequest(); - signRequest.setKeyIdentifier(keyboxIdentifier); - signRequest.setSignedInfo(data.toByteArray()); - signRequest.setHashDataInput(signRefDataSupplier); - - List responses = stal.handleRequest(Collections.singletonList((STALRequest) signRequest)); - - if (responses == null || responses.size() != 1) { - throw new SignatureException("Failed to access STAL."); - } - - STALResponse response = responses.get(0); - if (response instanceof SignResponse) { - return ((SignResponse) response).getSignatureValue(); - } else if (response instanceof ErrorResponse) { - throw new STALSignatureException(((ErrorResponse) response).getErrorCode()); - } else { - throw new SignatureException("Failed to access STAL."); - } - - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineUpdate(byte) - */ - @Override - protected void engineUpdate(byte b) throws SignatureException { - data.write(b); - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineUpdate(byte[], int, int) - */ - @Override - protected void engineUpdate(byte[] b, int off, int len) - throws SignatureException { - data.write(b, off, len); - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineVerify(byte[]) - */ - @Override - protected boolean engineVerify(byte[] sigBytes) throws SignatureException { - throw new UnsupportedOperationException("STALSignature des not support signature verification."); - } - -} +package at.gv.egiz.bku.slcommands.impl.xsect; + +import at.gv.egiz.bku.slcommands.impl.HashDataInputImpl; +import java.io.ByteArrayOutputStream; +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SignatureException; +import java.security.SignatureSpi; +import java.util.Collections; +import java.util.List; + +import at.gv.egiz.stal.ErrorResponse; +import at.gv.egiz.stal.HashDataInput; +import at.gv.egiz.stal.STAL; +import at.gv.egiz.stal.STALRequest; +import at.gv.egiz.stal.STALResponse; +import at.gv.egiz.stal.SignRequest; +import at.gv.egiz.stal.SignResponse; +//import at.gv.egiz.stal.HashDataInputCallback; +import java.util.ArrayList; + +/** + * A signature service provider implementation that uses STAL to sign. + * + * @author mcentner + */ +public class STALSignature extends SignatureSpi { + +// private static final Log log = LogFactory.getLog(STALSignature.class); + + /** + * The private key. + */ + protected STALPrivateKey privateKey; + + /** + * The to-be signed data. + */ + protected ByteArrayOutputStream data = new ByteArrayOutputStream(); + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineGetParameter(java.lang.String) + */ + @Override + protected Object engineGetParameter(String param) + throws InvalidParameterException { + throw new InvalidParameterException(); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineInitSign(java.security.PrivateKey) + */ + @Override + protected void engineInitSign(PrivateKey privateKey) + throws InvalidKeyException { + + if (!(privateKey instanceof STALPrivateKey)) { + throw new InvalidKeyException("STALSignature supports STALKeys only."); + } + + this.privateKey = (STALPrivateKey) privateKey; + + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineInitVerify(java.security.PublicKey) + */ + @Override + protected void engineInitVerify(PublicKey publicKey) + throws InvalidKeyException { + + throw new UnsupportedOperationException("STALSignature does not support signature verification."); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineSetParameter(java.lang.String, java.lang.Object) + */ + @Override + protected void engineSetParameter(String param, Object value) + throws InvalidParameterException { + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineSign() + */ + @Override + protected byte[] engineSign() throws SignatureException { + + STAL stal = privateKey.getStal(); + + if (stal == null) { + throw new SignatureException("STALSignature requires the STALPrivateKey " + + "to provide a STAL implementation reference."); + } + + String keyboxIdentifier = privateKey.getKeyboxIdentifier(); + + if (keyboxIdentifier == null) { + throw new SignatureException("STALSignature requires the STALPrivateKey " + + "to provide a KeyboxIdentifier."); + } + + // get hashDataInputs (DigestInputStreams) once slcommands.impl.xsect.Signature::sign() was called + List dataObjects = privateKey.getDataObjects(); +// log.debug("got " + dataObjects.size() + " DataObjects, passing HashDataInputs to STAL SignRequest"); + + List hashDataInputs = new ArrayList(); + for (DataObject dataObject : dataObjects) { + hashDataInputs.add(new HashDataInputImpl(dataObject)); + } + + SignRequest signRequest = new SignRequest(); + signRequest.setKeyIdentifier(keyboxIdentifier); + signRequest.setSignedInfo(data.toByteArray()); + signRequest.setHashDataInput(hashDataInputs); + + List responses = stal.handleRequest(Collections.singletonList((STALRequest) signRequest)); + + if (responses == null || responses.size() != 1) { + throw new SignatureException("Failed to access STAL."); + } + + STALResponse response = responses.get(0); + if (response instanceof SignResponse) { + return ((SignResponse) response).getSignatureValue(); + } else if (response instanceof ErrorResponse) { + throw new STALSignatureException(((ErrorResponse) response).getErrorCode()); + } else { + throw new SignatureException("Failed to access STAL."); + } + + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineUpdate(byte) + */ + @Override + protected void engineUpdate(byte b) throws SignatureException { + data.write(b); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineUpdate(byte[], int, int) + */ + @Override + protected void engineUpdate(byte[] b, int off, int len) + throws SignatureException { + data.write(b, off, len); + } + + /* (non-Javadoc) + * @see java.security.SignatureSpi#engineVerify(byte[]) + */ + @Override + protected boolean engineVerify(byte[] sigBytes) throws SignatureException { + throw new UnsupportedOperationException("STALSignature des not support signature verification."); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java index 94a4a066..191f8371 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java @@ -14,922 +14,939 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package at.gv.egiz.bku.slcommands.impl.xsect; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.dom.DOMStructure; -import javax.xml.crypto.dsig.CanonicalizationMethod; -import javax.xml.crypto.dsig.DigestMethod; -import javax.xml.crypto.dsig.Reference; -import javax.xml.crypto.dsig.SignatureMethod; -import javax.xml.crypto.dsig.SignedInfo; -import javax.xml.crypto.dsig.XMLObject; -import javax.xml.crypto.dsig.XMLSignature; -import javax.xml.crypto.dsig.XMLSignatureException; -import javax.xml.crypto.dsig.XMLSignatureFactory; -import javax.xml.crypto.dsig.dom.DOMSignContext; -import javax.xml.crypto.dsig.keyinfo.KeyInfo; -import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; -import javax.xml.crypto.dsig.keyinfo.X509Data; -import javax.xml.stream.XMLStreamException; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.etsi.uri._01903.v1_1.DataObjectFormatType; -import org.etsi.uri._01903.v1_1.QualifyingPropertiesType; -import org.w3c.dom.DOMConfiguration; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSException; -import org.w3c.dom.ls.LSInput; -import org.w3c.dom.ls.LSOutput; -import org.w3c.dom.ls.LSParser; -import org.w3c.dom.ls.LSResourceResolver; -import org.w3c.dom.ls.LSSerializer; - -import at.buergerkarte.namespaces.securitylayer._1.Base64XMLLocRefReqRefContentType; -import at.buergerkarte.namespaces.securitylayer._1.Base64XMLOptRefContentType; -import at.buergerkarte.namespaces.securitylayer._1.DataObjectAssociationType; -import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; -import at.buergerkarte.namespaces.securitylayer._1.SignatureInfoCreationType; -import at.gv.egiz.bku.binding.HttpUtil; -import at.gv.egiz.bku.slexceptions.SLCommandException; -import at.gv.egiz.bku.slexceptions.SLRequestException; -import at.gv.egiz.bku.utils.HexDump; -import at.gv.egiz.bku.utils.urldereferencer.StreamData; -import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; -import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; -import at.gv.egiz.dom.DOMUtils; -import at.gv.egiz.slbinding.impl.XMLContentType; -import at.gv.egiz.stal.HashDataInputCallback; -import at.gv.egiz.stal.STAL; -import at.gv.egiz.xades.QualifyingPropertiesException; -import at.gv.egiz.xades.QualifyingPropertiesFactory; - -/** - * This class represents an XML-Signature as to be created by the - * security layer command CreateXMLSignatureRequest. - * - * @author mcentner - */ -public class Signature implements HashDataInputCallback { - - /** - * Logging facility. - */ - private static Log log = LogFactory.getLog(Signature.class); - - /** - * The DOM implementation used. - */ - private DOMImplementationLS domImplLS; - - /** - * The SignatureContext for the XMLSignature. - */ - private SignatureContext ctx; - - /** - * The list of {@link DataObject}s for this signature. - */ - private List dataObjects = new ArrayList(); - - /** - * A mapping from the Id-attribute values of this signature's - * ds:References to the corresponding {@link DataObject}s. - */ - private Map dataObjectReferencIds = new HashMap(); - - /** - * The SignatureEnvironment for this signature. - */ - private SignatureLocation signatureLocation; - - /** - * The XML signature. - */ - private XMLSignature xmlSignature; - - /** - * A list of attributes of type xsd:ID to be registered in the {@link DOMSignContext}. - */ - private List idAttributes = new ArrayList(); - - /** - * The signer's X509 certificate. - */ - private X509Certificate signerCertificate; - - /** - * The signing time. - */ - private Date signingTime; - - /** - * Creates a new SLXMLSignature instance. - */ - public Signature(URLDereferencerContext dereferencerContext, - IdValueFactory idValueFactory, - AlgorithmMethodFactory algorithmMethodFactory) { - - domImplLS = DOMUtils.getDOMImplementationLS(); - - ctx = new SignatureContext(); - - ctx.setSignatureFactory(XMLSignatureFactory.getInstance()); - - ctx.setDereferencerContext(dereferencerContext); - ctx.setIdValueFactory(idValueFactory); - ctx.setAlgorithmMethodFactory(algorithmMethodFactory); - - } - - /** - * @return the Document containing this Signature - */ - public Document getDocument() { - return ctx.getDocument(); - } - - /** - * @return the parent Node for this Signature - */ - public Node getParent() { - return (signatureLocation != null) ? signatureLocation.getParent() : null; - } - - /** - * @return the next sibling Node for this Signature - */ - public Node getNextSibling() { - return (signatureLocation != null) ? signatureLocation.getNextSibling() : null; - } - - /** - * @return the XMLSignature - */ - public XMLSignature getXMLSignature() { - return xmlSignature; - } - - /** - * @return the list of {@link Reference}s of this Signature - */ - @SuppressWarnings("unchecked") - public List getReferences() { - return (xmlSignature != null) ? xmlSignature.getSignedInfo().getReferences() : null; - } - - /** - * @return the list of {@link XMLObject}s of this Signature - */ - @SuppressWarnings("unchecked") - public List getXMLObjects() { - return (xmlSignature != null) ? xmlSignature.getObjects() : null; - } - - /** - * Prepares the signature document with the information given by the - * signatureInfo provided. - * - * @param signatureInfo - * the SignatureInfo - * - * @throws SLCommandException - * if processing fails for any reason - * @throws IllegalStateException - * if the parent node has already been set - * @throws NullPointerException - * if signatureInfo is null - */ - public void setSignatureInfo(SignatureInfoCreationType signatureInfo) throws SLCommandException { - - if (signatureLocation != null) { - throw new IllegalStateException("SignatureEnvironment already set."); - } - - Base64XMLOptRefContentType signatureEnvironment = signatureInfo.getSignatureEnvironment(); - - if (signatureEnvironment == null) { - - // no SignatureEnvironment, so we use an empty document and the document as parent - ensureSignatureLocation(); - - } else { - - // parse SignatureEnvrionment and use as document - Document document = parseSignatureEnvironment(signatureEnvironment, signatureInfo.getSupplement()); - ctx.setDocument(document); - - signatureLocation = new SignatureLocation(ctx); - signatureLocation.setSignatureInfo(signatureInfo); - - } - - } - - /** - * Ensures a SignatureLocation for this Signature. - */ - private void ensureSignatureLocation() { - - if (signatureLocation == null) { - Document document = DOMUtils.createDocument(); - ctx.setDocument(document); - - signatureLocation = new SignatureLocation(ctx); - signatureLocation.setParent(document); - } - - } - - /** - * Adds a DataObject with the information given by the - * dataObjectInfo provided to this Signature. - * - * @param dataObjectInfo - * the DataObjectInfo element - * - * @throws SLCommandException - * if adding the DataObject fails - * @throws SLRequestException - * if the information provided by the given - * dataObjectInfo does not conform to the security - * layer specification - * @throws NullPointerException - * if dataObjectInfo is null - */ - public void addDataObject(DataObjectInfoType dataObjectInfo) throws SLCommandException, SLRequestException { - - ensureSignatureLocation(); - - DataObject dataObject = new DataObject(ctx); - dataObject.setDataObjectInfo(dataObjectInfo); - - dataObjects.add(dataObject); - - dataObjectReferencIds.put(dataObject.getReference().getId(), dataObject); - - } - - /** - * Sets the SigningTime qualifying property of this Signature. - * - * @param signingTime the signing time to set - */ - public void setSigningTime(Date signingTime) { - this.signingTime = signingTime; - } - - /** - * Sets the SignerCertificate qualifying property of this Signature. - * - * @param certificate the signer's certificate - */ - public void setSignerCeritifcate(X509Certificate certificate) { - this.signerCertificate = certificate; - } - - /** - * Builds the XMLSignature data structure of this Signature as configured by - * the various setter methods. - * - * @throws SLCommandException if building this signature fails - */ - public void buildXMLSignature() throws SLCommandException { - - List objects = new ArrayList(); - List references = new ArrayList(); - - // add all data objects - for (DataObject dataObject : dataObjects) { - if (dataObject.getXmlObject() != null) { - objects.add(dataObject.getXmlObject()); - } - if (dataObject.getReference() != null) { - references.add(dataObject.getReference()); - } - } - - addXAdESObjectAndReference(objects, references); - - XMLSignatureFactory signatureFactory = ctx.getSignatureFactory(); - AlgorithmMethodFactory algorithmMethodFactory = ctx.getAlgorithmMethodFactory(); - - CanonicalizationMethod cm; - SignatureMethod sm; - try { - cm = algorithmMethodFactory.createCanonicalizationMethod(ctx); - sm = algorithmMethodFactory.createSignatureMethod(ctx); - } catch (NoSuchAlgorithmException e) { - log.error("Failed to get Canonicalization or Signature algorithm.", e); - throw new SLCommandException(4006); - } catch (InvalidAlgorithmParameterException e) { - log.error("Failed to get Canonicalization or Signature algorithm.", e); - throw new SLCommandException(4006); - } - - String siId = ctx.getIdValueFactory().createIdValue("SignedInfo"); - - SignedInfo si = signatureFactory.newSignedInfo(cm, sm, references, siId); - - KeyInfo ki = null; - if (signerCertificate != null) { - KeyInfoFactory kif = KeyInfoFactory.getInstance(); - X509Data x509Data = kif.newX509Data(Collections.singletonList(signerCertificate)); - ki = kif.newKeyInfo(Collections.singletonList(x509Data)); - } - - String signatureId = ctx.getIdValueFactory().createIdValue("Signature"); - String signatureValueId = ctx.getIdValueFactory().createIdValue("SignatureValue"); - - xmlSignature = signatureFactory.newXMLSignature(si, ki, objects, signatureId, signatureValueId); - - } - - /** - * Sign this Signature using the given signContext. - *

- * Call's {@link #buildXMLSignature()} if it has not been called yet. - *

- * - * @param signContext - * the signing context - * - * @throws MarshalException - * if marshalling the XMLSignature fails - * @throws XMLSignatureException - * if signing the XMLSignature fails - * @throws SLCommandException - * if building the XMLSignature fails - * @throws NullPointerException - * if signContext is null - */ - public void sign(DOMSignContext signContext) throws MarshalException, XMLSignatureException, SLCommandException { - - if (xmlSignature == null) { - buildXMLSignature(); - } - - for (IdAttribute idAttribute : idAttributes) { - signContext.setIdAttributeNS(idAttribute.element, idAttribute.namespaceURI, idAttribute.localName); - } - - // DO NOT USE: - // signContext.setProperty("iaik.xml.crypto.dsig.sign-over", Boolean.TRUE); - - signContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); - - signContext.putNamespacePrefix(XMLSignature.XMLNS, "dsig"); - - signContext.setURIDereferencer(new URIDereferncerAdapter(ctx.getDereferencerContext())); - - try { - xmlSignature.sign(signContext); - } catch (XMLSignatureException e) { - Throwable cause = e.getCause(); - while (cause != null) { - if (cause instanceof STALSignatureException) { - int errorCode = ((STALSignatureException) cause).getErrorCode(); - SLCommandException commandException = new SLCommandException(errorCode); - log.info("Failed to sign signature.", commandException); - throw commandException; - } else { - cause = cause.getCause(); - } - } - throw e; - } - - // debug - if (log.isTraceEnabled()) { - for (DataObject dataObject : dataObjects) { - Reference reference = dataObject.getReference(); - InputStream digestInputStream = reference.getDigestInputStream(); - if (digestInputStream != null) { - String mimeType = dataObject.getMimeType(); - StringBuilder sb = new StringBuilder(); - sb.append("DigestInput for Reference with id='"); - sb.append(reference.getId()); - sb.append("' (MIME-Type="); - sb.append(dataObject.getMimeType()); - sb.append("):\n"); - try { - if (mimeType != null && ( - mimeType.startsWith("text") || - "application/xhtml+xml".equals(mimeType))) { - byte[] b = new byte[512]; - for (int l; (l = digestInputStream.read(b)) != -1;) { - sb.append(new String(b, 0, l)); - } - } else { - sb.append(HexDump.hexDump(digestInputStream)); - } - } catch (IOException e) { - log.error(e); - } - log.trace(sb.toString()); - } else { - log.trace("Reference caching is not enabled."); - } - } - } - - } - - /** - * Sign this Signature using the given stal implementation and - * keyboxIdentifier. - *

- * This method configures an appropriate {@link DOMSignContext} and calls - * {@link #sign(DOMSignContext)}. If {@link #buildXMLSignature()} has not been - * called yet, it is called by this method. - *

- * - * @param stal - * the STAL implementation to use - * @param keyboxIdentifier - * the KeyboxIdentifier to use - * - * @throws MarshalException - * if marshalling this Signature fails - * @throws XMLSignatureException - * if signing this Signature fails - * @throws SLCommandException - * if building this Signature fails - * @throws NullPointerException - * if stal or keyboxIdentifier is - * null - */ - public void sign(STAL stal, String keyboxIdentifier) throws MarshalException, XMLSignatureException, SLCommandException { - - if (stal == null) { - throw new NullPointerException("Argument 'stal' must not be null."); - } - - if (keyboxIdentifier == null) { - throw new NullPointerException("Argument 'keyboxIdentifier' must not be null."); - } - - if (xmlSignature == null) { - buildXMLSignature(); - } - - SignatureMethod signatureMethod = xmlSignature.getSignedInfo().getSignatureMethod(); - String algorithm = signatureMethod.getAlgorithm(); - - PrivateKey privateKey = new STALPrivateKey(stal, algorithm, keyboxIdentifier, this); - - DOMSignContext signContext; - if (getNextSibling() == null) { - signContext = new DOMSignContext(privateKey, getParent()); - } else { - signContext = new DOMSignContext(privateKey, getParent(), getNextSibling()); - } - - sign(signContext); - } - - @Override - public InputStream getHashDataInput(String referenceId) { - - DataObject dataObject = dataObjectReferencIds.get(referenceId); - if (dataObject != null) { - return dataObject.getReference().getDigestInputStream(); - } else { - return null; - } - } - - /** - * Adds the XAdES QualifyingProperties as an - * ds:Object and a corresponding ds:Reference to - * it's SignedProperties element to this Signature. - * - * @param objects - * the list of ds:Objects to add the created - * ds:Object to - * @param references - * the list of ds:References to add the created - * ds:Reference to - * - * @throws SLCommandException - * if creating and adding the XAdES - * QualifyingProperties fails - * @throws NullPointerException - * if objects or references is - * null - */ - private void addXAdESObjectAndReference(List objects, List references) throws SLCommandException { - - QualifyingPropertiesFactory factory = QualifyingPropertiesFactory.getInstance(); - - String idValue = ctx.getIdValueFactory().createIdValue("SignedProperties"); - - Date date = (signingTime != null) ? signingTime : new Date(); - - List signingCertificates; - if (signerCertificate != null) { - signingCertificates = Collections.singletonList(signerCertificate); - } else { - signingCertificates = Collections.emptyList(); - } - - // TODO: report MOA-SP bug - // - // The security layer specification mandates the use of version 1.2.2. of the - // XAdES QualifyingProperties. However MOA-SP supports only version 1.1.1. Therefore, - // the version 1.1.1 is used in order to be compatible with current MOA-SP versions. - - List dataObjectFormats = new ArrayList(); - for (DataObject dataObject : dataObjects) { - if (dataObject.getMimeType() != null && dataObject.getReference() != null) { - Reference reference = dataObject.getReference(); - if (reference.getId() != null) { - String objectReference = "#" + reference.getId(); - dataObjectFormats.add(factory.createDataObjectFormatType( - objectReference, dataObject.getMimeType(), dataObject - .getDescription())); - } - } - } - - JAXBElement qualifyingProperties; - try { - qualifyingProperties = factory.createQualifyingProperties111(date, signingCertificates, idValue, dataObjectFormats); - } catch (QualifyingPropertiesException e) { - log.error("Failed to create QualifyingProperties.", e); - throw new SLCommandException(4000); - } - - DocumentFragment fragment = ctx.getDocument().createDocumentFragment(); - - try { - factory.marshallQualifyingProperties(qualifyingProperties, fragment); - } catch (JAXBException e) { - log.error("Failed to marshal QualifyingProperties.", e); - throw new SLCommandException(4000); - } - - List content = Collections.singletonList(new DOMStructure(fragment.getFirstChild())); - - String objectIdValue = ctx.getIdValueFactory().createIdValue("Object"); - - XMLObject object = ctx.getSignatureFactory().newXMLObject(content, objectIdValue, null, null); - - objects.add(object); - - // TODO: Report MOA-SP Bug - // - // Direct referencing of the SignedPorperties Id-attribute is not supported by MOA-SP - // because the QualifyingProperties are parsed without the XAdES schema. Therefore, - // the shorthand XPointer could not be resolved. - // - // The following workaround uses an XPointer to select the SignedProperties in order - // to allow the signature to be verified with MOA-SP. - - String referenceURI = "#xmlns(xades=http://uri.etsi.org/01903/v1.1.1%23)%20xpointer(id('" - + objectIdValue - + "')/child::xades:QualifyingProperties/child::xades:SignedProperties)"; - DigestMethod dm; - try { - dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); - } catch (NoSuchAlgorithmException e) { - log.error("Failed to get DigestMethod algorithm.", e); - throw new SLCommandException(4006); - } catch (InvalidAlgorithmParameterException e) { - log.error("Failed to get DigestMethod algorithm.", e); - throw new SLCommandException(4006); - } - - String referenceIdValue = ctx.getIdValueFactory().createIdValue("Reference"); - String referenceType = QualifyingPropertiesFactory.SIGNED_PROPERTIES_REFERENCE_TYPE_V1_1_1; - - Reference reference = ctx.getSignatureFactory().newReference(referenceURI, dm, null, referenceType, referenceIdValue); - - references.add(reference); - - Node child = fragment.getFirstChild(); - if (child instanceof Element) { - NodeList nodes = ((Element) child).getElementsByTagNameNS(QualifyingPropertiesFactory.NS_URI_V1_1_1, "SignedProperties"); - if (nodes.getLength() > 0) { - IdAttribute idAttribute = new IdAttribute(); - idAttribute.element = (Element) nodes.item(0); - idAttribute.namespaceURI = null; - idAttribute.localName = "Id"; - idAttributes.add(idAttribute); - } - } - - } - - /** - * Parse the SignatureEnvironment. - * - * @param signatureEnvironment - * the SignatureEnvironment element - * @param supplements - * an optional list of Supplements (may be - * null) - * - * @return the parsed SignatureEnvironment document - * - * @throws SLCommandException - * if parsing the SignatureEnvironment fails - * @throws NullPointerException - * if signatureEnvironment is null - */ - private Document parseSignatureEnvironment( - Base64XMLOptRefContentType signatureEnvironment, - List supplements) throws SLCommandException { - - if (signatureEnvironment == null) { - throw new NullPointerException("Argument 'signatureEnvironment' must not be null."); - } - - LSInput input; - try { - if (signatureEnvironment.getReference() != null) { - log.debug("SignatureEnvironment contains Reference " + signatureEnvironment.getReference() + "."); - input = createLSInput(signatureEnvironment.getReference()); - } else if (signatureEnvironment.getBase64Content() != null) { - log.debug("SignatureEnvironment contains Base64Content."); - input = createLSInput(signatureEnvironment.getBase64Content()); - } else if (signatureEnvironment.getXMLContent() != null) { - log.debug("SignatureEnvironment contains XMLContent."); - input = createLSInput((XMLContentType) signatureEnvironment.getXMLContent()); - } else { - // the schema does not allow us to reach this point - throw new SLCommandException(4000); - } - } catch (IOException e) { - log.info("XML document in which the signature is to be integrated cannot be resolved.", e); - throw new SLCommandException(4100); - } catch (XMLStreamException e) { - log.info("XML document in which the signature is to be integrated cannot be resolved.", e); - throw new SLCommandException(4100); - } - - LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); - DOMConfiguration domConfig = parser.getDomConfig(); - SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); - domConfig.setParameter("error-handler", errorHandler); - LSResourceResolverAdapter resourceResolver = new LSResourceResolverAdapter(supplements); - domConfig.setParameter("resource-resolver", resourceResolver); - domConfig.setParameter("validate", Boolean.TRUE); - - Document doc; - try { - doc = parser.parse(input); - } catch (DOMException e) { - log.info("XML document in which the signature is to be integrated cannot be parsed.", e); - throw new SLCommandException(4101); - } catch (LSException e) { - log.info("XML document in which the signature is to be integrated cannot be parsed.", e); - throw new SLCommandException(4101); - } - - if (resourceResolver.getError() != null) { - log.info("Failed to resolve resource while parsing SignatureEnvironment document.", resourceResolver.getError()); - // we don't stop here, as we only _try_ to parse validating - } - - if (errorHandler.hasFatalErrors()) { - // log fatal errors - if (log.isInfoEnabled()) { - List errorMessages = errorHandler.getErrorMessages(); - StringBuffer sb = new StringBuffer(); - for (String errorMessage : errorMessages) { - sb.append(" "); - sb.append(errorMessage); - } - log.info("XML document in which the signature is to be integrated cannot be parsed." + sb.toString()); - } - throw new SLCommandException(4101); - } - - // log parsed document - if (log.isTraceEnabled()) { - - StringWriter writer = new StringWriter(); - - writer.write("SignatureEnvironment:\n"); - - LSOutput output = domImplLS.createLSOutput(); - output.setCharacterStream(writer); - output.setEncoding("UTF-8"); - LSSerializer serializer = domImplLS.createLSSerializer(); - serializer.write(doc, output); - - log.trace(writer.toString()); - } - - return doc; - - } - - /** - * Creates an LSInput from the given reference URI. - * - * @param reference - * the reference URL - * - * @return an LSInput from the given reference URI - * - * @throws IOException - * if dereferencing the given reference fails - */ - private LSInput createLSInput(String reference) throws IOException { - - URLDereferencer urlDereferencer = URLDereferencer.getInstance(); - StreamData streamData = urlDereferencer.dereference(reference, ctx.getDereferencerContext()); - - String contentType = streamData.getContentType(); - String charset = HttpUtil.getCharset(contentType, true); - InputStreamReader streamReader; - try { - streamReader = new InputStreamReader(streamData.getStream(), charset); - } catch (UnsupportedEncodingException e) { - log.info("Charset " + charset + " not supported. Using default."); - streamReader = new InputStreamReader(streamData.getStream()); - } - - LSInput input = domImplLS.createLSInput(); - input = domImplLS.createLSInput(); - input.setCharacterStream(streamReader); - - return input; - - } - - /** - * Creates an LSInput from the given content bytes. - * - * @param content - * the content bytes - * - * @return an LSInput from the givne content bytes - */ - private LSInput createLSInput(byte[] content) { - - ByteArrayInputStream inputStream = new ByteArrayInputStream(content); - LSInput input = domImplLS.createLSInput(); - input.setByteStream(inputStream); - - return input; - - } - - /** - * Creates an LSInput from the given XML content. - * - * @param content - * the XML content - * @return an LSInput from the given XML content - * - * @throws XMLStreamException - * if reading the XMLStream from the given XML content fails - */ - private LSInput createLSInput(XMLContentType content) throws XMLStreamException { - - ByteArrayOutputStream redirectedStream = content.getRedirectedStream(); - if (redirectedStream != null) { - LSInput input = domImplLS.createLSInput(); - input.setByteStream(new ByteArrayInputStream(redirectedStream.toByteArray())); - return input; - } else { - return null; - } - - } - - /** - * Represents an xsd:Id-attribute value. - * - * @author mcentner - */ - private class IdAttribute { - - private Element element; - - private String namespaceURI; - - private String localName; - - } - - /** - * An implementation of the LSResourceResolver that uses a list of supplements - * to resolve resources. - * - * @author mcentner - */ - private class LSResourceResolverAdapter implements LSResourceResolver { - - List supplements; - - private LSResourceResolverAdapter( - List supplements) { - this.supplements = supplements; - } - - private Exception error; - - /** - * @return the error - */ - public Exception getError() { - return error; - } - - @Override - public LSInput resolveResource(String type, String namespaceURI, - String publicId, String systemId, String baseURI) { - - if (log.isTraceEnabled()) { - log.trace("Resolve resource :" + - "\n type=" + type + - "\n namespaceURI=" + namespaceURI + - "\n publicId=" + publicId + - "\n systemId=" + systemId + - "\n baseURI=" + baseURI); - } - - if (systemId != null) { - - log.debug("Resolve resource '" + systemId + "'."); - - for (DataObjectAssociationType supplement : supplements) { - - Base64XMLLocRefReqRefContentType content = supplement.getContent(); - if (content != null) { - - String reference = content.getReference(); - if (systemId.equals(reference)) { - - try { - if (content.getLocRefContent() != null) { - log.trace("Resolved resource '" + reference + "' to supplement with LocRefContent."); - return createLSInput(content.getLocRefContent()); - } else if (content.getBase64Content() != null) { - log.trace("Resolved resource '" + reference + "' to supplement with Base64Content."); - return createLSInput(content.getBase64Content()); - } else if (content.getXMLContent() != null) { - log.trace("Resolved resource '" + reference + "' to supplement with XMLContent."); - return createLSInput((XMLContentType) content.getXMLContent()); - } else { - return null; - } - } catch (IOException e) { - log.info("Failed to resolve resource '" + systemId + "' to supplement.", e); - error = e; - return null; - } catch (XMLStreamException e) { - log.info("Failed to resolve resource '" + systemId + "' to supplement.", e); - error = e; - return null; - } - - } - - } - - } - - log.info("Failed to resolve resource '" + systemId + "' to supplement. No such supplement."); - - } - - return null; - - } - - - } - -} +package at.gv.egiz.bku.slcommands.impl.xsect; + +import at.gv.egiz.stal.HashDataInput; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.security.InvalidAlgorithmParameterException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.dom.DOMStructure; +import javax.xml.crypto.dsig.CanonicalizationMethod; +import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.dsig.Reference; +import javax.xml.crypto.dsig.SignatureMethod; +import javax.xml.crypto.dsig.SignedInfo; +import javax.xml.crypto.dsig.XMLObject; +import javax.xml.crypto.dsig.XMLSignature; +import javax.xml.crypto.dsig.XMLSignatureException; +import javax.xml.crypto.dsig.XMLSignatureFactory; +import javax.xml.crypto.dsig.dom.DOMSignContext; +import javax.xml.crypto.dsig.keyinfo.KeyInfo; +import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; +import javax.xml.crypto.dsig.keyinfo.X509Data; +import javax.xml.stream.XMLStreamException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.etsi.uri._01903.v1_1.DataObjectFormatType; +import org.etsi.uri._01903.v1_1.QualifyingPropertiesType; +import org.w3c.dom.DOMConfiguration; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSException; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSParser; +import org.w3c.dom.ls.LSResourceResolver; +import org.w3c.dom.ls.LSSerializer; + +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLLocRefReqRefContentType; +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLOptRefContentType; +import at.buergerkarte.namespaces.securitylayer._1.DataObjectAssociationType; +import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; +import at.buergerkarte.namespaces.securitylayer._1.SignatureInfoCreationType; +import at.gv.egiz.bku.binding.HttpUtil; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLRequestException; +import at.gv.egiz.bku.utils.HexDump; +import at.gv.egiz.bku.utils.urldereferencer.StreamData; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; +import at.gv.egiz.dom.DOMUtils; +import at.gv.egiz.slbinding.impl.XMLContentType; +import at.gv.egiz.stal.STAL; +import at.gv.egiz.xades.QualifyingPropertiesException; +import at.gv.egiz.xades.QualifyingPropertiesFactory; + +/** + * This class represents an XML-Signature as to be created by the + * security layer command CreateXMLSignatureRequest. + * + * @author mcentner + */ +public class Signature { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(Signature.class); + + /** + * The DOM implementation used. + */ + private DOMImplementationLS domImplLS; + + /** + * The SignatureContext for the XMLSignature. + */ + private SignatureContext ctx; + + /** + * The list of {@link DataObject}s for this signature. + */ + private List dataObjects = new ArrayList(); + + /** + * A mapping from the Id-attribute values of this signature's + * ds:References to the corresponding {@link DataObject}s. + */ +// private Map dataObjectReferencIds = new HashMap(); + + /** + * The SignatureEnvironment for this signature. + */ + private SignatureLocation signatureLocation; + + /** + * The XML signature. + */ + private XMLSignature xmlSignature; + + /** + * A list of attributes of type xsd:ID to be registered in the {@link DOMSignContext}. + */ + private List idAttributes = new ArrayList(); + + /** + * The signer's X509 certificate. + */ + private X509Certificate signerCertificate; + + /** + * The signing time. + */ + private Date signingTime; + + /** + * Creates a new SLXMLSignature instance. + */ + public Signature(URLDereferencerContext dereferencerContext, + IdValueFactory idValueFactory, + AlgorithmMethodFactory algorithmMethodFactory) { + + domImplLS = DOMUtils.getDOMImplementationLS(); + + ctx = new SignatureContext(); + + ctx.setSignatureFactory(XMLSignatureFactory.getInstance()); + + ctx.setDereferencerContext(dereferencerContext); + ctx.setIdValueFactory(idValueFactory); + ctx.setAlgorithmMethodFactory(algorithmMethodFactory); + + } + + /** + * @return the Document containing this Signature + */ + public Document getDocument() { + return ctx.getDocument(); + } + + /** + * @return the parent Node for this Signature + */ + public Node getParent() { + return (signatureLocation != null) ? signatureLocation.getParent() : null; + } + + /** + * @return the next sibling Node for this Signature + */ + public Node getNextSibling() { + return (signatureLocation != null) ? signatureLocation.getNextSibling() : null; + } + + /** + * @return the XMLSignature + */ + public XMLSignature getXMLSignature() { + return xmlSignature; + } + + /** + * @return the list of {@link Reference}s of this Signature + */ + @SuppressWarnings("unchecked") + public List getReferences() { + return (xmlSignature != null) ? xmlSignature.getSignedInfo().getReferences() : null; + } + + /** + * @return the list of {@link XMLObject}s of this Signature + */ + @SuppressWarnings("unchecked") + public List getXMLObjects() { + return (xmlSignature != null) ? xmlSignature.getObjects() : null; + } + + /** + * Prepares the signature document with the information given by the + * signatureInfo provided. + * + * @param signatureInfo + * the SignatureInfo + * + * @throws SLCommandException + * if processing fails for any reason + * @throws IllegalStateException + * if the parent node has already been set + * @throws NullPointerException + * if signatureInfo is null + */ + public void setSignatureInfo(SignatureInfoCreationType signatureInfo) throws SLCommandException { + + if (signatureLocation != null) { + throw new IllegalStateException("SignatureEnvironment already set."); + } + + Base64XMLOptRefContentType signatureEnvironment = signatureInfo.getSignatureEnvironment(); + + if (signatureEnvironment == null) { + + // no SignatureEnvironment, so we use an empty document and the document as parent + ensureSignatureLocation(); + + } else { + + // parse SignatureEnvrionment and use as document + Document document = parseSignatureEnvironment(signatureEnvironment, signatureInfo.getSupplement()); + ctx.setDocument(document); + + signatureLocation = new SignatureLocation(ctx); + signatureLocation.setSignatureInfo(signatureInfo); + + } + + } + + /** + * Ensures a SignatureLocation for this Signature. + */ + private void ensureSignatureLocation() { + + if (signatureLocation == null) { + Document document = DOMUtils.createDocument(); + ctx.setDocument(document); + + signatureLocation = new SignatureLocation(ctx); + signatureLocation.setParent(document); + } + + } + + /** + * Adds a DataObject with the information given by the + * dataObjectInfo provided to this Signature. + * + * @param dataObjectInfo + * the DataObjectInfo element + * + * @throws SLCommandException + * if adding the DataObject fails + * @throws SLRequestException + * if the information provided by the given + * dataObjectInfo does not conform to the security + * layer specification + * @throws NullPointerException + * if dataObjectInfo is null + */ + public void addDataObject(DataObjectInfoType dataObjectInfo) throws SLCommandException, SLRequestException { + + ensureSignatureLocation(); + + DataObject dataObject = new DataObject(ctx); + dataObject.setDataObjectInfo(dataObjectInfo); + + dataObjects.add(dataObject); + +// dataObjectReferencIds.put(dataObject.getReference().getId(), dataObject); + + } + + /** + * Sets the SigningTime qualifying property of this Signature. + * + * @param signingTime the signing time to set + */ + public void setSigningTime(Date signingTime) { + this.signingTime = signingTime; + } + + /** + * Sets the SignerCertificate qualifying property of this Signature. + * + * @param certificate the signer's certificate + */ + public void setSignerCeritifcate(X509Certificate certificate) { + this.signerCertificate = certificate; + } + + /** + * Builds the XMLSignature data structure of this Signature as configured by + * the various setter methods. + * + * @throws SLCommandException if building this signature fails + */ + public void buildXMLSignature() throws SLCommandException { + + List objects = new ArrayList(); + List references = new ArrayList(); + + // add all data objects + for (DataObject dataObject : dataObjects) { + if (dataObject.getXmlObject() != null) { + objects.add(dataObject.getXmlObject()); + } + if (dataObject.getReference() != null) { + references.add(dataObject.getReference()); + } + } + + addXAdESObjectAndReference(objects, references); + + XMLSignatureFactory signatureFactory = ctx.getSignatureFactory(); + AlgorithmMethodFactory algorithmMethodFactory = ctx.getAlgorithmMethodFactory(); + + CanonicalizationMethod cm; + SignatureMethod sm; + try { + cm = algorithmMethodFactory.createCanonicalizationMethod(ctx); + sm = algorithmMethodFactory.createSignatureMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get Canonicalization or Signature algorithm.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get Canonicalization or Signature algorithm.", e); + throw new SLCommandException(4006); + } + + String siId = ctx.getIdValueFactory().createIdValue("SignedInfo"); + + SignedInfo si = signatureFactory.newSignedInfo(cm, sm, references, siId); + + KeyInfo ki = null; + if (signerCertificate != null) { + KeyInfoFactory kif = KeyInfoFactory.getInstance(); + X509Data x509Data = kif.newX509Data(Collections.singletonList(signerCertificate)); + ki = kif.newKeyInfo(Collections.singletonList(x509Data)); + } + + String signatureId = ctx.getIdValueFactory().createIdValue("Signature"); + String signatureValueId = ctx.getIdValueFactory().createIdValue("SignatureValue"); + + xmlSignature = signatureFactory.newXMLSignature(si, ki, objects, signatureId, signatureValueId); + + } + + /** + * Sign this Signature using the given signContext. + *

+ * Call's {@link #buildXMLSignature()} if it has not been called yet. + *

+ * + * @param signContext + * the signing context + * + * @throws MarshalException + * if marshalling the XMLSignature fails + * @throws XMLSignatureException + * if signing the XMLSignature fails + * @throws SLCommandException + * if building the XMLSignature fails + * @throws NullPointerException + * if signContext is null + */ + public void sign(DOMSignContext signContext) throws MarshalException, XMLSignatureException, SLCommandException { + + if (xmlSignature == null) { + buildXMLSignature(); + } + + for (IdAttribute idAttribute : idAttributes) { + signContext.setIdAttributeNS(idAttribute.element, idAttribute.namespaceURI, idAttribute.localName); + } + + // DO NOT USE: + // signContext.setProperty("iaik.xml.crypto.dsig.sign-over", Boolean.TRUE); + + signContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); + + signContext.putNamespacePrefix(XMLSignature.XMLNS, "dsig"); + + signContext.setURIDereferencer(new URIDereferncerAdapter(ctx.getDereferencerContext())); + + try { + xmlSignature.sign(signContext); + } catch (XMLSignatureException e) { + Throwable cause = e.getCause(); + while (cause != null) { + if (cause instanceof STALSignatureException) { + int errorCode = ((STALSignatureException) cause).getErrorCode(); + SLCommandException commandException = new SLCommandException(errorCode); + log.info("Failed to sign signature.", commandException); + throw commandException; + } else { + cause = cause.getCause(); + } + } + throw e; + } + + // debug + if (log.isTraceEnabled()) { + for (DataObject dataObject : dataObjects) { + Reference reference = dataObject.getReference(); + InputStream digestInputStream = reference.getDigestInputStream(); + if (digestInputStream != null) { + String mimeType = dataObject.getMimeType(); + StringBuilder sb = new StringBuilder(); + sb.append("DigestInput for Reference with id='"); + sb.append(reference.getId()); + sb.append("' (MIME-Type="); + sb.append(dataObject.getMimeType()); + sb.append("):\n"); + try { + if (mimeType != null && ( + mimeType.startsWith("text") || + "application/xhtml+xml".equals(mimeType))) { + byte[] b = new byte[512]; + for (int l; (l = digestInputStream.read(b)) != -1;) { + sb.append(new String(b, 0, l)); + } + } else { + sb.append(HexDump.hexDump(digestInputStream)); + } + } catch (IOException e) { + log.error(e); + } + log.trace(sb.toString()); + } else { + log.trace("Reference caching is not enabled."); + } + } + } + + } + + /** + * Sign this Signature using the given stal implementation and + * keyboxIdentifier. + *

+ * This method configures an appropriate {@link DOMSignContext} and calls + * {@link #sign(DOMSignContext)}. If {@link #buildXMLSignature()} has not been + * called yet, it is called by this method. + *

+ * + * @param stal + * the STAL implementation to use + * @param keyboxIdentifier + * the KeyboxIdentifier to use + * + * @throws MarshalException + * if marshalling this Signature fails + * @throws XMLSignatureException + * if signing this Signature fails + * @throws SLCommandException + * if building this Signature fails + * @throws NullPointerException + * if stal or keyboxIdentifier is + * null + */ + public void sign(STAL stal, String keyboxIdentifier) throws MarshalException, XMLSignatureException, SLCommandException { + + if (stal == null) { + throw new NullPointerException("Argument 'stal' must not be null."); + } + + if (keyboxIdentifier == null) { + throw new NullPointerException("Argument 'keyboxIdentifier' must not be null."); + } + + if (xmlSignature == null) { + buildXMLSignature(); + } + + SignatureMethod signatureMethod = xmlSignature.getSignedInfo().getSignatureMethod(); + String algorithm = signatureMethod.getAlgorithm(); + + //don't get hashDataInputs (digestInputStreams) now, only once Signature.sign() was called (cf STALSignature.engineSign) + PrivateKey privateKey = new STALPrivateKey(stal, algorithm, keyboxIdentifier, dataObjects); // hashDataInputs); + + DOMSignContext signContext; + if (getNextSibling() == null) { + signContext = new DOMSignContext(privateKey, getParent()); + } else { + signContext = new DOMSignContext(privateKey, getParent(), getNextSibling()); + } + + sign(signContext); + } + +// @Override +// public HashDataInput getHashDataInput(final String referenceId) { +// final DataObject dataObject = dataObjectReferencIds.get(referenceId); +// if (dataObject != null) { +// return new HashDataInput() { +// +// InputStream hashDataInput = dataObject.getReference().getDigestInputStream(); +// +// @Override +// public String getReferenceId() { +// return referenceId; +// } +// +// @Override +// public String getMimeType() { +// return dataObject.getMimeType(); +// } +// +// @Override +// public InputStream getHashDataInput() { +// return hashDataInput; +// } +// }; +// } +// return null; +// } + + /** + * Adds the XAdES QualifyingProperties as an + * ds:Object and a corresponding ds:Reference to + * it's SignedProperties element to this Signature. + * + * @param objects + * the list of ds:Objects to add the created + * ds:Object to + * @param references + * the list of ds:References to add the created + * ds:Reference to + * + * @throws SLCommandException + * if creating and adding the XAdES + * QualifyingProperties fails + * @throws NullPointerException + * if objects or references is + * null + */ + private void addXAdESObjectAndReference(List objects, List references) throws SLCommandException { + + QualifyingPropertiesFactory factory = QualifyingPropertiesFactory.getInstance(); + + String idValue = ctx.getIdValueFactory().createIdValue("SignedProperties"); + + Date date = (signingTime != null) ? signingTime : new Date(); + + List signingCertificates; + if (signerCertificate != null) { + signingCertificates = Collections.singletonList(signerCertificate); + } else { + signingCertificates = Collections.emptyList(); + } + + // TODO: report MOA-SP bug + // + // The security layer specification mandates the use of version 1.2.2. of the + // XAdES QualifyingProperties. However MOA-SP supports only version 1.1.1. Therefore, + // the version 1.1.1 is used in order to be compatible with current MOA-SP versions. + + List dataObjectFormats = new ArrayList(); + for (DataObject dataObject : dataObjects) { + if (dataObject.getMimeType() != null && dataObject.getReference() != null) { + Reference reference = dataObject.getReference(); + if (reference.getId() != null) { + String objectReference = "#" + reference.getId(); + dataObjectFormats.add(factory.createDataObjectFormatType( + objectReference, dataObject.getMimeType(), dataObject + .getDescription())); + } + } + } + + JAXBElement qualifyingProperties; + try { + qualifyingProperties = factory.createQualifyingProperties111(date, signingCertificates, idValue, dataObjectFormats); + } catch (QualifyingPropertiesException e) { + log.error("Failed to create QualifyingProperties.", e); + throw new SLCommandException(4000); + } + + DocumentFragment fragment = ctx.getDocument().createDocumentFragment(); + + try { + factory.marshallQualifyingProperties(qualifyingProperties, fragment); + } catch (JAXBException e) { + log.error("Failed to marshal QualifyingProperties.", e); + throw new SLCommandException(4000); + } + + List content = Collections.singletonList(new DOMStructure(fragment.getFirstChild())); + + String objectIdValue = ctx.getIdValueFactory().createIdValue("Object"); + + XMLObject object = ctx.getSignatureFactory().newXMLObject(content, objectIdValue, null, null); + + objects.add(object); + + // TODO: Report MOA-SP Bug + // + // Direct referencing of the SignedPorperties Id-attribute is not supported by MOA-SP + // because the QualifyingProperties are parsed without the XAdES schema. Therefore, + // the shorthand XPointer could not be resolved. + // + // The following workaround uses an XPointer to select the SignedProperties in order + // to allow the signature to be verified with MOA-SP. + + String referenceURI = "#xmlns(xades=http://uri.etsi.org/01903/v1.1.1%23)%20xpointer(id('" + + objectIdValue + + "')/child::xades:QualifyingProperties/child::xades:SignedProperties)"; + DigestMethod dm; + try { + dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod algorithm.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get DigestMethod algorithm.", e); + throw new SLCommandException(4006); + } + + String referenceIdValue = ctx.getIdValueFactory().createIdValue("Reference"); + String referenceType = QualifyingPropertiesFactory.SIGNED_PROPERTIES_REFERENCE_TYPE_V1_1_1; + + Reference reference = ctx.getSignatureFactory().newReference(referenceURI, dm, null, referenceType, referenceIdValue); + + references.add(reference); + + Node child = fragment.getFirstChild(); + if (child instanceof Element) { + NodeList nodes = ((Element) child).getElementsByTagNameNS(QualifyingPropertiesFactory.NS_URI_V1_1_1, "SignedProperties"); + if (nodes.getLength() > 0) { + IdAttribute idAttribute = new IdAttribute(); + idAttribute.element = (Element) nodes.item(0); + idAttribute.namespaceURI = null; + idAttribute.localName = "Id"; + idAttributes.add(idAttribute); + } + } + + } + + /** + * Parse the SignatureEnvironment. + * + * @param signatureEnvironment + * the SignatureEnvironment element + * @param supplements + * an optional list of Supplements (may be + * null) + * + * @return the parsed SignatureEnvironment document + * + * @throws SLCommandException + * if parsing the SignatureEnvironment fails + * @throws NullPointerException + * if signatureEnvironment is null + */ + private Document parseSignatureEnvironment( + Base64XMLOptRefContentType signatureEnvironment, + List supplements) throws SLCommandException { + + if (signatureEnvironment == null) { + throw new NullPointerException("Argument 'signatureEnvironment' must not be null."); + } + + LSInput input; + try { + if (signatureEnvironment.getReference() != null) { + log.debug("SignatureEnvironment contains Reference " + signatureEnvironment.getReference() + "."); + input = createLSInput(signatureEnvironment.getReference()); + } else if (signatureEnvironment.getBase64Content() != null) { + log.debug("SignatureEnvironment contains Base64Content."); + input = createLSInput(signatureEnvironment.getBase64Content()); + } else if (signatureEnvironment.getXMLContent() != null) { + log.debug("SignatureEnvironment contains XMLContent."); + input = createLSInput((XMLContentType) signatureEnvironment.getXMLContent()); + } else { + // the schema does not allow us to reach this point + throw new SLCommandException(4000); + } + } catch (IOException e) { + log.info("XML document in which the signature is to be integrated cannot be resolved.", e); + throw new SLCommandException(4100); + } catch (XMLStreamException e) { + log.info("XML document in which the signature is to be integrated cannot be resolved.", e); + throw new SLCommandException(4100); + } + + LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); + DOMConfiguration domConfig = parser.getDomConfig(); + SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); + domConfig.setParameter("error-handler", errorHandler); + LSResourceResolverAdapter resourceResolver = new LSResourceResolverAdapter(supplements); + domConfig.setParameter("resource-resolver", resourceResolver); + domConfig.setParameter("validate", Boolean.TRUE); + + Document doc; + try { + doc = parser.parse(input); + } catch (DOMException e) { + log.info("XML document in which the signature is to be integrated cannot be parsed.", e); + throw new SLCommandException(4101); + } catch (LSException e) { + log.info("XML document in which the signature is to be integrated cannot be parsed.", e); + throw new SLCommandException(4101); + } + + if (resourceResolver.getError() != null) { + log.info("Failed to resolve resource while parsing SignatureEnvironment document.", resourceResolver.getError()); + // we don't stop here, as we only _try_ to parse validating + } + + if (errorHandler.hasFatalErrors()) { + // log fatal errors + if (log.isInfoEnabled()) { + List errorMessages = errorHandler.getErrorMessages(); + StringBuffer sb = new StringBuffer(); + for (String errorMessage : errorMessages) { + sb.append(" "); + sb.append(errorMessage); + } + log.info("XML document in which the signature is to be integrated cannot be parsed." + sb.toString()); + } + throw new SLCommandException(4101); + } + + // log parsed document + if (log.isTraceEnabled()) { + + StringWriter writer = new StringWriter(); + + writer.write("SignatureEnvironment:\n"); + + LSOutput output = domImplLS.createLSOutput(); + output.setCharacterStream(writer); + output.setEncoding("UTF-8"); + LSSerializer serializer = domImplLS.createLSSerializer(); + serializer.write(doc, output); + + log.trace(writer.toString()); + } + + return doc; + + } + + /** + * Creates an LSInput from the given reference URI. + * + * @param reference + * the reference URL + * + * @return an LSInput from the given reference URI + * + * @throws IOException + * if dereferencing the given reference fails + */ + private LSInput createLSInput(String reference) throws IOException { + + URLDereferencer urlDereferencer = URLDereferencer.getInstance(); + StreamData streamData = urlDereferencer.dereference(reference, ctx.getDereferencerContext()); + + String contentType = streamData.getContentType(); + String charset = HttpUtil.getCharset(contentType, true); + InputStreamReader streamReader; + try { + streamReader = new InputStreamReader(streamData.getStream(), charset); + } catch (UnsupportedEncodingException e) { + log.info("Charset " + charset + " not supported. Using default."); + streamReader = new InputStreamReader(streamData.getStream()); + } + + LSInput input = domImplLS.createLSInput(); + input = domImplLS.createLSInput(); + input.setCharacterStream(streamReader); + + return input; + + } + + /** + * Creates an LSInput from the given content bytes. + * + * @param content + * the content bytes + * + * @return an LSInput from the givne content bytes + */ + private LSInput createLSInput(byte[] content) { + + ByteArrayInputStream inputStream = new ByteArrayInputStream(content); + LSInput input = domImplLS.createLSInput(); + input.setByteStream(inputStream); + + return input; + + } + + /** + * Creates an LSInput from the given XML content. + * + * @param content + * the XML content + * @return an LSInput from the given XML content + * + * @throws XMLStreamException + * if reading the XMLStream from the given XML content fails + */ + private LSInput createLSInput(XMLContentType content) throws XMLStreamException { + + ByteArrayOutputStream redirectedStream = content.getRedirectedStream(); + if (redirectedStream != null) { + LSInput input = domImplLS.createLSInput(); + input.setByteStream(new ByteArrayInputStream(redirectedStream.toByteArray())); + return input; + } else { + return null; + } + + } + + /** + * Represents an xsd:Id-attribute value. + * + * @author mcentner + */ + private class IdAttribute { + + private Element element; + + private String namespaceURI; + + private String localName; + + } + + /** + * An implementation of the LSResourceResolver that uses a list of supplements + * to resolve resources. + * + * @author mcentner + */ + private class LSResourceResolverAdapter implements LSResourceResolver { + + List supplements; + + private LSResourceResolverAdapter( + List supplements) { + this.supplements = supplements; + } + + private Exception error; + + /** + * @return the error + */ + public Exception getError() { + return error; + } + + @Override + public LSInput resolveResource(String type, String namespaceURI, + String publicId, String systemId, String baseURI) { + + if (log.isTraceEnabled()) { + log.trace("Resolve resource :" + + "\n type=" + type + + "\n namespaceURI=" + namespaceURI + + "\n publicId=" + publicId + + "\n systemId=" + systemId + + "\n baseURI=" + baseURI); + } + + if (systemId != null) { + + log.debug("Resolve resource '" + systemId + "'."); + + for (DataObjectAssociationType supplement : supplements) { + + Base64XMLLocRefReqRefContentType content = supplement.getContent(); + if (content != null) { + + String reference = content.getReference(); + if (systemId.equals(reference)) { + + try { + if (content.getLocRefContent() != null) { + log.trace("Resolved resource '" + reference + "' to supplement with LocRefContent."); + return createLSInput(content.getLocRefContent()); + } else if (content.getBase64Content() != null) { + log.trace("Resolved resource '" + reference + "' to supplement with Base64Content."); + return createLSInput(content.getBase64Content()); + } else if (content.getXMLContent() != null) { + log.trace("Resolved resource '" + reference + "' to supplement with XMLContent."); + return createLSInput((XMLContentType) content.getXMLContent()); + } else { + return null; + } + } catch (IOException e) { + log.info("Failed to resolve resource '" + systemId + "' to supplement.", e); + error = e; + return null; + } catch (XMLStreamException e) { + log.info("Failed to resolve resource '" + systemId + "' to supplement.", e); + error = e; + return null; + } + + } + + } + + } + + log.info("Failed to resolve resource '" + systemId + "' to supplement. No such supplement."); + + } + + return null; + + } + + + } + +} -- cgit v1.2.3 From 66cfb865fbfa7af514e803003f928d77f1156e46 Mon Sep 17 00:00:00 2001 From: mcentner Date: Thu, 11 Sep 2008 12:16:35 +0000 Subject: Added to be signed data validation. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@32 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../impl/CreateXMLSignatureCommandImpl.java | 13 +-- .../egiz/bku/slcommands/impl/xsect/DataObject.java | 119 ++++++++++++++++++++- .../bku/slcommands/impl/xsect/STALSignature.java | 11 +- .../egiz/bku/slcommands/impl/xsect/Signature.java | 10 +- 4 files changed, 138 insertions(+), 15 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java index 136fa6f3..628326cf 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java @@ -44,7 +44,9 @@ import at.gv.egiz.bku.slcommands.impl.xsect.IdValueFactory; import at.gv.egiz.bku.slcommands.impl.xsect.IdValueFactoryImpl; import at.gv.egiz.bku.slcommands.impl.xsect.Signature; import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLException; import at.gv.egiz.bku.slexceptions.SLRequestException; +import at.gv.egiz.bku.slexceptions.SLViewerException; import at.gv.egiz.dom.DOMUtils; import at.gv.egiz.stal.InfoboxReadRequest; import at.gv.egiz.stal.InfoboxReadResponse; @@ -166,9 +168,10 @@ public class CreateXMLSignatureCommandImpl extends SLCommandImpltrue if validation should be enabled, or + * false otherwise. + */ + public static void enableHashDataInputValidation(boolean validate) { + DataObject.validate = validate; + } + + /** + * @return true if hash data input validation is enabled, + * or false otherwise. + */ + public static boolean isHashDataInputValidationEnabled() { + return validate; + } + + /** + * Valid MIME types. + */ + private static String[] validMimeTypes = DEFAULT_PREFFERED_MIME_TYPES; + + /** + * Sets the list of valid hash data input media types. + *

The array is also used for transformation path selection. + * The transformation path with a final type, that appears in the + * given array in the earliest position is used selected.

+ * + * @param mediaTypes an array of MIME media types. + */ + public static void setValidHashDataInputMediaTypes(String[] mediaTypes) { + validMimeTypes = mediaTypes; + } + /** * The DOM implementation used. */ @@ -184,7 +230,70 @@ public class DataObject { public String getDescription() { return description; } - + + public void validateHashDataInput() throws SLViewerException { + + if (validate) { + + if (reference == null) { + log.error("Medthod validateHashDataInput() called before reference has been created."); + throw new SLViewerException(5000); + } + + InputStream digestInputStream = reference.getDigestInputStream(); + if (digestInputStream == null) { + log.error("Method validateHashDataInput() called before reference has been generated " + + "or reference caching is not enabled."); + throw new SLViewerException(5000); + } + + if (mimeType == null) { + log.info("FinalDataMetaInfo does not specify MIME type of to be signed data."); + // TODO: add detailed message + throw new SLViewerException(5000); + } + + // get MIME media type + String mediaType = mimeType.split(";")[0].trim(); + // and optional charset + String charset = HttpUtil.getCharset(mimeType, false); + + if (Arrays.asList(validMimeTypes).contains(mediaType)) { + + Validator validator; + try { + validator = ValidatorFactory.newValidator(mediaType); + } catch (IllegalArgumentException e) { + log.error("No validator found for mime type '" + mediaType + "'."); + throw new SLViewerException(5000); + } + + try { + validator.validate(digestInputStream, charset); + } catch (ValidationException e) { + if ("text/plain".equals(mediaType)) { + log.info("Data to be displayed contains unsupported characters.", e); + // TODO: add detailed message + throw new SLViewerException(5003); + } else if ("application/xhtml+xml".equals(mediaType)) { + // TODO: add detailed message + log.info("Standard display format: HTML does not conform to specification.", e); + throw new SLViewerException(5004); + } else { + // TODO: add detailed message + log.info("Data to be displayed is invalid.", e); + throw new SLViewerException(5000); + } + } + + } else { + log.info("MIME media type '" + mediaType + "' is not a valid digest input."); + throw new SLViewerException(5001); + } + } + + } + /** * Configures this DataObject with the information provided within the given * sl:DataObjectInfo. diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java index eba1d96d..2d89c8ae 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java @@ -17,6 +17,8 @@ package at.gv.egiz.bku.slcommands.impl.xsect; import at.gv.egiz.bku.slcommands.impl.HashDataInputImpl; +import at.gv.egiz.bku.slexceptions.SLViewerException; + import java.io.ByteArrayOutputStream; import java.security.InvalidKeyException; import java.security.InvalidParameterException; @@ -123,9 +125,14 @@ public class STALSignature extends SignatureSpi { // log.debug("got " + dataObjects.size() + " DataObjects, passing HashDataInputs to STAL SignRequest"); List hashDataInputs = new ArrayList(); - for (DataObject dataObject : dataObjects) { - hashDataInputs.add(new HashDataInputImpl(dataObject)); + for (DataObject dataObject : dataObjects) { + try { + dataObject.validateHashDataInput(); + } catch (SLViewerException e) { + throw new STALSignatureException(e); } + hashDataInputs.add(new HashDataInputImpl(dataObject)); + } SignRequest signRequest = new SignRequest(); signRequest.setKeyIdentifier(keyboxIdentifier); diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java index 191f8371..2330ed3f 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java @@ -81,6 +81,7 @@ import at.buergerkarte.namespaces.securitylayer._1.SignatureInfoCreationType; import at.gv.egiz.bku.binding.HttpUtil; import at.gv.egiz.bku.slexceptions.SLCommandException; import at.gv.egiz.bku.slexceptions.SLRequestException; +import at.gv.egiz.bku.slexceptions.SLViewerException; import at.gv.egiz.bku.utils.HexDump; import at.gv.egiz.bku.utils.urldereferencer.StreamData; import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; @@ -387,10 +388,11 @@ public class Signature { * if signing the XMLSignature fails * @throws SLCommandException * if building the XMLSignature fails + * @throws SLViewerException * @throws NullPointerException * if signContext is null */ - public void sign(DOMSignContext signContext) throws MarshalException, XMLSignatureException, SLCommandException { + public void sign(DOMSignContext signContext) throws MarshalException, XMLSignatureException, SLCommandException, SLViewerException { if (xmlSignature == null) { buildXMLSignature(); @@ -415,6 +417,9 @@ public class Signature { Throwable cause = e.getCause(); while (cause != null) { if (cause instanceof STALSignatureException) { + if (((STALSignatureException) cause).getCause() instanceof SLViewerException) { + throw (SLViewerException) ((STALSignatureException) cause).getCause(); + } int errorCode = ((STALSignatureException) cause).getErrorCode(); SLCommandException commandException = new SLCommandException(errorCode); log.info("Failed to sign signature.", commandException); @@ -482,11 +487,12 @@ public class Signature { * if signing this Signature fails * @throws SLCommandException * if building this Signature fails + * @throws SLViewerException * @throws NullPointerException * if stal or keyboxIdentifier is * null */ - public void sign(STAL stal, String keyboxIdentifier) throws MarshalException, XMLSignatureException, SLCommandException { + public void sign(STAL stal, String keyboxIdentifier) throws MarshalException, XMLSignatureException, SLCommandException, SLViewerException { if (stal == null) { throw new NullPointerException("Argument 'stal' must not be null."); -- cgit v1.2.3 From 76bb812a3254be530e403f8db8c01323a31b30c1 Mon Sep 17 00:00:00 2001 From: wbauer Date: Thu, 11 Sep 2008 13:03:44 +0000 Subject: git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@33 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java index 555f83bd..fb624211 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java @@ -16,12 +16,14 @@ */ package at.gv.egiz.bku.slcommands.impl; -import at.buergerkarte.namespaces.securitylayer._1.ErrorResponseType; -import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; -import at.gv.egiz.bku.slcommands.ErrorResult; -import at.gv.egiz.bku.slexceptions.SLException; - -import javax.xml.transform.Result; +import java.util.Locale; + +import javax.xml.transform.Result; + +import at.buergerkarte.namespaces.securitylayer._1.ErrorResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.gv.egiz.bku.slcommands.ErrorResult; +import at.gv.egiz.bku.slexceptions.SLException; /** * This class implements the security layer result ErrorResponse. -- cgit v1.2.3 From 0df8bb10302989f41ed420ec0ff29b2fc2005471 Mon Sep 17 00:00:00 2001 From: wbauer Date: Mon, 15 Sep 2008 14:18:53 +0000 Subject: Migrated BKULocal to BKUCommonGUI and minor bug fixes git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@37 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../egiz/bku/slcommands/impl/xsect/Signature.java | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java index 2330ed3f..8baa0137 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java @@ -463,6 +463,31 @@ public class Signature { log.trace("Reference caching is not enabled."); } } + for (Reference reference : getReferences()) { + if (reference.getType() != null) { + InputStream digestInputStream = reference.getDigestInputStream(); + if (digestInputStream != null) { + StringBuilder sb = new StringBuilder(); + sb.append("DigestInput for Reference with id='"); + sb.append(reference.getId()); + sb.append("'; Type:"); + sb.append(reference.getType()); + sb.append("):\n"); + try { + byte[] b = new byte[512]; + for (int l; (l = digestInputStream.read(b)) != -1;) { + sb.append(new String(b, 0, l)); + } + } catch (IOException e) { + log.error(e); + } + log.trace(sb.toString()); + } else { + log.trace("Reference caching is not enabled."); + } + + } + } } } -- cgit v1.2.3 From fd1db02bdc9fbd2a5beca0cc2b214c1adbcc1a7a Mon Sep 17 00:00:00 2001 From: clemenso Date: Mon, 15 Sep 2008 18:01:32 +0000 Subject: encoding git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@39 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java index 49d3c63f..d6999404 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java @@ -4,6 +4,7 @@ */ package at.gv.egiz.bku.slcommands.impl; +import at.gv.egiz.bku.binding.HttpUtil; import at.gv.egiz.bku.slcommands.impl.xsect.DataObject; import at.gv.egiz.stal.HashDataInput; import java.io.InputStream; @@ -16,11 +17,14 @@ public class HashDataInputImpl implements HashDataInput { String refId; String mimeType; + String encoding; InputStream hashDataInput; public HashDataInputImpl(DataObject dataObject) { refId = dataObject.getReference().getId(); - mimeType = dataObject.getMimeType(); + String contentType = dataObject.getMimeType(); + mimeType = contentType.split(";")[0].trim(); + encoding = HttpUtil.getCharset(dataObject.getMimeType(), false); hashDataInput = dataObject.getReference().getDigestInputStream(); } @@ -39,4 +43,9 @@ public class HashDataInputImpl implements HashDataInput { return hashDataInput; } + @Override + public String getEncoding() { + return encoding; + } + } -- cgit v1.2.3 From f72d5842828ec072813eb30051d24f7cc8613606 Mon Sep 17 00:00:00 2001 From: clemenso Date: Wed, 17 Sep 2008 17:18:14 +0000 Subject: hashdatainput digest verification git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@45 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/DataObjectHashDataInput.java | 50 +++++++++++++++++++++ .../bku/slcommands/impl/HashDataInputImpl.java | 51 ---------------------- .../bku/slcommands/impl/xsect/STALSignature.java | 4 +- 3 files changed, 52 insertions(+), 53 deletions(-) create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java delete mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java new file mode 100644 index 00000000..71b62911 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java @@ -0,0 +1,50 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package at.gv.egiz.bku.slcommands.impl; + +import at.gv.egiz.bku.binding.HttpUtil; +import at.gv.egiz.bku.slcommands.impl.xsect.DataObject; +import at.gv.egiz.stal.HashDataInput; +import java.io.InputStream; + +/** + * + * @author clemens + */ +public class DataObjectHashDataInput implements HashDataInput { + + protected DataObject dataObject; + + public DataObjectHashDataInput(DataObject dataObject) { + if (dataObject.getReference() == null) + throw new NullPointerException("DataObject reference must not be null"); + this.dataObject = dataObject; + } + + @Override + public String getReferenceId() { + return dataObject.getReference().getId(); + } + + @Override + public String getMimeType() { + return dataObject.getMimeType(); + } + + /** + * + * @return the pre-digested input stream if reference caching is enabled, null otherwise + */ + @Override + public InputStream getHashDataInput() { + return dataObject.getReference().getDigestInputStream(); + } + + @Override + public String getEncoding() { + return HttpUtil.getCharset(dataObject.getMimeType(), false); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java deleted file mode 100644 index d6999404..00000000 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/HashDataInputImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package at.gv.egiz.bku.slcommands.impl; - -import at.gv.egiz.bku.binding.HttpUtil; -import at.gv.egiz.bku.slcommands.impl.xsect.DataObject; -import at.gv.egiz.stal.HashDataInput; -import java.io.InputStream; - -/** - * - * @author clemens - */ -public class HashDataInputImpl implements HashDataInput { - - String refId; - String mimeType; - String encoding; - InputStream hashDataInput; - - public HashDataInputImpl(DataObject dataObject) { - refId = dataObject.getReference().getId(); - String contentType = dataObject.getMimeType(); - mimeType = contentType.split(";")[0].trim(); - encoding = HttpUtil.getCharset(dataObject.getMimeType(), false); - hashDataInput = dataObject.getReference().getDigestInputStream(); - } - - @Override - public String getReferenceId() { - return refId; - } - - @Override - public String getMimeType() { - return mimeType; - } - - @Override - public InputStream getHashDataInput() { - return hashDataInput; - } - - @Override - public String getEncoding() { - return encoding; - } - -} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java index 2d89c8ae..dd7c7d8a 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java @@ -16,7 +16,7 @@ */ package at.gv.egiz.bku.slcommands.impl.xsect; -import at.gv.egiz.bku.slcommands.impl.HashDataInputImpl; +import at.gv.egiz.bku.slcommands.impl.DataObjectHashDataInput; import at.gv.egiz.bku.slexceptions.SLViewerException; import java.io.ByteArrayOutputStream; @@ -131,7 +131,7 @@ public class STALSignature extends SignatureSpi { } catch (SLViewerException e) { throw new STALSignatureException(e); } - hashDataInputs.add(new HashDataInputImpl(dataObject)); + hashDataInputs.add(new DataObjectHashDataInput(dataObject)); } SignRequest signRequest = new SignRequest(); -- cgit v1.2.3 From a20fb683943ce0893302b6dc25015c998cd9687f Mon Sep 17 00:00:00 2001 From: clemenso Date: Thu, 18 Sep 2008 09:25:55 +0000 Subject: hashdatainput cached git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@46 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java index 71b62911..0386bdd6 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java @@ -10,7 +10,9 @@ import at.gv.egiz.stal.HashDataInput; import java.io.InputStream; /** - * + * DataObject-backed HashDataInput + * If reference caching is enabled, + * the hashdata input stream can be obtained repeatedly. * @author clemens */ public class DataObjectHashDataInput implements HashDataInput { @@ -34,7 +36,7 @@ public class DataObjectHashDataInput implements HashDataInput { } /** - * + * may be called repeatedly * @return the pre-digested input stream if reference caching is enabled, null otherwise */ @Override -- cgit v1.2.3 From 40e57f6c9101ddcc00422d95086d6a485c3ceda2 Mon Sep 17 00:00:00 2001 From: clemenso Date: Thu, 18 Sep 2008 15:52:02 +0000 Subject: mimetype git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@52 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java index 0386bdd6..1a9b56fb 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java @@ -32,7 +32,8 @@ public class DataObjectHashDataInput implements HashDataInput { @Override public String getMimeType() { - return dataObject.getMimeType(); + String contentType = dataObject.getMimeType(); + return contentType.split(";")[0].trim(); } /** -- cgit v1.2.3 From 3edfbe631f24d73324bc4dd0d182ca7737c4d5b5 Mon Sep 17 00:00:00 2001 From: mcentner Date: Wed, 24 Sep 2008 13:56:53 +0000 Subject: Improved SLResult marshalling. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@66 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../impl/CreateXMLSignatureResultImpl.java | 73 ++--- .../egiz/bku/slcommands/impl/ErrorResultImpl.java | 21 +- .../slcommands/impl/InfoboxReadCommandImpl.java | 320 ++++++++++++++++----- .../slcommands/impl/InfoboxReadResultFileImpl.java | 141 +++++++++ .../bku/slcommands/impl/InfoboxReadResultImpl.java | 190 +++--------- .../slcommands/impl/NullOperationResultImpl.java | 5 +- .../gv/egiz/bku/slcommands/impl/SLResultImpl.java | 166 ++++++++--- 7 files changed, 588 insertions(+), 328 deletions(-) create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java index d2d2e678..092a13c4 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java @@ -16,28 +16,24 @@ */ package at.gv.egiz.bku.slcommands.impl; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.transform.Result; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import at.buergerkarte.namespaces.securitylayer._1.CreateXMLSignatureResponseType; -import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; -import at.gv.egiz.bku.slcommands.SLCommandFactory; -import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.transform.Result; +import javax.xml.transform.Templates; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import at.buergerkarte.namespaces.securitylayer._1.CreateXMLSignatureResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.gv.egiz.bku.slcommands.SLCommandFactory; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; /** * This calls implements the result of the security layer command CreateXMLSignature. @@ -104,35 +100,10 @@ public class CreateXMLSignatureResultImpl extends SLResultImpl { } } - - @Override - public void writeTo(Result result) { - - try { - writeTo(result, null); - } catch (TransformerException e) { - log.error(e); - } - - } - - /* (non-Javadoc) - * @see at.gv.egiz.bku.slcommands.impl.SLResultImpl#writeTo(javax.xml.transform.Result, javax.xml.transform.Transformer) - */ - @Override - public void writeTo(Result result, Transformer transformer) throws TransformerException { - - if (transformer == null) { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - try { - transformer = transformerFactory.newTransformer(); - } catch (TransformerConfigurationException e) { - log.error("Failed to create Transformer.", e); - throw new SLRuntimeException(e); - } - } - transformer.transform(new DOMSource(doc), result); - + + @Override + public void writeTo(Result result, Templates templates) { + writeTo(doc, result, templates); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java index fb624211..176ba001 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java @@ -16,12 +16,9 @@ */ package at.gv.egiz.bku.slcommands.impl; -import java.util.Locale; - import javax.xml.transform.Result; +import javax.xml.transform.Templates; -import at.buergerkarte.namespaces.securitylayer._1.ErrorResponseType; -import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; import at.gv.egiz.bku.slcommands.ErrorResult; import at.gv.egiz.bku.slexceptions.SLException; @@ -48,15 +45,9 @@ public class ErrorResultImpl extends SLResultImpl implements ErrorResult { this.slException = slException; } - @Override - public void writeTo(Result result) { - - ObjectFactory factory = new ObjectFactory(); - ErrorResponseType responseType = factory.createErrorResponseType(); - responseType.setErrorCode(slException.getErrorCode()); - responseType.setInfo(slException.getDetailedMsg()); - - writeTo(factory.createErrorResponse(responseType), result); - - } + @Override + public void writeTo(Result result, Templates templates) { + writeErrorTo(slException, result, templates); + } + } \ No newline at end of file diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java index b6745e1f..4d64ae36 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java @@ -16,55 +16,66 @@ */ package at.gv.egiz.bku.slcommands.impl; -import iaik.asn1.CodingException; -import iaik.asn1.DerCoder; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Result; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMResult; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -import at.buergerkarte.namespaces.personenbindung._20020506_.CompressedIdentityLinkType; -import at.buergerkarte.namespaces.securitylayer._1.AnyChildrenType; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsBinaryFileType; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; -import at.gv.egiz.bku.slcommands.InfoboxReadCommand; -import at.gv.egiz.bku.slcommands.SLCommand; -import at.gv.egiz.bku.slcommands.SLCommandContext; -import at.gv.egiz.bku.slcommands.SLResult; -import at.gv.egiz.bku.slexceptions.SLCommandException; -import at.gv.egiz.bku.slexceptions.SLExceptionMessages; -import at.gv.egiz.bku.slexceptions.SLRuntimeException; -import at.gv.egiz.idlink.CompressedIdentityLinkFactory; -import at.gv.egiz.idlink.IdentityLinkTransformer; -import at.gv.egiz.idlink.ans1.IdentityLink; -import at.gv.egiz.stal.InfoboxReadRequest; -import at.gv.egiz.stal.InfoboxReadResponse; -import at.gv.egiz.stal.STALRequest; +import iaik.asn1.CodingException; +import iaik.asn1.DerCoder; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Result; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import at.buergerkarte.namespaces.personenbindung._20020506_.CompressedIdentityLinkType; +import at.buergerkarte.namespaces.securitylayer._1.AnyChildrenType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxAssocArrayPairType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadDataAssocArrayType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsBinaryFileType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadKeys; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadPairs; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadValue; +import at.gv.egiz.bku.slcommands.InfoboxReadCommand; +import at.gv.egiz.bku.slcommands.SLCommand; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slcommands.SLResult; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLExceptionMessages; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import at.gv.egiz.idlink.CompressedIdentityLinkFactory; +import at.gv.egiz.idlink.IdentityLinkTransformer; +import at.gv.egiz.idlink.ans1.IdentityLink; +import at.gv.egiz.stal.InfoboxReadRequest; +import at.gv.egiz.stal.InfoboxReadResponse; +import at.gv.egiz.stal.STALRequest; /** * This class implements the security layer command @@ -82,23 +93,45 @@ public class InfoboxReadCommandImpl extends SLCommandImplInfoboxIdentifier */ protected String infoboxIdentifier; /** - * The IdentityLinkDomainIdentifier value of an IdentyLink infobox. + * The IdentityLinkDomainIdentifier value of an IdentyLink infobox. */ - protected String identityLinkDomainIdentifier; + protected String identityLinkDomainIdentifier; + + /** + * The list of certificates to be read from an Certificates infobox. + */ + protected List certificates; + + /** + * The result type. + */ + protected int assocArrayResult; /** * Is content XML entity? @@ -125,12 +158,6 @@ public class InfoboxReadCommandImpl extends SLCommandImpl 1) { + log.info("UserMakesUnique not supported"); + // TODO: give more specific error message + throw new SLCommandException(4010); + } + } + + // ReadPairs? + if (assocArrayParameters.getReadPairs() != null) { + assocArrayResult = ASSOC_ARRAY_READ_PAIRS; + ReadPairs readPairs = assocArrayParameters.getReadPairs(); + if (readPairs.isValuesAreXMLEntities()) { + log.info("Got valuesAreXMLEntities but infobox type is binary."); + throw new SLCommandException(4010); + } + certificates = findCertificates(readPairs.getSearchString()); + if (readPairs.isUserMakesUnique() && certificates.size() > 1) { + log.info("UserMakesUnique not supported"); + // TODO: give more specific error message + throw new SLCommandException(4010); + } + } + + // ReadValue + if (assocArrayParameters.getReadValue() != null) { + assocArrayResult = ASSOC_ARRAY_READ_VALUE; + ReadValue readValue = assocArrayParameters.getReadValue(); + if (readValue.isValueIsXMLEntity()) { + log.info("Got valuesAreXMLEntities but infobox type is binary."); + throw new SLCommandException(4010); + } + String key = readValue.getKey(); + if (Arrays.asList(INFOXBOX_CERTIFICATES_KEYS).contains(key)) { + certificates = Collections.singletonList(key); + } else { + certificates = Collections.emptyList(); + } + } + + if (assocArrayResult == 0) { + log.info("Infobox type is AssocArray but got invalid AssocArrayParameters."); + throw new SLCommandException(4010); + } } else { throw new SLCommandException(4002, @@ -168,9 +268,15 @@ public class InfoboxReadCommandImpl extends SLCommandImpl findCertificates(String searchString) throws SLCommandException { + + if ("*".equals(searchString) || "**".equals(searchString)) { + return Arrays.asList(INFOXBOX_CERTIFICATES_KEYS); + } + + if (Pattern.matches(SEARCH_STRING_PATTERN, searchString)) { + +// for (int i = 0; i < searchString.length(); i++) { +// int codePoint = searchString.codePointAt(i); +// +// } + + // TODO : build pattern + return Collections.emptyList(); + } else { + log.info("Got invalid search string '" + searchString + "'"); + throw new SLCommandException(4010); + } + + } + + private SLResult readCertificates() throws SLCommandException { + + ObjectFactory objectFactory = new ObjectFactory(); + + InfoboxReadDataAssocArrayType infoboxReadDataAssocArrayType = objectFactory + .createInfoboxReadDataAssocArrayType(); + + if (assocArrayResult == ASSOC_ARRAY_READ_KEYS) { - @Override - public String getIdentityLinkDomainId() { - return identityLinkDomainIdentifier; - } + List keys = infoboxReadDataAssocArrayType.getKey(); + keys.addAll(certificates); + + } else { + + if (certificates != null && !certificates.isEmpty()) { + + List stalRequests = new ArrayList(); + + // get certificates + InfoboxReadRequest infoboxReadRequest; + for (int i = 0; i < certificates.size(); i++) { + infoboxReadRequest = new InfoboxReadRequest(); + infoboxReadRequest.setInfoboxIdentifier(certificates.get(i)); + stalRequests.add(infoboxReadRequest); + } + + requestSTAL(stalRequests); + + List x509Certs = getCertificatesFromResponses(); + + for (int i = 0; i < certificates.size(); i++) { + InfoboxAssocArrayPairType infoboxAssocArrayPairType = objectFactory.createInfoboxAssocArrayPairType(); + infoboxAssocArrayPairType.setKey(certificates.get(i)); + try { + infoboxAssocArrayPairType.setBase64Content(x509Certs.get(i).getEncoded()); + } catch (CertificateEncodingException e) { + log.error("Failed to encode certificate.", e); + throw new SLCommandException(4000); + } + infoboxReadDataAssocArrayType.getPair().add(infoboxAssocArrayPairType); + } + + } + + } + + return new InfoboxReadResultImpl(infoboxReadDataAssocArrayType); + + } + + @Override + public String getIdentityLinkDomainId() { + return identityLinkDomainIdentifier; + } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java new file mode 100644 index 00000000..6f41b562 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java @@ -0,0 +1,141 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Result; +import javax.xml.transform.Templates; +import javax.xml.transform.dom.DOMResult; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; + +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLContentType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.buergerkarte.namespaces.securitylayer._1.XMLContentType; +import at.gv.egiz.bku.slcommands.InfoboxReadResult; +import at.gv.egiz.bku.slcommands.SLCommand; +import at.gv.egiz.bku.slcommands.SLCommandFactory; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; + +/** + * This class implements the result of the security layer command InfoboxReadRequest. + * + * @author mcentner + */ +public class InfoboxReadResultFileImpl extends SLResultImpl implements + InfoboxReadResult { + + /** + * Logging facility. + */ + protected static Log log = LogFactory.getLog(InfoboxReadResultFileImpl.class); + + /** + * The XML document containing the infobox content. + */ + Document xmlDocument; + + /** + * Creates the response document from the given binaryContent. + * + * @param binaryContent the infobox content + * @param preserveSpace the value of the preserveSpace parameter + * + * @return the created response document + */ + private Document createResponseDocument(byte[] binaryContent, boolean preserveSpace) { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + Document doc; + try { + doc = dbf.newDocumentBuilder().newDocument(); + } catch (ParserConfigurationException e) { + // it should always be possible to create a new Document + log.error("Failed to create XML document.", e); + throw new SLRuntimeException(e); + } + + ObjectFactory factory = new ObjectFactory(); + + Base64XMLContentType base64XMLContentType = factory.createBase64XMLContentType(); + if (binaryContent == null) { + XMLContentType xmlContentType = factory.createXMLContentType(); + if (preserveSpace) { + xmlContentType.setSpace("preserve"); + } + base64XMLContentType.setXMLContent(xmlContentType); + } else { + base64XMLContentType.setBase64Content(binaryContent); + } + InfoboxReadResponseType infoboxReadResponseType = factory.createInfoboxReadResponseType(); + infoboxReadResponseType.setBinaryFileData(base64XMLContentType); + + JAXBElement infoboxReadResponse = factory.createInfoboxReadResponse(infoboxReadResponseType); + + JAXBContext context = SLCommandFactory.getJaxbContext(); + try { + Marshaller marshaller = context.createMarshaller(); + marshaller.marshal(infoboxReadResponse, doc); + } catch (JAXBException e) { + log.error("Failed to marshal 'InfoboxReadResponse' document.", e); + throw new SLRuntimeException(e); + } + + return doc; + + } + + + /** + * @return an XMLResult for marshalling the infobox to + */ + Result getXmlResult(boolean preserveSpace) { + + xmlDocument = createResponseDocument(null, preserveSpace); + + NodeList nodeList = xmlDocument.getElementsByTagNameNS(SLCommand.NAMESPACE_URI, "XMLContent"); + return new DOMResult(nodeList.item(0)); + + } + + /** + * Creates a new result document for this InfoboxReadResult + * and sets the given resultBytes as content. + * + * @param resultBytes + */ + void setResultBytes(byte[] resultBytes) { + + xmlDocument = createResponseDocument(resultBytes, false); + + } + + @Override + public void writeTo(Result result, Templates templates) { + writeTo(xmlDocument, result, templates); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java index 6f07338f..8904eac6 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java @@ -14,158 +14,38 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package at.gv.egiz.bku.slcommands.impl; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Result; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMResult; -import javax.xml.transform.dom.DOMSource; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; - -import at.buergerkarte.namespaces.securitylayer._1.Base64XMLContentType; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadResponseType; -import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; -import at.buergerkarte.namespaces.securitylayer._1.XMLContentType; -import at.gv.egiz.bku.slcommands.InfoboxReadResult; -import at.gv.egiz.bku.slcommands.SLCommand; -import at.gv.egiz.bku.slcommands.SLCommandFactory; -import at.gv.egiz.bku.slexceptions.SLRuntimeException; - -/** - * This class implements the result of the security layer command InfoboxReadRequest. - * - * @author mcentner - */ -public class InfoboxReadResultImpl extends SLResultImpl implements - InfoboxReadResult { - - /** - * Logging facility. - */ - protected static Log log = LogFactory.getLog(InfoboxReadResultImpl.class); - - /** - * The XML document containing the infobox content. - */ - Document xmlDocument; - - /** - * Creates the response document from the given binaryContent. - * - * @param binaryContent the infobox content - * @param preserveSpace the value of the preserveSpace parameter - * - * @return the created response document - */ - private Document createResponseDocument(byte[] binaryContent, boolean preserveSpace) { - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - Document doc; - try { - doc = dbf.newDocumentBuilder().newDocument(); - } catch (ParserConfigurationException e) { - // it should always be possible to create a new Document - log.error("Failed to create XML document.", e); - throw new SLRuntimeException(e); - } - - ObjectFactory factory = new ObjectFactory(); - - Base64XMLContentType base64XMLContentType = factory.createBase64XMLContentType(); - if (binaryContent == null) { - XMLContentType xmlContentType = factory.createXMLContentType(); - if (preserveSpace) { - xmlContentType.setSpace("preserve"); - } - base64XMLContentType.setXMLContent(xmlContentType); - } else { - base64XMLContentType.setBase64Content(binaryContent); - } - InfoboxReadResponseType infoboxReadResponseType = factory.createInfoboxReadResponseType(); - infoboxReadResponseType.setBinaryFileData(base64XMLContentType); - - JAXBElement infoboxReadResponse = factory.createInfoboxReadResponse(infoboxReadResponseType); - - JAXBContext context = SLCommandFactory.getJaxbContext(); - try { - Marshaller marshaller = context.createMarshaller(); - marshaller.marshal(infoboxReadResponse, doc); - } catch (JAXBException e) { - log.error("Failed to marshal 'InfoboxReadResponse' document.", e); - throw new SLRuntimeException(e); - } - - return doc; - - } - - - /** - * @return an XMLResult for marshalling the infobox to - */ - Result getXmlResult(boolean preserveSpace) { - - xmlDocument = createResponseDocument(null, preserveSpace); - - NodeList nodeList = xmlDocument.getElementsByTagNameNS(SLCommand.NAMESPACE_URI, "XMLContent"); - return new DOMResult(nodeList.item(0)); - - } - - /** - * Creates a new result document for this InfoboxReadResult - * and sets the given resultBytes as content. - * - * @param resultBytes - */ - void setResultBytes(byte[] resultBytes) { - - xmlDocument = createResponseDocument(resultBytes, false); - - } - - @Override - public void writeTo(Result result) { - - try { - writeTo(result, null); - } catch (TransformerException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - /* (non-Javadoc) - * @see at.gv.egiz.bku.slcommands.impl.SLResultImpl#writeTo(javax.xml.transform.Result, javax.xml.transform.Transformer) - */ - @Override - public void writeTo(Result result, Transformer transformer) throws TransformerException { - - if (transformer == null) { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - try { - transformer = transformerFactory.newTransformer(); - } catch (TransformerConfigurationException e) { - log.error("Failed to create Transformer.", e); - throw new SLRuntimeException(e); - } - } - transformer.transform(new DOMSource(xmlDocument), result); - - } - -} +package at.gv.egiz.bku.slcommands.impl; + +import javax.xml.bind.JAXBElement; +import javax.xml.transform.Result; +import javax.xml.transform.Templates; + +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadDataAssocArrayType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; + +public class InfoboxReadResultImpl extends SLResultImpl { + + /** + * The InfoboxReadResponse + */ + protected InfoboxReadResponseType infoboxReadResponse; + + public InfoboxReadResultImpl(InfoboxReadDataAssocArrayType assocArray) { + + ObjectFactory objectFactory = new ObjectFactory(); + InfoboxReadResponseType infoboxReadResponseType = objectFactory.createInfoboxReadResponseType(); + + infoboxReadResponseType.setAssocArrayData(assocArray); + + this.infoboxReadResponse = infoboxReadResponseType; + } + + @Override + public void writeTo(Result result, Templates templates) { + ObjectFactory objectFactory = new ObjectFactory(); + JAXBElement response = objectFactory.createInfoboxReadResponse(infoboxReadResponse); + writeTo(response, result, templates); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java index ae1f91ce..05986f85 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java @@ -18,6 +18,7 @@ package at.gv.egiz.bku.slcommands.impl; import javax.xml.bind.JAXBElement; import javax.xml.transform.Result; +import javax.xml.transform.Templates; import at.buergerkarte.namespaces.securitylayer._1.NullOperationResponseType; import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; @@ -40,8 +41,8 @@ public class NullOperationResultImpl extends SLResultImpl implements NullOperati } @Override - public void writeTo(Result result) { - writeTo(RESPONSE, result); + public void writeTo(Result result, Templates templates) { + writeTo(RESPONSE, result, templates); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java index a79382b6..57309182 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java @@ -16,24 +16,33 @@ */ package at.gv.egiz.bku.slcommands.impl; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.transform.Result; +import javax.xml.transform.Templates; import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Node; +import at.buergerkarte.namespaces.securitylayer._1.ErrorResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; import at.gv.egiz.bku.slcommands.SLCommandFactory; import at.gv.egiz.bku.slcommands.SLResult; +import at.gv.egiz.bku.slexceptions.SLBindingException; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLException; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; /** * This class serves as an abstract base class for the implementation of a @@ -72,46 +81,135 @@ public abstract class SLResultImpl implements SLResult { return resultingMimeType; } + private Marshaller getMarshaller() { + try { + JAXBContext context = SLCommandFactory.getJaxbContext(); + Marshaller marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + return marshaller; + } catch (JAXBException e) { + log.fatal("Failed to marshall error response.", e); + throw new SLRuntimeException("Failed to marshall error response.", e); + } + } + + private TransformerHandler getTransformerHandler(Templates templates, Result result) throws SLException { + try { + SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(templates); + transformerHandler.setResult(result); + return transformerHandler; + } catch (TransformerFactoryConfigurationError e) { + log.error("Failed to create an instance of SAXTransformerFactory.", e); + throw new SLBindingException(2000); + } catch (IllegalArgumentException e) { + log.error("Failed to set result for transformation.", e); + throw new SLBindingException(2000); + } catch (TransformerConfigurationException e) { + log.info("Failed to create an instance of SAXTransformerFactory.", e); + throw new SLBindingException(2008); + } + } + + @Override + public void writeTo(Result result) { + writeTo(result, null); + } + + /** - * Writes the given response to the result. + * Writes the given response to the SAX result using + * the given transform templates. * - * @param response the security layer response element - * @param result the result to marshal the response to + * @param response + * @param result + * @param templates */ - @SuppressWarnings("unchecked") - public void writeTo(JAXBElement response, Result result) { + protected void writeTo(JAXBElement response, Result result, Templates templates) { + TransformerHandler transformerHandler = null; + if (templates != null) { + try { + transformerHandler = getTransformerHandler(templates, result); + } catch (SLException e) { + writeErrorTo(e, result, templates); + } + } + + Marshaller marshaller = getMarshaller(); try { - JAXBContext context = SLCommandFactory.getJaxbContext(); - Marshaller marshaller = context.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.marshal(response, result); + if (transformerHandler != null) { + marshaller.marshal(response, transformerHandler); + } else { + marshaller.marshal(response, result); + } } catch (JAXBException e) { - // TODO Add throws clause to interface - log.fatal("Failed to marshall JAXBElement.", e); - throw new RuntimeException("Failed to marshall JAXBElement.", e); + log.info("Failed to marshall " + response.getName() + " result." , e); + SLCommandException commandException = new SLCommandException(4000); + writeErrorTo(commandException, result, templates); } + + } + + protected void writeTo(Node node, Result result, Templates templates) { + if (templates == null) { + try { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(new DOMSource(node), result); + } catch (TransformerConfigurationException e) { + log.error("Failed to create Transformer.", e); + writeErrorTo(new SLException(4000), result, null); + } catch (TransformerException e) { + log.error("Failed to transform result.", e); + writeErrorTo(new SLException(4000), result, null); + } + } else { + try { + Transformer transformer = templates.newTransformer(); + transformer.transform(new DOMSource(node), result); + } catch (TransformerConfigurationException e) { + log.info("Failed to create transformer.", e); + writeErrorTo(new SLException(2008), result, templates); + } catch (TransformerException e) { + log.error("Failed to transform result.", e); + writeErrorTo(new SLException(2008), result, templates); + } + } + } + + protected void writeErrorTo(SLException slException, Result result, Templates templates) { + + TransformerHandler transformerHandler = null; + if (templates != null) { + try { + transformerHandler = getTransformerHandler(templates, result); + } catch (SLException e) { + // write the exception thrown instead of the given one + slException = e; + } + } - /* (non-Javadoc) - * @see at.gv.egiz.bku.slcommands.SLResult#writeTo(javax.xml.transform.Result, javax.xml.transform.Transformer) - */ - @Override - public void writeTo(Result result, Transformer transformer) throws TransformerException { - // TODO Auto-generated method stub - // fixxme: wb added for testing purposes to be completed - // begin hack - if (transformer == null) { - writeTo(result); - return; + ObjectFactory factory = new ObjectFactory(); + ErrorResponseType responseType = factory.createErrorResponseType(); + responseType.setErrorCode(slException.getErrorCode()); + responseType.setInfo(slException.getDetailedMsg()); + JAXBElement response = factory.createErrorResponse(responseType); + + Marshaller marshaller = getMarshaller(); + try { + if (transformerHandler != null) { + marshaller.marshal(response, transformerHandler); + } else { + marshaller.marshal(response, result); + } + } catch (JAXBException e) { + log.fatal("Failed to marshall error result." , e); + throw new SLRuntimeException("Failed to marshall error result."); } - // just a quick hack to proceed with testing - ByteArrayOutputStream os = new ByteArrayOutputStream(); - writeTo(new StreamResult(os)); - ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); - transformer.transform(new StreamSource(is), result); - //end hack + } } -- cgit v1.2.3 From e21dd5249d5fa19c5619847922cf8cdea95e3145 Mon Sep 17 00:00:00 2001 From: wbauer Date: Thu, 25 Sep 2008 07:29:47 +0000 Subject: improved robustness of http binding processor git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@70 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java index 4d64ae36..b6c89e5b 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java @@ -371,12 +371,12 @@ public class InfoboxReadCommandImpl extends SLCommandImpl certificates = getCertificatesFromResponses(); @@ -413,10 +413,12 @@ public class InfoboxReadCommandImpl extends SLCommandImpl Date: Tue, 21 Oct 2008 15:00:33 +0000 Subject: Simplified IdentityLinkTransformer. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@124 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../bku/slcommands/impl/InfoboxReadCommandImpl.java | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java index b6c89e5b..d23c0598 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java @@ -23,6 +23,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.net.MalformedURLException; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; @@ -415,11 +416,22 @@ public class InfoboxReadCommandImpl extends SLCommandImpl Date: Thu, 30 Oct 2008 10:33:29 +0000 Subject: Updated SMCC to use exclusive access and to throw exceptions upon locked or not activated cards. Improved locale support in the security layer request and response processing. Fixed issue in STAL which prevented the use of RSA-SHA1 signatures. Added additional parameters to the applet test pages. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@128 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../impl/CreateXMLSignatureCommandImpl.java | 4 +-- .../egiz/bku/slcommands/impl/ErrorResultImpl.java | 42 ++++++++++++++-------- .../slcommands/impl/InfoboxReadCommandImpl.java | 2 +- .../gv/egiz/bku/slcommands/impl/SLResultImpl.java | 8 ++++- 4 files changed, 38 insertions(+), 18 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java index 628326cf..6462bcf6 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java @@ -216,8 +216,8 @@ public class CreateXMLSignatureCommandImpl extends SLCommandImplErrorResponse. */ - protected SLException slException; - - /** - * Creates a new instance of this ErrorResultImpl with the given - * slException containing information provided in the - * ErrorResponse. - * - * @param slException the exception - */ - public ErrorResultImpl(SLException slException) { - this.slException = slException; - } - + protected SLException slException; + + /** + * The locale to be used for rendering an ErrorResponse. + */ + protected Locale locale; + + /** + * Creates a new instance of this ErrorResultImpl with the given + * slException containing information provided in the + * ErrorResponse and the locale for rendering + * the ErrorResponse. + * + * @param slException the exception + * @param locale the locale + */ + public ErrorResultImpl(SLException slException, Locale locale) { + this.slException = slException; + this.locale = locale; + } + @Override public void writeTo(Result result, Templates templates) { - writeErrorTo(slException, result, templates); + if (locale == null) { + writeErrorTo(slException, result, templates); + } else { + writeErrorTo(slException, result, templates, locale); + } } } \ No newline at end of file diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java index d23c0598..c7bb5205 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java @@ -279,7 +279,7 @@ public class InfoboxReadCommandImpl extends SLCommandImpl response = factory.createErrorResponse(responseType); Marshaller marshaller = getMarshaller(); -- cgit v1.2.3 From 7201a18efa2f9aac4109b1accb5de9d8449dd558 Mon Sep 17 00:00:00 2001 From: wbauer Date: Fri, 14 Nov 2008 10:34:30 +0000 Subject: git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@169 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../impl/CreateXMLSignatureCommandImpl.java | 446 +++++++++++---------- 1 file changed, 230 insertions(+), 216 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java index 6462bcf6..b2e3b303 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java @@ -1,230 +1,244 @@ /* -* Copyright 2008 Federal Chancellery Austria and -* Graz University of Technology -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package at.gv.egiz.bku.slcommands.impl; - -import java.io.ByteArrayInputStream; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Date; - -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.URIReferenceException; -import javax.xml.crypto.dsig.XMLSignatureException; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSSerializer; - -import at.buergerkarte.namespaces.securitylayer._1.CreateXMLSignatureRequestType; -import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; -import at.gv.egiz.bku.slcommands.CreateXMLSignatureCommand; -import at.gv.egiz.bku.slcommands.SLCommandContext; -import at.gv.egiz.bku.slcommands.SLResult; -import at.gv.egiz.bku.slcommands.impl.xsect.AlgorithmMethodFactory; -import at.gv.egiz.bku.slcommands.impl.xsect.AlgorithmMethodFactoryImpl; -import at.gv.egiz.bku.slcommands.impl.xsect.IdValueFactory; -import at.gv.egiz.bku.slcommands.impl.xsect.IdValueFactoryImpl; -import at.gv.egiz.bku.slcommands.impl.xsect.Signature; -import at.gv.egiz.bku.slexceptions.SLCommandException; + * Copyright 2008 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package at.gv.egiz.bku.slcommands.impl; + +import java.io.ByteArrayInputStream; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Collections; +import java.util.Date; + +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.URIReferenceException; +import javax.xml.crypto.dsig.XMLSignatureException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSSerializer; + +import at.buergerkarte.namespaces.securitylayer._1.CreateXMLSignatureRequestType; +import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; +import at.gv.egiz.bku.slcommands.CreateXMLSignatureCommand; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slcommands.SLResult; +import at.gv.egiz.bku.slcommands.impl.xsect.AlgorithmMethodFactory; +import at.gv.egiz.bku.slcommands.impl.xsect.AlgorithmMethodFactoryImpl; +import at.gv.egiz.bku.slcommands.impl.xsect.IdValueFactory; +import at.gv.egiz.bku.slcommands.impl.xsect.IdValueFactoryImpl; +import at.gv.egiz.bku.slcommands.impl.xsect.Signature; +import at.gv.egiz.bku.slexceptions.SLCommandException; import at.gv.egiz.bku.slexceptions.SLException; -import at.gv.egiz.bku.slexceptions.SLRequestException; +import at.gv.egiz.bku.slexceptions.SLRequestException; import at.gv.egiz.bku.slexceptions.SLViewerException; -import at.gv.egiz.dom.DOMUtils; -import at.gv.egiz.stal.InfoboxReadRequest; -import at.gv.egiz.stal.InfoboxReadResponse; -import at.gv.egiz.stal.STALRequest; -import at.gv.egiz.stal.STALResponse; - -/** - * This class implements the security layer command CreateXMLSignatureRequest. - * - * @author mcentner - */ -public class CreateXMLSignatureCommandImpl extends SLCommandImpl implements - CreateXMLSignatureCommand { - - /** - * Logging facility. - */ - protected static Log log = LogFactory.getLog(CreateXMLSignatureCommandImpl.class); - - /** - * The signing certificate. - */ - protected X509Certificate signingCertificate; - - /** - * The keybox identifier of the key used for signing. - */ - protected String keyboxIdentifier; - - /** - * The to-be signed signature. - */ - protected Signature signature; - - @Override - public void init(SLCommandContext ctx, Object unmarshalledRequest) - throws SLCommandException { - super.init(ctx, unmarshalledRequest); - } - - @Override - public void prepareXMLSignature() throws SLCommandException, SLRequestException { - - CreateXMLSignatureRequestType request = getRequestValue(); - +import at.gv.egiz.dom.DOMUtils; +import at.gv.egiz.stal.ErrorResponse; +import at.gv.egiz.stal.InfoboxReadRequest; +import at.gv.egiz.stal.InfoboxReadResponse; +import at.gv.egiz.stal.STALRequest; +import at.gv.egiz.stal.STALResponse; + +/** + * This class implements the security layer command + * CreateXMLSignatureRequest. + * + * @author mcentner + */ +public class CreateXMLSignatureCommandImpl extends + SLCommandImpl implements + CreateXMLSignatureCommand { + + /** + * Logging facility. + */ + protected static Log log = LogFactory + .getLog(CreateXMLSignatureCommandImpl.class); + + /** + * The signing certificate. + */ + protected X509Certificate signingCertificate; + + /** + * The keybox identifier of the key used for signing. + */ + protected String keyboxIdentifier; + + /** + * The to-be signed signature. + */ + protected Signature signature; + + @Override + public void init(SLCommandContext ctx, Object unmarshalledRequest) + throws SLCommandException { + super.init(ctx, unmarshalledRequest); + } + + @Override + public void prepareXMLSignature() throws SLCommandException, + SLRequestException { + + CreateXMLSignatureRequestType request = getRequestValue(); + // TODO: make configurable? - IdValueFactory idValueFactory = new IdValueFactoryImpl(); - + IdValueFactory idValueFactory = new IdValueFactoryImpl(); + // TODO: make configurable? - AlgorithmMethodFactory algorithmMethodFactory; - try { - algorithmMethodFactory = new AlgorithmMethodFactoryImpl(signingCertificate); - } catch (NoSuchAlgorithmException e) { - log.error("Failed to get DigestMethod.", e); - throw new SLCommandException(4006); - } - - signature = new Signature(getCmdCtx().getURLDereferencerContext(), idValueFactory, algorithmMethodFactory); - + AlgorithmMethodFactory algorithmMethodFactory; + try { + algorithmMethodFactory = new AlgorithmMethodFactoryImpl( + signingCertificate); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } + + signature = new Signature(getCmdCtx().getURLDereferencerContext(), + idValueFactory, algorithmMethodFactory); + // SigningTime - signature.setSigningTime(new Date()); - + signature.setSigningTime(new Date()); + // SigningCertificate - signature.setSignerCeritifcate(signingCertificate); - + signature.setSignerCeritifcate(signingCertificate); + // SignatureInfo - if (request.getSignatureInfo() != null) { - signature.setSignatureInfo(request.getSignatureInfo()); - } - + if (request.getSignatureInfo() != null) { + signature.setSignatureInfo(request.getSignatureInfo()); + } + // DataObjects - for (DataObjectInfoType dataObjectInfo : request.getDataObjectInfo()) { - signature.addDataObject(dataObjectInfo); - } - - signature.buildXMLSignature(); - - } - - /** - * Gets the signing certificate from STAL. - * - * @throws SLCommandException - * if getting the singing certificate fails - */ - private void getSigningCertificate() throws SLCommandException { - - CreateXMLSignatureRequestType request = getRequestValue(); - keyboxIdentifier = request.getKeyboxIdentifier(); - - InfoboxReadRequest stalRequest = new InfoboxReadRequest(); - stalRequest.setInfoboxIdentifier(keyboxIdentifier); - - requestSTAL(Collections.singletonList((STALRequest) stalRequest)); - - STALResponse stalResponse = stalResponses.next(); - - if (stalResponse instanceof InfoboxReadResponse) { - byte[] infobox = ((InfoboxReadResponse) stalResponse).getInfoboxValue(); - - try { - CertificateFactory certFactory = CertificateFactory.getInstance("X509"); - signingCertificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(infobox)); - } catch (CertificateException e) { - log.info("Failed to decode signing certificate.", e); + for (DataObjectInfoType dataObjectInfo : request.getDataObjectInfo()) { + signature.addDataObject(dataObjectInfo); + } + + signature.buildXMLSignature(); + + } + + /** + * Gets the signing certificate from STAL. + * + * @throws SLCommandException + * if getting the singing certificate fails + */ + private void getSigningCertificate() throws SLCommandException { + + CreateXMLSignatureRequestType request = getRequestValue(); + keyboxIdentifier = request.getKeyboxIdentifier(); + + InfoboxReadRequest stalRequest = new InfoboxReadRequest(); + stalRequest.setInfoboxIdentifier(keyboxIdentifier); + + requestSTAL(Collections.singletonList((STALRequest) stalRequest)); + + STALResponse stalResponse = stalResponses.next(); + + if (stalResponse instanceof InfoboxReadResponse) { + byte[] infobox = ((InfoboxReadResponse) stalResponse).getInfoboxValue(); + + try { + CertificateFactory certFactory = CertificateFactory.getInstance("X509"); + signingCertificate = (X509Certificate) certFactory + .generateCertificate(new ByteArrayInputStream(infobox)); + } catch (CertificateException e) { + log.info("Failed to decode signing certificate.", e); // TODO: issue appropriate error - throw new SLCommandException(4000); - } - - } else { - log.info("Failed to get signing certificate."); - // TODO: issue appropriate error - throw new SLCommandException(4000); - } - - } - - /** - * Signs the signature. - * - * @throws SLCommandException + throw new SLCommandException(4000); + } + + } else if (stalResponse instanceof ErrorResponse) { + ErrorResponse err = (ErrorResponse) stalResponse; + log.info("Received an error response from STAL with code: " + + err.getErrorCode()); + throw new SLCommandException(err.getErrorCode()); + + } else { + log.info("Failed to get signing certificate."); + throw new SLCommandException(4000); + } + + } + + /** + * Signs the signature. + * + * @throws SLCommandException * if signing the signature fails - * @throws SLViewerException - */ - private void signXMLSignature() throws SLCommandException, SLViewerException { - - try { - signature.sign(getCmdCtx().getSTAL(), keyboxIdentifier); - } catch (MarshalException e) { - log.error("Failed to marshall XMLSignature.", e); - throw new SLCommandException(4000); - } catch (XMLSignatureException e) { - if (e.getCause() instanceof URIReferenceException) { - URIReferenceException uriReferenceException = (URIReferenceException) e.getCause(); - if (uriReferenceException.getCause() instanceof SLCommandException) { - throw (SLCommandException) uriReferenceException.getCause(); - } - } - log.error("Failed to sign XMLSignature.", e); - throw new SLCommandException(4000); - } - - } - - @Override - public SLResult execute() { - try { - - // get certificate in order to select appropriate algorithms for hashing and signing - getSigningCertificate(); - + * @throws SLViewerException + */ + private void signXMLSignature() throws SLCommandException, SLViewerException { + + try { + signature.sign(getCmdCtx().getSTAL(), keyboxIdentifier); + } catch (MarshalException e) { + log.error("Failed to marshall XMLSignature.", e); + throw new SLCommandException(4000); + } catch (XMLSignatureException e) { + if (e.getCause() instanceof URIReferenceException) { + URIReferenceException uriReferenceException = (URIReferenceException) e + .getCause(); + if (uriReferenceException.getCause() instanceof SLCommandException) { + throw (SLCommandException) uriReferenceException.getCause(); + } + } + log.error("Failed to sign XMLSignature.", e); + throw new SLCommandException(4000); + } + + } + + @Override + public SLResult execute() { + try { + + // get certificate in order to select appropriate algorithms for hashing + // and signing + getSigningCertificate(); + // prepare the XMLSignature for signing - prepareXMLSignature(); - + prepareXMLSignature(); + // sign the XMLSignature - signXMLSignature(); - - if (log.isTraceEnabled()) { - - DOMImplementationLS domImplLS = DOMUtils.getDOMImplementationLS(); - LSSerializer serializer = domImplLS.createLSSerializer(); - String debugString = serializer.writeToString(signature.getDocument()); - - log.trace(debugString); - - } - - return new CreateXMLSignatureResultImpl(signature.getDocument()); - + signXMLSignature(); + + if (log.isTraceEnabled()) { + + DOMImplementationLS domImplLS = DOMUtils.getDOMImplementationLS(); + LSSerializer serializer = domImplLS.createLSSerializer(); + String debugString = serializer.writeToString(signature.getDocument()); + + log.trace(debugString); + + } + + return new CreateXMLSignatureResultImpl(signature.getDocument()); + } catch (SLException e) { - return new ErrorResultImpl(e, cmdCtx.getLocale()); - } - } - - @Override - public String getName() { - return "CreateXMLSignatureRequest"; - } - - -} + return new ErrorResultImpl(e, cmdCtx.getLocale()); + } + } + + @Override + public String getName() { + return "CreateXMLSignatureRequest"; + } + +} -- cgit v1.2.3 From 99134c1be5db0fedadc051922e70c9bf563ce16d Mon Sep 17 00:00:00 2001 From: wbauer Date: Tue, 2 Dec 2008 10:13:09 +0000 Subject: Changed SLCommandFactory configuration mechanism and moved the actual configuration to spring's application context git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@231 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java | 2 +- .../java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java | 2 +- .../src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java index 092a13c4..4969c85a 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java @@ -84,7 +84,7 @@ public class CreateXMLSignatureResultImpl extends SLResultImpl { DocumentFragment fragment = doc.createDocumentFragment(); - JAXBContext jaxbContext = SLCommandFactory.getJaxbContext(); + JAXBContext jaxbContext = SLCommandFactory.getInstance().getJaxbContext(); try { Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(createCreateXMLSignatureResponse, fragment); diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java index 6f41b562..78e2e7fa 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java @@ -95,7 +95,7 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements JAXBElement infoboxReadResponse = factory.createInfoboxReadResponse(infoboxReadResponseType); - JAXBContext context = SLCommandFactory.getJaxbContext(); + JAXBContext context = SLCommandFactory.getInstance().getJaxbContext(); try { Marshaller marshaller = context.createMarshaller(); marshaller.marshal(infoboxReadResponse, doc); diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java index 7306b237..80bbdca8 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java @@ -85,7 +85,7 @@ public abstract class SLResultImpl implements SLResult { private Marshaller getMarshaller() { try { - JAXBContext context = SLCommandFactory.getJaxbContext(); + JAXBContext context = SLCommandFactory.getInstance().getJaxbContext(); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); return marshaller; -- cgit v1.2.3 From 3aadcf8f877a560bed75af7e0db918aa26ef2a03 Mon Sep 17 00:00:00 2001 From: mcentner Date: Thu, 4 Dec 2008 10:00:31 +0000 Subject: Refactoring of infobox implementation. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@232 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/AbstractAssocArrayInfobox.java | 284 ++++++++++ .../slcommands/impl/AbstractBinaryFileInfobox.java | 68 +++ .../impl/AbstractInfoboxCommandImpl.java | 55 ++ .../bku/slcommands/impl/AbstractInfoboxImpl.java | 26 + .../bku/slcommands/impl/AssocArrayInfobox.java | 27 + .../bku/slcommands/impl/BinaryFileInfobox.java | 27 + .../slcommands/impl/CertificatesInfoboxImpl.java | 112 ++++ .../impl/CreateXMLSignatureCommandImpl.java | 37 +- .../slcommands/impl/IdentityLinkInfoboxImpl.java | 291 +++++++++++ .../at/gv/egiz/bku/slcommands/impl/Infobox.java | 53 ++ .../egiz/bku/slcommands/impl/InfoboxFactory.java | 151 ++++++ .../slcommands/impl/InfoboxReadCommandImpl.java | 569 ++------------------- .../bku/slcommands/impl/InfoboxReadResultImpl.java | 3 +- .../slcommands/impl/InfoboxUpdateCommandImpl.java | 158 ++++++ .../slcommands/impl/InfoboxUpdateResultImpl.java | 43 ++ .../gv/egiz/bku/slcommands/impl/SLCommandImpl.java | 107 +--- .../at/gv/egiz/bku/slcommands/impl/STALHelper.java | 218 ++++++++ 17 files changed, 1568 insertions(+), 661 deletions(-) create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractBinaryFileInfobox.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AssocArrayInfobox.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/BinaryFileInfobox.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CertificatesInfoboxImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/Infobox.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateCommandImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateResultImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java new file mode 100644 index 00000000..e49ed6c0 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java @@ -0,0 +1,284 @@ +/* + * Copyright 2008 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package at.gv.egiz.bku.slcommands.impl; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.buergerkarte.namespaces.securitylayer._1.InfoboxAssocArrayPairType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadDataAssocArrayType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.buergerkarte.namespaces.securitylayer._1.XMLContentType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadKeys; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadPairs; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadValue; +import at.gv.egiz.bku.slcommands.InfoboxReadResult; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; + +/** + * An abstract base class for {@link Infobox} implementations of type associative array. + * + * @author mcentner + */ +public abstract class AbstractAssocArrayInfobox extends AbstractInfoboxImpl + implements AssocArrayInfobox { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(AbstractAssocArrayInfobox.class); + + /** + * The search string pattern. + */ + public static final String SEARCH_STRING_PATTERN = ".&&[^/](/.&&[^/])*"; + + /** + * @return the keys available in this infobox. + */ + public abstract String[] getKeys(); + + /** + * @return true if the values are XML entities, or false otherwise. + */ + public abstract boolean isValuesAreXMLEntities(); + + /** + * Returns a key to value mapping for the given keys. + * + * @param keys a list of keys + * @param cmdCtx the command context + * + * @return a key to value mapping for the given keys. + * + * @throws SLCommandException if obtaining the values fails + */ + public abstract Map getValues(List keys, SLCommandContext cmdCtx) throws SLCommandException; + + /** + * Returns all keys that match the given searchString. + * + * @param searchString the search string + * + * @return all keys that match the given searchString + * + * @throws SLCommandException if the given search string is invalid + */ + protected List selectKeys(String searchString) throws SLCommandException { + + if ("*".equals(searchString) || "**".equals(searchString)) { + return Arrays.asList(getKeys()); + } + + if (Pattern.matches(SEARCH_STRING_PATTERN, searchString)) { + +// for (int i = 0; i < searchString.length(); i++) { +// int codePoint = searchString.codePointAt(i); +// +// } + + // TODO : build pattern + return Collections.emptyList(); + } else { + log.info("Got invalid search string '" + searchString + "'"); + throw new SLCommandException(4010); + } + + } + + /** + * Read all keys specified by readKeys. + * + * @param readKeys + * the ReadKeys element + * @param cmdCtx + * the command context + * @return a corresponding InfoboxReadResult + * + * @throws SLCommandException + * if the ReadKeys element is invalid or obtaining the corresponding + * values fails + */ + protected InfoboxReadResult readKeys(ReadKeys readKeys, SLCommandContext cmdCtx) throws SLCommandException { + + List selectedKeys = selectKeys(readKeys.getSearchString()); + + if (readKeys.isUserMakesUnique() && selectedKeys.size() > 1) { + log.info("UserMakesUnique not supported"); + // TODO: give more specific error message + throw new SLCommandException(4010); + } + + ObjectFactory objectFactory = new ObjectFactory(); + + InfoboxReadDataAssocArrayType infoboxReadDataAssocArrayType = objectFactory + .createInfoboxReadDataAssocArrayType(); + + List keys = infoboxReadDataAssocArrayType.getKey(); + keys.addAll(selectedKeys); + + return new InfoboxReadResultImpl(infoboxReadDataAssocArrayType); + + } + + /** + * Read all pairs specified by readPairs. + * + * @param readPairs + * the readPairs element + * @param cmdCtx + * the command context + * @return a corresponding InfoboxReadResult + * + * @throws SLCommandException + * if the ReadPairs element is invalid or obtaining the corresponding + * values fails + */ + protected InfoboxReadResult readPairs(ReadPairs readPairs, SLCommandContext cmdCtx) throws SLCommandException { + + if (readPairs.isValuesAreXMLEntities() && !isValuesAreXMLEntities()) { + log.info("Got valuesAreXMLEntities=" + readPairs + " but infobox type is binary."); + throw new SLCommandException(4010); + } + + if (!readPairs.isValuesAreXMLEntities() && isValuesAreXMLEntities()) { + log.info("Got valuesAreXMLEntities=" + readPairs + " but infobox type is XML."); + throw new SLCommandException(4010); + } + + List selectedKeys = selectKeys(readPairs.getSearchString()); + + if (readPairs.isUserMakesUnique() && selectedKeys.size() > 1) { + log.info("UserMakesUnique not supported"); + // TODO: give more specific error message + throw new SLCommandException(4010); + } + + ObjectFactory objectFactory = new ObjectFactory(); + + InfoboxReadDataAssocArrayType infoboxReadDataAssocArrayType = objectFactory.createInfoboxReadDataAssocArrayType(); + + Map values = getValues(selectedKeys, cmdCtx); + for (String key : selectedKeys) { + InfoboxAssocArrayPairType infoboxAssocArrayPairType = objectFactory.createInfoboxAssocArrayPairType(); + infoboxAssocArrayPairType.setKey(key); + Object value = values.get(key); + if (value instanceof byte[]) { + infoboxAssocArrayPairType.setBase64Content((byte[]) value); + } else { + infoboxAssocArrayPairType.setXMLContent((XMLContentType) value); + } + infoboxReadDataAssocArrayType.getPair().add(infoboxAssocArrayPairType); + } + + return new InfoboxReadResultImpl(infoboxReadDataAssocArrayType); + } + + /** + * Read the value specified by readPairs. + * + * @param readValue + * the readValue element + * @param cmdCtx + * the command context + * @return a corresponding InfoboxReadResult + * + * @throws SLCommandException + * if the ReadValue element is invalid or obtaining the corresponding + * values fails + */ + protected InfoboxReadResult readValue(ReadValue readValue, SLCommandContext cmdCtx) throws SLCommandException { + + if (readValue.isValueIsXMLEntity() && !isValuesAreXMLEntities()) { + log.info("Got valuesAreXMLEntities=" + readValue + " but infobox type is binary."); + throw new SLCommandException(4010); + } + + if (!readValue.isValueIsXMLEntity() && isValuesAreXMLEntities()) { + log.info("Got valuesAreXMLEntities=" + readValue + " but infobox type is XML."); + throw new SLCommandException(4010); + } + + List selectedKeys; + + if (Arrays.asList(getKeys()).contains(readValue.getKey())) { + selectedKeys = Collections.singletonList(readValue.getKey()); + } else { + selectedKeys = Collections.emptyList(); + } + + ObjectFactory objectFactory = new ObjectFactory(); + + InfoboxReadDataAssocArrayType infoboxReadDataAssocArrayType = objectFactory.createInfoboxReadDataAssocArrayType(); + + Map values = getValues(selectedKeys, cmdCtx); + for (String key : selectedKeys) { + InfoboxAssocArrayPairType infoboxAssocArrayPairType = objectFactory.createInfoboxAssocArrayPairType(); + infoboxAssocArrayPairType.setKey(key); + Object value = values.get(key); + if (value instanceof byte[]) { + infoboxAssocArrayPairType.setBase64Content((byte[]) value); + } else { + infoboxAssocArrayPairType.setXMLContent((XMLContentType) value); + } + infoboxReadDataAssocArrayType.getPair().add(infoboxAssocArrayPairType); + } + + return new InfoboxReadResultImpl(infoboxReadDataAssocArrayType); + } + + @Override + public InfoboxReadResult read(InfoboxReadRequestType req, + SLCommandContext cmdCtx) throws SLCommandException { + + InfoboxReadParamsAssocArrayType assocArrayParameters = req + .getAssocArrayParameters(); + + if (assocArrayParameters == null) { + log.info("Infobox type is AssocArray but got no AssocArrayParameters."); + throw new SLCommandException(4010); + } + + if (assocArrayParameters.getReadKeys() != null) { + return readKeys(assocArrayParameters.getReadKeys(), cmdCtx); + } + + if (assocArrayParameters.getReadPairs() != null) { + return readPairs(assocArrayParameters.getReadPairs(), cmdCtx); + } + + // ReadValue + if (assocArrayParameters.getReadValue() != null) { + return readValue(assocArrayParameters.getReadValue(), cmdCtx); + } + + log + .info("Infobox type is AssocArray but got invalid AssocArrayParameters."); + throw new SLCommandException(4010); + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractBinaryFileInfobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractBinaryFileInfobox.java new file mode 100644 index 00000000..07ca639c --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractBinaryFileInfobox.java @@ -0,0 +1,68 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsBinaryFileType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; + +/** + * An abstract base class for {@link Infobox} implementations of type binary file. + * + * @author mcentner + */ +public abstract class AbstractBinaryFileInfobox extends AbstractInfoboxImpl implements BinaryFileInfobox { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(AbstractBinaryFileInfobox.class); + + /** + * Is this infobox' content an XML entity? + */ + private boolean isXMLEntity = false; + + /** + * @return true if this infobox' content is an XML entity or false otherwise. + */ + public boolean isXMLEntity() { + return isXMLEntity; + } + + /** + * Sets the value returned by {@link #isXMLEntity()} according to the given + * request. + * + * @param request the InfoboxReadRequest + */ + public void setIsXMLEntity(InfoboxReadRequestType request) { + + InfoboxReadParamsBinaryFileType binaryFileParameters = request.getBinaryFileParameters(); + if (binaryFileParameters != null) { + isXMLEntity = binaryFileParameters.isContentIsXMLEntity(); + log.debug("Got ContentIsXMLEntity=" + isXMLEntity + "."); + } + + } + + + + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java new file mode 100644 index 00000000..305769a8 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java @@ -0,0 +1,55 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; + +/** + * An abstract base class for implementations of security layer infobox requests. + * + * @author mcentner + * + * @param + */ +public abstract class AbstractInfoboxCommandImpl extends SLCommandImpl { + + /** + * The infobox implementation. + */ + protected Infobox infobox; + + @Override + public void init(SLCommandContext ctx, Object request) + throws SLCommandException { + super.init(ctx, request); + + String infoboxIdentifier = getInfoboxIdentifier(getRequestValue()); + + infobox = InfoboxFactory.getInstance().createInfobox(infoboxIdentifier); + } + + /** + * Returns the infobox identifier given in request. + * + * @param request the request value + * + * @return the infobox identifier givne in request + */ + protected abstract String getInfoboxIdentifier(T request); + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxImpl.java new file mode 100644 index 00000000..e5c7afcc --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxImpl.java @@ -0,0 +1,26 @@ +/* + * Copyright 2008 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package at.gv.egiz.bku.slcommands.impl; + +/** + * An abstract base class for {@link Infobox} implementations. + * + * @author mcentner + */ +public abstract class AbstractInfoboxImpl implements Infobox { + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AssocArrayInfobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AssocArrayInfobox.java new file mode 100644 index 00000000..908d95da --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AssocArrayInfobox.java @@ -0,0 +1,27 @@ +/* + * Copyright 2008 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package at.gv.egiz.bku.slcommands.impl; + +/** + * An {@link Infobox} of type associative array as defined in Security Layer + * 1.2. + * + * @author mcentner + */ +public interface AssocArrayInfobox extends Infobox { + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/BinaryFileInfobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/BinaryFileInfobox.java new file mode 100644 index 00000000..c27f9446 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/BinaryFileInfobox.java @@ -0,0 +1,27 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +/** + * An {@link Infobox} of type binary file as defined in Security Layer + * 1.2. + * + * @author mcentner + */ +public interface BinaryFileInfobox extends Infobox { + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CertificatesInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CertificatesInfoboxImpl.java new file mode 100644 index 00000000..0208f137 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CertificatesInfoboxImpl.java @@ -0,0 +1,112 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.stal.InfoboxReadRequest; +import at.gv.egiz.stal.STALRequest; + +/** + * An implementation of the {@link Infobox} Certificates as + * specified in Security Layer 1.2. + * + * @author mcentner + */ +public class CertificatesInfoboxImpl extends AbstractAssocArrayInfobox { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(CertificatesInfoboxImpl.class); + + /** + * The valid keys. + */ + public static final String[] CERTIFICATES_KEYS = new String[] { + "SecureSignatureKeypair", + "CertifiedKeypair" }; + + @Override + public String getIdentifier() { + return "Certificates"; + } + + @Override + public String[] getKeys() { + return CERTIFICATES_KEYS; + } + + @Override + public boolean isValuesAreXMLEntities() { + return false; + } + + @Override + public Map getValues(List certificates, SLCommandContext cmdCtx) throws SLCommandException { + + STALHelper stalHelper = new STALHelper(cmdCtx.getSTAL()); + + if (certificates != null && !certificates.isEmpty()) { + + List stalRequests = new ArrayList(); + + // get certificates + InfoboxReadRequest infoboxReadRequest; + for (int i = 0; i < certificates.size(); i++) { + infoboxReadRequest = new InfoboxReadRequest(); + infoboxReadRequest.setInfoboxIdentifier(certificates.get(i)); + stalRequests.add(infoboxReadRequest); + } + + stalHelper.transmitSTALRequest(stalRequests); + + List x509Certs = stalHelper.getCertificatesFromResponses(); + + Map values = new HashMap(); + + for (int i = 0; i < certificates.size(); i++) { + try { + values.put(certificates.get(i), x509Certs.get(i).getEncoded()); + } catch (CertificateEncodingException e) { + log.error("Failed to encode certificate.", e); + throw new SLCommandException(4000); + } + } + + return values; + + } else { + + return new HashMap(); + + } + + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java index b2e3b303..01686641 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureCommandImpl.java @@ -16,13 +16,11 @@ */ package at.gv.egiz.bku.slcommands.impl; -import java.io.ByteArrayInputStream; import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Date; +import java.util.List; import javax.xml.crypto.MarshalException; import javax.xml.crypto.URIReferenceException; @@ -48,11 +46,8 @@ import at.gv.egiz.bku.slexceptions.SLException; import at.gv.egiz.bku.slexceptions.SLRequestException; import at.gv.egiz.bku.slexceptions.SLViewerException; import at.gv.egiz.dom.DOMUtils; -import at.gv.egiz.stal.ErrorResponse; import at.gv.egiz.stal.InfoboxReadRequest; -import at.gv.egiz.stal.InfoboxReadResponse; import at.gv.egiz.stal.STALRequest; -import at.gv.egiz.stal.STALResponse; /** * This class implements the security layer command @@ -147,33 +142,13 @@ public class CreateXMLSignatureCommandImpl extends InfoboxReadRequest stalRequest = new InfoboxReadRequest(); stalRequest.setInfoboxIdentifier(keyboxIdentifier); - requestSTAL(Collections.singletonList((STALRequest) stalRequest)); - - STALResponse stalResponse = stalResponses.next(); - - if (stalResponse instanceof InfoboxReadResponse) { - byte[] infobox = ((InfoboxReadResponse) stalResponse).getInfoboxValue(); - - try { - CertificateFactory certFactory = CertificateFactory.getInstance("X509"); - signingCertificate = (X509Certificate) certFactory - .generateCertificate(new ByteArrayInputStream(infobox)); - } catch (CertificateException e) { - log.info("Failed to decode signing certificate.", e); - // TODO: issue appropriate error - throw new SLCommandException(4000); - } - - } else if (stalResponse instanceof ErrorResponse) { - ErrorResponse err = (ErrorResponse) stalResponse; - log.info("Received an error response from STAL with code: " - + err.getErrorCode()); - throw new SLCommandException(err.getErrorCode()); - - } else { - log.info("Failed to get signing certificate."); + stalHelper.transmitSTALRequest(Collections.singletonList((STALRequest) stalRequest)); + List certificates = stalHelper.getCertificatesFromResponses(); + if (certificates == null || certificates.size() != 1) { + log.info("Got an unexpected number of certificates from STAL."); throw new SLCommandException(4000); } + signingCertificate = certificates.get(0); } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java new file mode 100644 index 00000000..20d20c9d --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java @@ -0,0 +1,291 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Result; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import at.buergerkarte.namespaces.personenbindung._20020506_.CompressedIdentityLinkType; +import at.buergerkarte.namespaces.securitylayer._1.AnyChildrenType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; +import at.gv.egiz.bku.slcommands.InfoboxReadResult; +import at.gv.egiz.bku.slcommands.SLCommand; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLExceptionMessages; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import at.gv.egiz.idlink.CompressedIdentityLinkFactory; +import at.gv.egiz.idlink.IdentityLinkTransformer; +import at.gv.egiz.idlink.ans1.IdentityLink; +import at.gv.egiz.stal.InfoboxReadRequest; +import at.gv.egiz.stal.STALRequest; + +/** + * An implementation of the {@link Infobox} IdentityLink as + * specified in Security Layer 1.2 + * + * @author mcentner + */ +public class IdentityLinkInfoboxImpl extends AbstractBinaryFileInfobox { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(IdentityLinkInfoboxImpl.class); + + /** + * The box specific parameter IdentityLinkDomainIdentifier. + */ + public static final String BOX_SPECIFIC_PARAMETER_IDENTITY_LINK_DOMAIN_IDENTIFIER = "IdentityLinkDomainIdentifier"; + + /** + * The value of the box specific parameter IdentityLinkDomainIdentifier. + */ + private String domainIdentifier; + + @Override + public String getIdentifier() { + return "IdentityLink"; + } + + /** + * @return the value of the box specific parameter IdentityLinkDomainIdentifier + */ + public String getDomainIdentifier() { + return domainIdentifier; + } + + @Override + public InfoboxReadResult read(InfoboxReadRequestType req, SLCommandContext cmdCtx) throws SLCommandException { + + AnyChildrenType boxSpecificParameters = req.getBoxSpecificParameters(); + + if (boxSpecificParameters != null) { + // check BoxSpecificParameters + List parameter = boxSpecificParameters.getAny(); + JAXBElement element; + if (parameter != null + && parameter.size() == 1 + && parameter.get(0) instanceof JAXBElement + && SLCommand.NAMESPACE_URI.equals((element = (JAXBElement) parameter.get(0)).getName().getNamespaceURI()) + && BOX_SPECIFIC_PARAMETER_IDENTITY_LINK_DOMAIN_IDENTIFIER.equals(element.getName().getLocalPart()) + && element.getValue() instanceof String) { + domainIdentifier = (String) element.getValue(); + log.debug("Got sl:IdentityLinkDomainIdentifier: " + domainIdentifier); + } else { + log.info("Got invalid BoxSpecificParameters."); + throw new SLCommandException(4010); + } + } + + setIsXMLEntity(req); + + STALHelper stalHelper = new STALHelper(cmdCtx.getSTAL()); + + List stalRequests = new ArrayList(); + + InfoboxReadRequest infoboxReadRequest; + // get raw identity link + infoboxReadRequest = new InfoboxReadRequest(); + infoboxReadRequest.setInfoboxIdentifier(getIdentifier()); + infoboxReadRequest.setDomainIdentifier(domainIdentifier); + stalRequests.add(infoboxReadRequest); + + // get certificates + infoboxReadRequest = new InfoboxReadRequest(); + infoboxReadRequest.setInfoboxIdentifier("SecureSignatureKeypair"); + stalRequests.add(infoboxReadRequest); + infoboxReadRequest = new InfoboxReadRequest(); + infoboxReadRequest.setInfoboxIdentifier("CertifiedKeypair"); + stalRequests.add(infoboxReadRequest); + + stalHelper.transmitSTALRequest(stalRequests); + log.trace("Got STAL response"); + + IdentityLink identityLink = stalHelper.getIdentityLinkFromResponses(); + List certificates = stalHelper.getCertificatesFromResponses(); + + + CompressedIdentityLinkFactory idLinkFactory = CompressedIdentityLinkFactory.getInstance(); + JAXBElement compressedIdentityLink = idLinkFactory + .createCompressedIdentityLink(identityLink, certificates, getDomainIdentifier()); + + IdentityLinkTransformer identityLinkTransformer = IdentityLinkTransformer.getInstance(); + String issuerTemplate = identityLink.getIssuerTemplate(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db; + try { + db = dbf.newDocumentBuilder(); + } catch (ParserConfigurationException e) { + log.error("Failed to create XML document.", e); + throw new SLRuntimeException(e); + } + + Document document = db.newDocument(); + try { + idLinkFactory.marshallCompressedIdentityLink(compressedIdentityLink, document, null, true); + } catch (JAXBException e) { + log.info("Failed to marshall CompressedIdentityLink.", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, + new Object[] { getIdentifier() }); + } + + InfoboxReadResultFileImpl result = new InfoboxReadResultFileImpl(); + ByteArrayOutputStream resultBytes = null; + Result xmlResult = (isXMLEntity() || getDomainIdentifier() != null) + ? result.getXmlResult(true) + : new StreamResult((resultBytes = new ByteArrayOutputStream())); + try { + log.trace("Trying to transform identitylink"); + identityLinkTransformer.transformIdLink(issuerTemplate, new DOMSource(document), xmlResult); + } catch (MalformedURLException e) { + log.warn("Malformed issuer template URL '" + issuerTemplate + "'."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } catch (IOException e) { + log.warn("Failed to dereferene issuer template URL '" + issuerTemplate + "'." ,e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } catch (TransformerConfigurationException e) { + log.warn("Failed to create transformation template from issuer template URL '" + issuerTemplate + "'", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } catch (TransformerException e) { + log.info("Faild to transform CompressedIdentityLink.", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + + // TODO: Report BUG in IssuerTemplates + // Some IssuerTemplate stylesheets do not consider the pr:Type-Element of the CompressedIdentityLink ... + if (getDomainIdentifier() != null) { + if (xmlResult instanceof DOMResult) { + Node node = ((DOMResult) xmlResult).getNode(); + Node nextSibling = ((DOMResult) xmlResult).getNextSibling(); + Node idLinkNode; + if (nextSibling != null) { + idLinkNode = nextSibling.getPreviousSibling(); + } else if (node != null) { + idLinkNode = node.getFirstChild(); + } else { + log + .error("An IdentityLinkDomainIdentifier of '" + + getDomainIdentifier() + + "' has been given. However, it cannot be set, as the transformation result does not contain a node."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + IdentityLinkTransformer.setDomainIdentifier(idLinkNode, getDomainIdentifier()); + } else { + log + .error("An IdentityLinkDomainIdentifier of '" + + getDomainIdentifier() + + "' has been given. However, it cannot be set, as the transformation result is not of type DOM."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + } + + if (!isXMLEntity()) { + if (resultBytes == null) { + resultBytes = new ByteArrayOutputStream(); + + if (xmlResult instanceof DOMResult) { + Node node = ((DOMResult) xmlResult).getNode(); + Node nextSibling = ((DOMResult) xmlResult).getNextSibling(); + + DOMSource xmlSource; + if (nextSibling != null) { + xmlSource = new DOMSource(nextSibling.getPreviousSibling()); + } else if (node != null) { + xmlSource = new DOMSource(node.getFirstChild()); + } else { + log + .error("IssuerTemplate transformation returned no node."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + try { + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(xmlSource, new StreamResult(resultBytes)); + } catch (TransformerConfigurationException e) { + log.error(e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } catch (TransformerException e) { + log.error(e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + } else if (xmlResult instanceof StreamResult) { + OutputStream outputStream = ((StreamResult) xmlResult).getOutputStream(); + if (outputStream instanceof ByteArrayOutputStream) { + result.setResultBytes(((ByteArrayOutputStream) outputStream).toByteArray()); + } else { + log.error("ContentIsXMLEntity is set to 'false'. However, an XMLResult has already been set."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); + } + } + } else { + result.setResultBytes(resultBytes.toByteArray()); + } + } + + return result; + + } + + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/Infobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/Infobox.java new file mode 100644 index 00000000..a6f8cbb2 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/Infobox.java @@ -0,0 +1,53 @@ +/* + * Copyright 2008 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package at.gv.egiz.bku.slcommands.impl; + +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; +import at.gv.egiz.bku.slcommands.InfoboxReadResult; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; + +/** + * An implementation of this interface represents a infobox as defined in + * Security-Layer 1.2. + * + * @author mcentner + */ +public interface Infobox { + + /** + * @return the identifier of this infobox + */ + public String getIdentifier(); + + /** + * Read data from this infobox. + * + * @param request + * the InfoboxReadRequest + * @param cmdCtx + * the command context + * + * @return the data read from this infobox as InfoboxReadResult + * + * @throws SLCommandException + * if reading from this infobox fails + */ + public InfoboxReadResult read(InfoboxReadRequestType request, + SLCommandContext cmdCtx) throws SLCommandException; + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java new file mode 100644 index 00000000..4a03fe74 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java @@ -0,0 +1,151 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLExceptionMessages; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; + +/** + * A factory for creating {@link Infobox}es. + * + * @author mcentner + */ +public class InfoboxFactory { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(InfoboxFactory.class); + + /** + * The singleton instance of this InfoboxFactory. + */ + private static InfoboxFactory instance; + + /** + * @return an instance of this InfoboxFactory + */ + public synchronized static InfoboxFactory getInstance() { + if (instance == null) { + instance = new InfoboxFactory(); + } + return instance; + } + + /** + * The mapping of infobox identifier to implementation class. + */ + private HashMap> implementations; + + /** + * Private constructor. + */ + private InfoboxFactory() { + } + + /** + * Sets the mapping of infobox identifier to implementation class name. + * + * @param infoboxImplMap + * a mapping of infobox identifiers to implementation class names + * + * @throws ClassNotFoundException + * if implementation class is not an instance of {@link Infobox} + */ + @SuppressWarnings("unchecked") + public void setInfoboxImpl(Map infoboxImplMap) throws ClassNotFoundException { + HashMap> implMap = new HashMap>(); + ClassLoader cl = getClass().getClassLoader(); + for (String key : infoboxImplMap.keySet()) { + Class impl = (Class) cl.loadClass(infoboxImplMap.get(key)); + log.debug("Registering infobox '" + key + "' implementation '" + impl.getCanonicalName() + "'."); + implementations.put(key, impl); + } + implementations = implMap; + } + + /** + * Returns the configured implementation class for the given + * infoboxIdentifier. + * + * @param infoboxIdentifier + * the infobox identifier + * + * @return the implementation class for the given infobox identifier or + * null if there is no implementation class configured + */ + public Class getImplClass(String infoboxIdentifier) { + if (implementations != null) { + return implementations.get(infoboxIdentifier); + } else { + return null; + } + } + + /** + * Create a new {@link Infobox} instance for the given + * infoboxIdentifier. + * + * @param infoboxIdentifier + * the infobox identifier + * + * @return an {@link Infobox} implementation for the given infobox identifier + * + * @throws SLCommandException + * if there is no implementation for the given infobox identifier + * @throws SLRuntimeException + * if creating an {@link Infobox} instance fails + */ + public Infobox createInfobox(String infoboxIdentifier) throws SLCommandException, SLRuntimeException { + + Class implClass = getImplClass(infoboxIdentifier); + if (implClass == null) { + // infobox not supported + log.info("Unsupported infobox '" + infoboxIdentifier + "."); + throw new SLCommandException(4002, + SLExceptionMessages.EC4002_INFOBOX_UNKNOWN, + new Object[] { infoboxIdentifier }); + } + + // try to instantiate + Infobox infobox; + try { + infobox = implClass.newInstance(); + log.debug("Infobox '" + infobox.getIdentifier() + "' created."); + } catch (InstantiationException e) { + // unexpected error + log.error("Failed to instantiate infobox implementation.", e); + throw new SLRuntimeException(e); + } catch (IllegalAccessException e) { + // unexpected error + log.error("Failed to instantiate infobox implementation.", e); + throw new SLRuntimeException(e); + } + + return infobox; + + } + + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java index c7bb5205..aaa786a6 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java @@ -16,67 +16,14 @@ */ package at.gv.egiz.bku.slcommands.impl; -import iaik.asn1.CodingException; -import iaik.asn1.DerCoder; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.regex.Pattern; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Result; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMResult; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import at.buergerkarte.namespaces.personenbindung._20020506_.CompressedIdentityLinkType; -import at.buergerkarte.namespaces.securitylayer._1.AnyChildrenType; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxAssocArrayPairType; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadDataAssocArrayType; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsBinaryFileType; import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; -import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadKeys; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadPairs; -import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadValue; import at.gv.egiz.bku.slcommands.InfoboxReadCommand; -import at.gv.egiz.bku.slcommands.SLCommand; import at.gv.egiz.bku.slcommands.SLCommandContext; import at.gv.egiz.bku.slcommands.SLResult; import at.gv.egiz.bku.slexceptions.SLCommandException; -import at.gv.egiz.bku.slexceptions.SLExceptionMessages; -import at.gv.egiz.bku.slexceptions.SLRuntimeException; -import at.gv.egiz.idlink.CompressedIdentityLinkFactory; -import at.gv.egiz.idlink.IdentityLinkTransformer; -import at.gv.egiz.idlink.ans1.IdentityLink; -import at.gv.egiz.stal.InfoboxReadRequest; -import at.gv.egiz.stal.InfoboxReadResponse; -import at.gv.egiz.stal.STALRequest; /** * This class implements the security layer command @@ -88,7 +35,7 @@ import at.gv.egiz.stal.STALRequest; * * @author mcentner */ -public class InfoboxReadCommandImpl extends SLCommandImpl implements +public class InfoboxReadCommandImpl extends AbstractInfoboxCommandImpl implements InfoboxReadCommand { /** @@ -96,511 +43,63 @@ public class InfoboxReadCommandImpl extends SLCommandImplInfoboxIdentifier - */ - protected String infoboxIdentifier; - - /** - * The IdentityLinkDomainIdentifier value of an IdentyLink infobox. - */ - protected String identityLinkDomainIdentifier; - - /** - * The list of certificates to be read from an Certificates infobox. - */ - protected List certificates; - - /** - * The result type. - */ - protected int assocArrayResult; - - /** - * Is content XML entity? - */ - protected boolean isXMLEntity; - @Override public String getName() { return "InfoboxReadRequest"; } - /** - * @return the infoboxIdentifier - */ - public String getInfoboxIdentifier() { - return infoboxIdentifier; - } - + @Override + protected String getInfoboxIdentifier(InfoboxReadRequestType request) { + return request.getInfoboxIdentifier(); + } + @Override public void init(SLCommandContext ctx, Object request) throws SLCommandException { super.init(ctx, request); InfoboxReadRequestType req = getRequestValue(); - - infoboxIdentifier = req.getInfoboxIdentifier(); - - if (INFOBOX_IDENTIFIER_IDENTITY_LINK.equals(infoboxIdentifier)) { - - if (req.getAssocArrayParameters() != null) { - log.info("Got AssocArrayParameters but Infobox type is BinaryFile."); - throw new SLCommandException(4010); - } - - InfoboxReadParamsBinaryFileType binaryFileParameters = req.getBinaryFileParameters(); - if (binaryFileParameters != null) { - isXMLEntity = binaryFileParameters.isContentIsXMLEntity(); - log.debug("Got ContentIsXMLEntity=" + isXMLEntity + "."); - } - - AnyChildrenType boxSpecificParameters = req.getBoxSpecificParameters(); - - if (boxSpecificParameters != null) { - // check BoxSpecificParameters - List parameter = boxSpecificParameters.getAny(); - JAXBElement element; - if (parameter != null - && parameter.size() == 1 - && parameter.get(0) instanceof JAXBElement - && SLCommand.NAMESPACE_URI.equals((element = (JAXBElement) parameter.get(0)).getName().getNamespaceURI()) - && BOX_SPECIFIC_PARAMETER_IDENTITY_LINK_DOMAIN_IDENTIFIER.equals(element.getName().getLocalPart()) - && element.getValue() instanceof String) { - identityLinkDomainIdentifier = (String) element.getValue(); - log.debug("Got sl:IdentityLinkDomainIdentifier: " + identityLinkDomainIdentifier); - } else { - log.info("Got invalid BoxSpecificParameters."); - throw new SLCommandException(4010); - } - } - } else if (INFOBOX_IDENTIFIER_CERTIFICATES.equals(infoboxIdentifier)) { - - if (req.getBinaryFileParameters() != null) { - log.info("Got BinaryFileParameters but Infobox type is AssocArray."); - throw new SLCommandException(4010); - } - - if (req.getBoxSpecificParameters() != null) { - log.info("Got invalid BoxSpecificParameters."); - throw new SLCommandException(4010); - } - - InfoboxReadParamsAssocArrayType assocArrayParameters = req - .getAssocArrayParameters(); - if (assocArrayParameters == null) { - log.info("Infobox type is AssocArray but got no AssocArrayParameters."); - throw new SLCommandException(4010); - } - - // RreadKeys? - if (assocArrayParameters.getReadKeys() != null) { - assocArrayResult = ASSOC_ARRAY_READ_KEYS; - ReadKeys readKeys = assocArrayParameters.getReadKeys(); - certificates = findCertificates(readKeys.getSearchString()); - if (readKeys.isUserMakesUnique() && certificates.size() > 1) { - log.info("UserMakesUnique not supported"); - // TODO: give more specific error message - throw new SLCommandException(4010); - } - } - - // ReadPairs? - if (assocArrayParameters.getReadPairs() != null) { - assocArrayResult = ASSOC_ARRAY_READ_PAIRS; - ReadPairs readPairs = assocArrayParameters.getReadPairs(); - if (readPairs.isValuesAreXMLEntities()) { - log.info("Got valuesAreXMLEntities but infobox type is binary."); - throw new SLCommandException(4010); - } - certificates = findCertificates(readPairs.getSearchString()); - if (readPairs.isUserMakesUnique() && certificates.size() > 1) { - log.info("UserMakesUnique not supported"); - // TODO: give more specific error message - throw new SLCommandException(4010); - } - } - - // ReadValue - if (assocArrayParameters.getReadValue() != null) { - assocArrayResult = ASSOC_ARRAY_READ_VALUE; - ReadValue readValue = assocArrayParameters.getReadValue(); - if (readValue.isValueIsXMLEntity()) { - log.info("Got valuesAreXMLEntities but infobox type is binary."); - throw new SLCommandException(4010); - } - String key = readValue.getKey(); - if (Arrays.asList(INFOXBOX_CERTIFICATES_KEYS).contains(key)) { - certificates = Collections.singletonList(key); - } else { - certificates = Collections.emptyList(); - } - } - - if (assocArrayResult == 0) { - log.info("Infobox type is AssocArray but got invalid AssocArrayParameters."); - throw new SLCommandException(4010); - } - - } else { - throw new SLCommandException(4002, - SLExceptionMessages.EC4002_INFOBOX_UNKNOWN, - new Object[] { infoboxIdentifier }); - } + if (req.getAssocArrayParameters() != null && + !(infobox instanceof AssocArrayInfobox)) { + log.info("Got AssocArrayParameters but Infobox type is not AssocArray."); + throw new SLCommandException(4010); + } + + if (req.getBinaryFileParameters() != null && + !(infobox instanceof BinaryFileInfobox)) { + log.info("Got BinaryFileParameters but Infobox type is not BinaryFile."); + throw new SLCommandException(4010); + } } @Override public SLResult execute() { - try { - if (INFOBOX_IDENTIFIER_IDENTITY_LINK.equals(infoboxIdentifier)) { - return readIdentityLink(); - } else if (INFOBOX_IDENTIFIER_CERTIFICATES.equals(infoboxIdentifier)) { - return readCertificates(); - } else { - throw new SLCommandException(4000); - } - } catch (SLCommandException e) { - return new ErrorResultImpl(e, cmdCtx.getLocale()); - } - } - - /** - * Gets the IdentitiyLink form the next STAL response. - * - * @return the IdentityLink - * - * @throws SLCommandException if getting the IdentitiyLink fails - */ - private IdentityLink getIdentityLinkFromResponses() throws SLCommandException { - - // IdentityLink - InfoboxReadResponse response; - if (hasNextResponse()) { - response = (InfoboxReadResponse) nextResponse(InfoboxReadResponse.class); - byte[] idLink = response.getInfoboxValue(); - try { - return new IdentityLink(DerCoder.decode(idLink)); - } catch (CodingException e) { - log.info("Failed to decode infobox '" + INFOBOX_IDENTIFIER_IDENTITY_LINK + "'.", e); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, - new Object[] { INFOBOX_IDENTIFIER_IDENTITY_LINK }); - } - } else { - log.info("No infobox '" + INFOBOX_IDENTIFIER_IDENTITY_LINK + "' returned from STAL."); - throw new SLCommandException(4000); - } - - } - - /** - * Gets the list of certificates from the next STAL responses. - * - * @return the list of certificates - * - * @throws SLCommandException if getting the list of certificates fails - */ - private List getCertificatesFromResponses() throws SLCommandException { - - List certificates = new ArrayList(); - - CertificateFactory certFactory; - try { - certFactory = CertificateFactory.getInstance("X509"); - } catch (CertificateException e) { - // we should always be able to get an X509 certificate factory - log.error("CertificateFactory.getInstance(\"X509\") failed.", e); - throw new SLRuntimeException(e); - } - - InfoboxReadResponse response; - while(hasNextResponse()) { - response = (InfoboxReadResponse) nextResponse(InfoboxReadResponse.class); - byte[] cert = response.getInfoboxValue(); - try { - certificates.add((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(cert))); - } catch (CertificateException e) { - log.info("Failed to decode certificate.", e); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, - new Object[] { INFOBOX_IDENTIFIER_CERTIFICATES }); - } - } - - return certificates; - - } - - /** - * Uses STAL to read the IdentityLink. - * - * @return the corresponding security layer result - * - * @throws SLCommandException if reading the IdentityLink fails - */ - private SLResult readIdentityLink() throws SLCommandException { - - List stalRequests = new ArrayList(); - - InfoboxReadRequest infoboxReadRequest; - // get raw identity link - infoboxReadRequest = new InfoboxReadRequest(); - infoboxReadRequest.setInfoboxIdentifier(INFOBOX_IDENTIFIER_IDENTITY_LINK); - infoboxReadRequest.setDomainIdentifier(identityLinkDomainIdentifier); - stalRequests.add(infoboxReadRequest); - - // get certificates - infoboxReadRequest = new InfoboxReadRequest(); - infoboxReadRequest.setInfoboxIdentifier("SecureSignatureKeypair"); - stalRequests.add(infoboxReadRequest); - infoboxReadRequest = new InfoboxReadRequest(); - infoboxReadRequest.setInfoboxIdentifier("CertifiedKeypair"); - stalRequests.add(infoboxReadRequest); - - requestSTAL(stalRequests); - log.trace("Got STAL response"); - - IdentityLink identityLink = getIdentityLinkFromResponses(); - List certificates = getCertificatesFromResponses(); - - - CompressedIdentityLinkFactory idLinkFactory = CompressedIdentityLinkFactory.getInstance(); - JAXBElement compressedIdentityLink = idLinkFactory - .createCompressedIdentityLink(identityLink, certificates, identityLinkDomainIdentifier); - - IdentityLinkTransformer identityLinkTransformer = IdentityLinkTransformer.getInstance(); - String issuerTemplate = identityLink.getIssuerTemplate(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db; - try { - db = dbf.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - log.error("Failed to create XML document.", e); - throw new SLRuntimeException(e); - } - - Document document = db.newDocument(); - try { - idLinkFactory.marshallCompressedIdentityLink(compressedIdentityLink, document, null, true); - } catch (JAXBException e) { - log.info("Failed to marshall CompressedIdentityLink.", e); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, - new Object[] { INFOBOX_IDENTIFIER_IDENTITY_LINK }); - } - - InfoboxReadResultFileImpl result = new InfoboxReadResultFileImpl(); - ByteArrayOutputStream resultBytes = null; - Result xmlResult = (isXMLEntity || identityLinkDomainIdentifier != null) - ? result.getXmlResult(true) - : new StreamResult((resultBytes = new ByteArrayOutputStream())); + try { - log.trace("Trying to transform identitylink"); - identityLinkTransformer.transformIdLink(issuerTemplate, new DOMSource(document), xmlResult); - } catch (MalformedURLException e) { - log.warn("Malformed issuer template URL '" + issuerTemplate + "'."); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } catch (IOException e) { - log.warn("Failed to dereferene issuer template URL '" + issuerTemplate + "'." ,e); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } catch (TransformerConfigurationException e) { - log.warn("Failed to create transformation template from issuer template URL '" + issuerTemplate + "'", e); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } catch (TransformerException e) { - log.info("Faild to transform CompressedIdentityLink.", e); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } - - // TODO: Report BUG in IssuerTemplates - // Some IssuerTemplate stylesheets do not consider the pr:Type-Element of the CompressedIdentityLink ... - if (identityLinkDomainIdentifier != null) { - if (xmlResult instanceof DOMResult) { - Node node = ((DOMResult) xmlResult).getNode(); - Node nextSibling = ((DOMResult) xmlResult).getNextSibling(); - Node idLinkNode; - if (nextSibling != null) { - idLinkNode = nextSibling.getPreviousSibling(); - } else if (node != null) { - idLinkNode = node.getFirstChild(); - } else { - log - .error("An IdentityLinkDomainIdentifier of '" - + identityLinkDomainIdentifier - + "' has been given. However, it cannot be set, as the transformation result does not contain a node."); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } - IdentityLinkTransformer.setDomainIdentifier(idLinkNode, identityLinkDomainIdentifier); - } else { - log - .error("An IdentityLinkDomainIdentifier of '" - + identityLinkDomainIdentifier - + "' has been given. However, it cannot be set, as the transformation result is not of type DOM."); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } - } - - if (!isXMLEntity) { - if (resultBytes == null) { - resultBytes = new ByteArrayOutputStream(); - - if (xmlResult instanceof DOMResult) { - Node node = ((DOMResult) xmlResult).getNode(); - Node nextSibling = ((DOMResult) xmlResult).getNextSibling(); - - DOMSource xmlSource; - if (nextSibling != null) { - xmlSource = new DOMSource(nextSibling.getPreviousSibling()); - } else if (node != null) { - xmlSource = new DOMSource(node.getFirstChild()); - } else { - log - .error("IssuerTemplate transformation returned no node."); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - try { - Transformer transformer = transformerFactory.newTransformer(); - transformer.transform(xmlSource, new StreamResult(resultBytes)); - } catch (TransformerConfigurationException e) { - log.error(e); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } catch (TransformerException e) { - log.error(e); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } - } else if (xmlResult instanceof StreamResult) { - OutputStream outputStream = ((StreamResult) xmlResult).getOutputStream(); - if (outputStream instanceof ByteArrayOutputStream) { - result.setResultBytes(((ByteArrayOutputStream) outputStream).toByteArray()); - } else { - log.error("ContentIsXMLEntity is set to 'false'. However, an XMLResult has already been set."); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } - } - } else { - result.setResultBytes(resultBytes.toByteArray()); - } - } - - - return result; - - } - - protected List findCertificates(String searchString) throws SLCommandException { - - if ("*".equals(searchString) || "**".equals(searchString)) { - return Arrays.asList(INFOXBOX_CERTIFICATES_KEYS); + return infobox.read(getRequestValue(), getCmdCtx()); + } catch (SLCommandException e) { + return new ErrorResultImpl(e, getCmdCtx().getLocale()); } - if (Pattern.matches(SEARCH_STRING_PATTERN, searchString)) { - -// for (int i = 0; i < searchString.length(); i++) { -// int codePoint = searchString.codePointAt(i); -// -// } - - // TODO : build pattern - return Collections.emptyList(); + } + + + @Override + public String getIdentityLinkDomainId() { + if (infobox instanceof IdentityLinkInfoboxImpl) { + return ((IdentityLinkInfoboxImpl) infobox).getDomainIdentifier(); } else { - log.info("Got invalid search string '" + searchString + "'"); - throw new SLCommandException(4010); + return null; } - } - private SLResult readCertificates() throws SLCommandException { - - ObjectFactory objectFactory = new ObjectFactory(); - - InfoboxReadDataAssocArrayType infoboxReadDataAssocArrayType = objectFactory - .createInfoboxReadDataAssocArrayType(); - - if (assocArrayResult == ASSOC_ARRAY_READ_KEYS) { - - List keys = infoboxReadDataAssocArrayType.getKey(); - keys.addAll(certificates); - + @Override + public String getInfoboxIdentifier() { + if (infobox != null) { + return infobox.getIdentifier(); } else { - - if (certificates != null && !certificates.isEmpty()) { - - List stalRequests = new ArrayList(); - - // get certificates - InfoboxReadRequest infoboxReadRequest; - for (int i = 0; i < certificates.size(); i++) { - infoboxReadRequest = new InfoboxReadRequest(); - infoboxReadRequest.setInfoboxIdentifier(certificates.get(i)); - stalRequests.add(infoboxReadRequest); - } - - requestSTAL(stalRequests); - - List x509Certs = getCertificatesFromResponses(); - - for (int i = 0; i < certificates.size(); i++) { - InfoboxAssocArrayPairType infoboxAssocArrayPairType = objectFactory.createInfoboxAssocArrayPairType(); - infoboxAssocArrayPairType.setKey(certificates.get(i)); - try { - infoboxAssocArrayPairType.setBase64Content(x509Certs.get(i).getEncoded()); - } catch (CertificateEncodingException e) { - log.error("Failed to encode certificate.", e); - throw new SLCommandException(4000); - } - infoboxReadDataAssocArrayType.getPair().add(infoboxAssocArrayPairType); - } - - } - + return null; } - - return new InfoboxReadResultImpl(infoboxReadDataAssocArrayType); - - } - - @Override - public String getIdentityLinkDomainId() { - return identityLinkDomainIdentifier; } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java index 8904eac6..a2b8ac9f 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java @@ -23,8 +23,9 @@ import javax.xml.transform.Templates; import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadDataAssocArrayType; import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadResponseType; import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.gv.egiz.bku.slcommands.InfoboxReadResult; -public class InfoboxReadResultImpl extends SLResultImpl { +public class InfoboxReadResultImpl extends SLResultImpl implements InfoboxReadResult { /** * The InfoboxReadResponse diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateCommandImpl.java new file mode 100644 index 00000000..6d281686 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateCommandImpl.java @@ -0,0 +1,158 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.buergerkarte.namespaces.cardchannel.CommandAPDUType; +import at.buergerkarte.namespaces.cardchannel.ResetType; +import at.buergerkarte.namespaces.cardchannel.ScriptType; +import at.buergerkarte.namespaces.cardchannel.VerifyAPDUType; +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLContentType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxUpdateRequestType; +import at.gv.egiz.bku.slcommands.InfoboxUpdateCommand; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slcommands.SLResult; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLExceptionMessages; + +public class InfoboxUpdateCommandImpl extends + SLCommandImpl implements InfoboxUpdateCommand { + + private static Log log = LogFactory.getLog(InfoboxUpdateCommandImpl.class); + + public static final String INFOBOX_IDENTIFIER_CARD_CHANNEL = "CardChannel"; + + protected String infoboxIdentifier; + + protected List cardChannelScript; + + @Override + public String getInfoboxIdentifier() { + return infoboxIdentifier; + } + + @Override + public void init(SLCommandContext ctx, Object request) + throws SLCommandException { + super.init(ctx, request); + + InfoboxUpdateRequestType req = getRequestValue(); + + infoboxIdentifier = req.getInfoboxIdentifier(); + + if (INFOBOX_IDENTIFIER_CARD_CHANNEL.equals(infoboxIdentifier)) { + + if (req.getAssocArrayParameters() != null) { + log.info("Got AssocArrayParameters but Infobox type is BinaryFile."); + throw new SLCommandException(4010); + } + + Base64XMLContentType binaryFileParameters = req.getBinaryFileParameters(); + if (binaryFileParameters == null) { + log.info("Got no BinaryFileParameters but Infobox type is BinaryFile."); + throw new SLCommandException(4010); + } + + if (binaryFileParameters.getBase64Content() == null) { + log.info("Got Base64Content but ContentIsXMLEntity is true."); + throw new SLCommandException(4010); + } + + List content = binaryFileParameters.getXMLContent().getContent(); + if (content.isEmpty()) { + log.info("Got no XMLContent but ContentIsXMLEntity is true."); + throw new SLCommandException(4010); + } + + for (Object element : content) { + if (!(element instanceof ScriptType)) { + log.info("Infobox identifier is '" + infoboxIdentifier + "' but XMLContent does not contain 'Script'."); + throw new SLCommandException(4010); + } + + setCardChannelScript(((ScriptType) element).getResetOrCommandAPDUOrVerifyAPDU()); + } + + if (getCardChannelScript() == null) { + log.info("Infobox identifier is '" + infoboxIdentifier + "' but XMLContent does not contain 'Script'."); + throw new SLCommandException(4010); + } + + } else { + throw new SLCommandException(4002, + SLExceptionMessages.EC4002_INFOBOX_UNKNOWN, + new Object[] { infoboxIdentifier }); + } + + } + + public List getCardChannelScript() { + return cardChannelScript; + } + + public void setCardChannelScript(List cardChannelScript) { + this.cardChannelScript = cardChannelScript; + } + + @Override + public SLResult execute() { + + try { + if (INFOBOX_IDENTIFIER_CARD_CHANNEL.equals(getInfoboxIdentifier())) { + + executeCardChannelScript(); + return new InfoboxUpdateResultImpl(); + + } else { + throw new SLCommandException(4002, + SLExceptionMessages.EC4002_INFOBOX_UNKNOWN, + new Object[] { infoboxIdentifier }); + } + } catch (SLCommandException e) { + return new ErrorResultImpl(e, cmdCtx.getLocale()); + } + + } + + protected void executeCardChannelScript() throws SLCommandException { + + if (cardChannelScript != null) { + + for (Object element : cardChannelScript) { + if (element instanceof ResetType) { + + } else if (element instanceof CommandAPDUType) { + + } else if (element instanceof VerifyAPDUType) { + + } + } + + } + + } + + @Override + public String getName() { + return "InfoboxUpdateRequest"; + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateResultImpl.java new file mode 100644 index 00000000..15064756 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateResultImpl.java @@ -0,0 +1,43 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import javax.xml.bind.JAXBElement; +import javax.xml.transform.Result; +import javax.xml.transform.Templates; + +import at.buergerkarte.namespaces.securitylayer._1.InfoboxUpdateResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.gv.egiz.bku.slcommands.InfoboxUpdateResult; + +public class InfoboxUpdateResultImpl extends SLResultImpl implements + InfoboxUpdateResult { + + protected static JAXBElement RESPONSE; + + static { + ObjectFactory factory = new ObjectFactory(); + InfoboxUpdateResponseType type = factory.createInfoboxUpdateResponseType(); + RESPONSE = factory.createInfoboxUpdateResponse(type); + } + + @Override + public void writeTo(Result result, Templates templates) { + writeTo(RESPONSE, result, templates); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLCommandImpl.java index 9a3a2984..ed055b69 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLCommandImpl.java @@ -16,22 +16,11 @@ */ package at.gv.egiz.bku.slcommands.impl; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.xml.bind.JAXBElement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import at.gv.egiz.bku.slcommands.SLCommand; -import at.gv.egiz.bku.slcommands.SLCommandContext; -import at.gv.egiz.bku.slexceptions.SLCommandException; -import at.gv.egiz.stal.ErrorResponse; -import at.gv.egiz.stal.STAL; -import at.gv.egiz.stal.STALRequest; -import at.gv.egiz.stal.STALResponse; +import javax.xml.bind.JAXBElement; + +import at.gv.egiz.bku.slcommands.SLCommand; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; /** * This class serves as abstract base class for the implementation of a security @@ -47,19 +36,18 @@ public abstract class SLCommandImpl implements SLCommand { /** * The SLCommandContext for this SLCommand. */ - protected SLCommandContext cmdCtx; + protected SLCommandContext cmdCtx; + + /** + * The STAL helper. + */ + protected STALHelper stalHelper; /** * The request element of this command. */ protected JAXBElement request; - /** - * An iterator over the STALResponses received in - * {@link SLCommandImpl#requestSTAL(List)}. - */ - protected Iterator stalResponses; - @SuppressWarnings("unchecked") @Override public void init(SLCommandContext ctx, Object request) @@ -67,8 +55,8 @@ public abstract class SLCommandImpl implements SLCommand { this.request = (JAXBElement) request; - this.cmdCtx = ctx; - assert this.cmdCtx != null; + this.cmdCtx = ctx; + stalHelper = new STALHelper(cmdCtx.getSTAL()); } @@ -90,73 +78,4 @@ public abstract class SLCommandImpl implements SLCommand { protected SLCommandContext getCmdCtx() { return cmdCtx; } - - /** - * Calls {@link STAL#handleRequest(List)} with the given - * stalRequests. - * - * @param stalRequests - * @throws SLCommandException - */ - protected void requestSTAL(List stalRequests) throws SLCommandException { - List responses = cmdCtx.getSTAL().handleRequest(stalRequests); - if (responses == null) { - Log log = LogFactory.getLog(this.getClass()); - log.info("Received no responses from STAL."); - throw new SLCommandException(4000); - } else if (responses.size() != stalRequests.size()) { - Log log = LogFactory.getLog(this.getClass()); - log.info("Received invalid count of responses from STAL. Expected " - + stalRequests.size() + ", but got " + responses.size() + "."); - // throw new SLCommandException(4000); - } - stalResponses = responses.iterator(); - } - - /** - * @return true if there are more {@link STALResponse}s to be - * fetched with {@link #nextResponse(Class)}, or false - * otherwise. - */ - protected boolean hasNextResponse() { - return (stalResponses != null) ? stalResponses.hasNext() : false; - } - - /** - * Returns the next response of type responseClass that has been - * received by {@link #requestSTAL(List)}. - * - * @param responseClass - * the response must be an instance of - * @return the next response of type responseClass - * - * @throws NoSuchElementException - * if there is no more response - * @throws SLCommandException - * if the next response is of type {@link ErrorResponse} or not of - * type responseClass - */ - protected STALResponse nextResponse( - Class responseClass) throws SLCommandException { - - if (stalResponses == null) { - throw new NoSuchElementException(); - } - - STALResponse response = stalResponses.next(); - - if (response instanceof ErrorResponse) { - throw new SLCommandException(((ErrorResponse) response).getErrorCode()); - } - - if (!(responseClass.isAssignableFrom(response.getClass()))) { - Log log = LogFactory.getLog(this.getClass()); - log.info("Received " + response.getClass() + " from STAL but expected " - + responseClass); - throw new SLCommandException(4000); - } - - return response; - - } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java new file mode 100644 index 00000000..969288c1 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java @@ -0,0 +1,218 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import iaik.asn1.CodingException; +import iaik.asn1.DerCoder; + +import java.io.ByteArrayInputStream; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLExceptionMessages; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import at.gv.egiz.idlink.ans1.IdentityLink; +import at.gv.egiz.stal.ErrorResponse; +import at.gv.egiz.stal.InfoboxReadResponse; +import at.gv.egiz.stal.STAL; +import at.gv.egiz.stal.STALRequest; +import at.gv.egiz.stal.STALResponse; + +/** + * A helper class for transmitting {@link STALRequest}s and obtaining their + * respective {@link STALResponse}s. + * + * @author mcentner + */ +public class STALHelper { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(STALHelper.class); + + /** + * The STAL implementation. + */ + private STAL stal; + + /** + * An iterator over the STALResponses received in + * {@link SLCommandImpl#transmitSTALRequest(List)}. + */ + protected Iterator stalResponses; + + /** + * Creates a new instance of this STALHelper with the given + * stal. + * + * @param stal the STAL to be used + */ + public STALHelper(STAL stal) { + if (stal == null) { + throw new NullPointerException("Argument 'stal' must not be null."); + } + this.stal = stal; + } + + /** + * Calls {@link STAL#handleRequest(List)} with the given + * stalRequests. + * + * @param stalRequests + * @throws SLCommandException + */ + public void transmitSTALRequest(List stalRequests) throws SLCommandException { + List responses = stal.handleRequest(stalRequests); + if (responses == null) { + Log log = LogFactory.getLog(this.getClass()); + log.info("Received no responses from STAL."); + throw new SLCommandException(4000); + } else if (responses.size() != stalRequests.size()) { + Log log = LogFactory.getLog(this.getClass()); + log.info("Received invalid count of responses from STAL. Expected " + + stalRequests.size() + ", but got " + responses.size() + "."); + // throw new SLCommandException(4000); + } + stalResponses = responses.iterator(); + } + + /** + * @return true if there are more {@link STALResponse}s to be + * fetched with {@link #nextResponse(Class)}, or false + * otherwise. + */ + public boolean hasNextResponse() { + return (stalResponses != null) ? stalResponses.hasNext() : false; + } + + /** + * Returns the next response of type responseClass that has been + * received by {@link #transmitSTALRequest(List)}. + * + * @param responseClass + * the response must be an instance of + * @return the next response of type responseClass + * + * @throws NoSuchElementException + * if there is no more response + * @throws SLCommandException + * if the next response is of type {@link ErrorResponse} or not of + * type responseClass + */ + public STALResponse nextResponse( + Class responseClass) throws SLCommandException { + + if (stalResponses == null) { + throw new NoSuchElementException(); + } + + STALResponse response = stalResponses.next(); + + if (response instanceof ErrorResponse) { + throw new SLCommandException(((ErrorResponse) response).getErrorCode()); + } + + if (!(responseClass.isAssignableFrom(response.getClass()))) { + Log log = LogFactory.getLog(this.getClass()); + log.info("Received " + response.getClass() + " from STAL but expected " + + responseClass); + throw new SLCommandException(4000); + } + + return response; + + } + + /** + * Gets the list of certificates from the next STAL responses. + * + * @return the list of certificates + * + * @throws SLCommandException if getting the list of certificates fails + */ + public List getCertificatesFromResponses() throws SLCommandException { + + List certificates = new ArrayList(); + + CertificateFactory certFactory; + try { + certFactory = CertificateFactory.getInstance("X509"); + } catch (CertificateException e) { + // we should always be able to get an X509 certificate factory + log.error("CertificateFactory.getInstance(\"X509\") failed.", e); + throw new SLRuntimeException(e); + } + + InfoboxReadResponse response; + while(hasNextResponse()) { + response = (InfoboxReadResponse) nextResponse(InfoboxReadResponse.class); + byte[] cert = response.getInfoboxValue(); + try { + certificates.add((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(cert))); + } catch (CertificateException e) { + log.info("Failed to decode certificate.", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, + new Object[] { "Certificates" }); + } + } + + return certificates; + + } + + /** + * Gets the IdentitiyLink form the next STAL response. + * + * @return the IdentityLink + * + * @throws SLCommandException if getting the IdentitiyLink fails + */ + public IdentityLink getIdentityLinkFromResponses() throws SLCommandException { + + // IdentityLink + InfoboxReadResponse response; + if (hasNextResponse()) { + response = (InfoboxReadResponse) nextResponse(InfoboxReadResponse.class); + byte[] idLink = response.getInfoboxValue(); + try { + return new IdentityLink(DerCoder.decode(idLink)); + } catch (CodingException e) { + log.info("Failed to decode infobox 'IdentityLink'.", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, + new Object[] { "IdentityLink" }); + } + } else { + log.info("No infobox 'IdentityLink' returned from STAL."); + throw new SLCommandException(4000); + } + + } + + +} -- cgit v1.2.3 From e51d51cf7f51a54b5e4e3414ac428fc6eecf5d8d Mon Sep 17 00:00:00 2001 From: mcentner Date: Fri, 5 Dec 2008 09:28:44 +0000 Subject: Fixed issue in InfoboxFactory. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@233 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java index 4a03fe74..e9736f6d 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java @@ -80,7 +80,7 @@ public class InfoboxFactory { for (String key : infoboxImplMap.keySet()) { Class impl = (Class) cl.loadClass(infoboxImplMap.get(key)); log.debug("Registering infobox '" + key + "' implementation '" + impl.getCanonicalName() + "'."); - implementations.put(key, impl); + implMap.put(key, impl); } implementations = implMap; } -- cgit v1.2.3 From 2df9621154ad057f6cace73efe49c9ef42515fde Mon Sep 17 00:00:00 2001 From: mcentner Date: Tue, 9 Dec 2008 08:14:43 +0000 Subject: Refactored STAL interface. Additional infobox functionality. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@236 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/AbstractBinaryFileInfobox.java | 4 +- .../impl/AbstractInfoboxCommandImpl.java | 9 + .../bku/slcommands/impl/AbstractInfoboxImpl.java | 19 ++ .../slcommands/impl/CardChannelInfoboxImpl.java | 235 +++++++++++++++++++++ .../at/gv/egiz/bku/slcommands/impl/Infobox.java | 21 +- .../slcommands/impl/InfoboxReadCommandImpl.java | 9 - .../bku/slcommands/impl/InfoboxReadResultImpl.java | 12 ++ .../slcommands/impl/InfoboxUpdateCommandImpl.java | 124 ++--------- .../gv/egiz/bku/slcommands/impl/SLResultImpl.java | 56 +++++ .../at/gv/egiz/bku/slcommands/impl/STALHelper.java | 2 +- 10 files changed, 372 insertions(+), 119 deletions(-) create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CardChannelInfoboxImpl.java (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractBinaryFileInfobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractBinaryFileInfobox.java index 07ca639c..23394bd5 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractBinaryFileInfobox.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractBinaryFileInfobox.java @@ -37,7 +37,7 @@ public abstract class AbstractBinaryFileInfobox extends AbstractInfoboxImpl impl /** * Is this infobox' content an XML entity? */ - private boolean isXMLEntity = false; + protected boolean isXMLEntity = false; /** * @return true if this infobox' content is an XML entity or false otherwise. @@ -61,8 +61,6 @@ public abstract class AbstractBinaryFileInfobox extends AbstractInfoboxImpl impl } } - - } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java index 305769a8..8a7edb71 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java @@ -52,4 +52,13 @@ public abstract class AbstractInfoboxCommandImpl extends SLCommandImpl { */ protected abstract String getInfoboxIdentifier(T request); + + public String getInfoboxIdentifier() { + if (infobox != null) { + return infobox.getIdentifier(); + } else { + return null; + } + } + } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxImpl.java index e5c7afcc..564cb8ff 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxImpl.java @@ -16,6 +16,13 @@ */ package at.gv.egiz.bku.slcommands.impl; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxUpdateRequestType; +import at.gv.egiz.bku.slcommands.InfoboxReadResult; +import at.gv.egiz.bku.slcommands.InfoboxUpdateResult; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; + /** * An abstract base class for {@link Infobox} implementations. * @@ -23,4 +30,16 @@ package at.gv.egiz.bku.slcommands.impl; */ public abstract class AbstractInfoboxImpl implements Infobox { + @Override + public InfoboxReadResult read(InfoboxReadRequestType request, + SLCommandContext cmdCtx) throws SLCommandException { + throw new SLCommandException(4011); + } + + @Override + public InfoboxUpdateResult update(InfoboxUpdateRequestType request, + SLCommandContext cmdCtx) throws SLCommandException { + throw new SLCommandException(4011); + } + } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CardChannelInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CardChannelInfoboxImpl.java new file mode 100644 index 00000000..4b1cc779 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CardChannelInfoboxImpl.java @@ -0,0 +1,235 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.WeakHashMap; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.buergerkarte.namespaces.cardchannel.ATRType; +import at.buergerkarte.namespaces.cardchannel.CommandAPDUType; +import at.buergerkarte.namespaces.cardchannel.ObjectFactory; +import at.buergerkarte.namespaces.cardchannel.ResetType; +import at.buergerkarte.namespaces.cardchannel.ResponseAPDUType; +import at.buergerkarte.namespaces.cardchannel.ResponseType; +import at.buergerkarte.namespaces.cardchannel.ScriptType; +import at.buergerkarte.namespaces.cardchannel.VerifyAPDUType; +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLContentType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxUpdateRequestType; +import at.buergerkarte.namespaces.securitylayer._1.XMLContentType; +import at.gv.egiz.bku.slcommands.InfoboxReadResult; +import at.gv.egiz.bku.slcommands.InfoboxUpdateResult; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import at.gv.egiz.stal.STAL; +import at.gv.egiz.stal.ext.APDUScriptRequest; +import at.gv.egiz.stal.ext.APDUScriptResponse; +import at.gv.egiz.stal.ext.APDUScriptRequest.RequestScriptElement; +import at.gv.egiz.stal.ext.APDUScriptResponse.ResponseScriptElement; + +public class CardChannelInfoboxImpl extends AbstractBinaryFileInfobox { + + private static Log log = LogFactory.getLog(CardChannelInfoboxImpl.class); + + private static WeakHashMap> scriptResults = new WeakHashMap>(); + + private static JAXBContext jaxbContext; + + static { + try { + jaxbContext = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName()); + } catch (JAXBException e) { + throw new SLRuntimeException("Failed to initalize CardChannel infobox.", e); + } + } + + public CardChannelInfoboxImpl() { + isXMLEntity = true; + } + + @Override + public String getIdentifier() { + return "CardChannel"; + } + + @Override + public InfoboxReadResult read(InfoboxReadRequestType request, + SLCommandContext cmdCtx) throws SLCommandException { + + at.buergerkarte.namespaces.securitylayer._1.ObjectFactory objectFactory + = new at.buergerkarte.namespaces.securitylayer._1.ObjectFactory(); + + Base64XMLContentType content = objectFactory.createBase64XMLContentType(); + XMLContentType xmlContent = objectFactory.createXMLContentType(); + content.setXMLContent(xmlContent); + + JAXBElement response = scriptResults.get(cmdCtx.getSTAL()); + if (response != null) { + xmlContent.getContent().add(response); + } + + return new InfoboxReadResultImpl(content); + + } + + @SuppressWarnings("unchecked") + @Override + public InfoboxUpdateResult update(InfoboxUpdateRequestType request, + SLCommandContext cmdCtx) throws SLCommandException { + + Base64XMLContentType binaryFileParameters = request.getBinaryFileParameters(); + + if (binaryFileParameters.getBase64Content() != null) { + log.info("Got Base64Content but ContentIsXMLEntity is true."); + throw new SLCommandException(4010); + } + + XMLContentType content = binaryFileParameters.getXMLContent(); + if (content instanceof at.gv.egiz.slbinding.impl.XMLContentType) { + + ByteArrayOutputStream redirectedStream = ((at.gv.egiz.slbinding.impl.XMLContentType) content).getRedirectedStream(); + if (redirectedStream != null) { + + if (log.isDebugEnabled()) { + + StringBuilder sb = new StringBuilder(); + sb.append("CardChannel script:\n"); + try { + sb.append(new String(redirectedStream.toByteArray(), "UTF-8")); + } catch (UnsupportedEncodingException e) { + sb.append(e.getMessage()); + } + log.debug(sb.toString()); + } + + Object object; + try { + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + object = unmarshaller.unmarshal(new ByteArrayInputStream(redirectedStream.toByteArray())); + } catch (JAXBException e) { + log.info("Failed to parse CardChannel script.", e); + throw new SLCommandException(4011); + } + + if (object instanceof JAXBElement) { + executeCardChannelScript(((JAXBElement) object).getValue(), cmdCtx); + return new InfoboxUpdateResultImpl(); + } + + } + + + } + log.info("Infobox identifier is '" + getIdentifier() + "' but XMLContent does not contain 'Script'."); + throw new SLCommandException(4010); + + } + + protected void executeCardChannelScript(ScriptType script, + SLCommandContext cmdCtx) throws SLCommandException { + + List resetOrCommandAPDUOrVerifyAPDU = script.getResetOrCommandAPDUOrVerifyAPDU(); + List requestScript = new ArrayList(); + + for (Object element : resetOrCommandAPDUOrVerifyAPDU) { + + if (element instanceof ResetType) { + + requestScript.add(new APDUScriptRequest.Reset()); + + } else if (element instanceof CommandAPDUType) { + + CommandAPDUType commandAPDU = (CommandAPDUType) element; + int sequence = (commandAPDU.getSequence() != null) + ? commandAPDU.getSequence().intValue() + : 0; + + requestScript.add( + new APDUScriptRequest.Command( + sequence, + commandAPDU.getValue(), + commandAPDU.getExpectedSW())); + + } else if (element instanceof VerifyAPDUType) { + log.warn("CardChannel script command 'VerifyAPDU' not implemented."); + throw new SLCommandException(4011); + } + } + + APDUScriptRequest scriptRequest = new APDUScriptRequest(requestScript); + + STAL stal = cmdCtx.getSTAL(); + STALHelper helper = new STALHelper(stal); + + helper.transmitSTALRequest(Collections.singletonList(scriptRequest)); + + List responseScript = ((APDUScriptResponse) helper + .nextResponse(APDUScriptResponse.class)).getScript(); + + ObjectFactory objectFactory = new ObjectFactory(); + + ResponseType responseType = objectFactory.createResponseType(); + + + for (ResponseScriptElement element : responseScript) { + + if (element instanceof APDUScriptResponse.ATR) { + + byte[] atr = ((APDUScriptResponse.ATR) element).getAtr(); + + ATRType atrType = objectFactory.createATRType(); + atrType.setValue(atr); + atrType.setRc(BigInteger.ZERO); + responseType.getATROrResponseAPDU().add(atrType); + + } else if (element instanceof APDUScriptResponse.Response) { + + APDUScriptResponse.Response response = (APDUScriptResponse.Response) element; + + ResponseAPDUType responseAPDUType = objectFactory.createResponseAPDUType(); + responseAPDUType.setSequence(BigInteger.valueOf(response.getSequence())); +// if (response.getRc() != 0) { + responseAPDUType.setRc(BigInteger.valueOf(response.getRc())); +// } + responseAPDUType.setSw(response.getSw()); + responseAPDUType.setValue(response.getApdu()); + + responseType.getATROrResponseAPDU().add(responseAPDUType); + } + + } + + scriptResults.put(stal, objectFactory.createResponse(responseType)); + } + + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/Infobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/Infobox.java index a6f8cbb2..99d62721 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/Infobox.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/Infobox.java @@ -17,7 +17,9 @@ package at.gv.egiz.bku.slcommands.impl; import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadRequestType; +import at.buergerkarte.namespaces.securitylayer._1.InfoboxUpdateRequestType; import at.gv.egiz.bku.slcommands.InfoboxReadResult; +import at.gv.egiz.bku.slcommands.InfoboxUpdateResult; import at.gv.egiz.bku.slcommands.SLCommandContext; import at.gv.egiz.bku.slexceptions.SLCommandException; @@ -44,10 +46,25 @@ public interface Infobox { * * @return the data read from this infobox as InfoboxReadResult * - * @throws SLCommandException - * if reading from this infobox fails + * @throws SLCommandException + * + * if reading from this infobox fails */ public InfoboxReadResult read(InfoboxReadRequestType request, SLCommandContext cmdCtx) throws SLCommandException; + /** + * Update data in this infobox. + * + * @param request + * the InfoboxUpdateRequest + * @param cmdCtx + * the command context + * @return a corresponding InfoboxUpdateResult + * @throws SLCommandException + * if updating this infobox fails + */ + public InfoboxUpdateResult update(InfoboxUpdateRequestType request, + SLCommandContext cmdCtx) throws SLCommandException; + } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java index aaa786a6..693f444f 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadCommandImpl.java @@ -83,7 +83,6 @@ public class InfoboxReadCommandImpl extends AbstractInfoboxCommandImpl implements InfoboxUpdateCommand { + AbstractInfoboxCommandImpl implements InfoboxUpdateCommand { private static Log log = LogFactory.getLog(InfoboxUpdateCommandImpl.class); - public static final String INFOBOX_IDENTIFIER_CARD_CHANNEL = "CardChannel"; + @Override + public String getName() { + return "InfoboxUpdateRequest"; + } - protected String infoboxIdentifier; - - protected List cardChannelScript; - @Override - public String getInfoboxIdentifier() { - return infoboxIdentifier; + protected String getInfoboxIdentifier(InfoboxUpdateRequestType request) { + return request.getInfoboxIdentifier(); } - + @Override - public void init(SLCommandContext ctx, Object request) - throws SLCommandException { + public void init(SLCommandContext ctx, Object request) throws SLCommandException { super.init(ctx, request); InfoboxUpdateRequestType req = getRequestValue(); - infoboxIdentifier = req.getInfoboxIdentifier(); + if (req.getAssocArrayParameters() != null && + !(infobox instanceof AssocArrayInfobox)) { + log.info("Got AssocArrayParameters but Infobox type is not AssocArray."); + throw new SLCommandException(4010); + } - if (INFOBOX_IDENTIFIER_CARD_CHANNEL.equals(infoboxIdentifier)) { - - if (req.getAssocArrayParameters() != null) { - log.info("Got AssocArrayParameters but Infobox type is BinaryFile."); - throw new SLCommandException(4010); - } - - Base64XMLContentType binaryFileParameters = req.getBinaryFileParameters(); - if (binaryFileParameters == null) { - log.info("Got no BinaryFileParameters but Infobox type is BinaryFile."); - throw new SLCommandException(4010); - } - - if (binaryFileParameters.getBase64Content() == null) { - log.info("Got Base64Content but ContentIsXMLEntity is true."); - throw new SLCommandException(4010); - } - - List content = binaryFileParameters.getXMLContent().getContent(); - if (content.isEmpty()) { - log.info("Got no XMLContent but ContentIsXMLEntity is true."); - throw new SLCommandException(4010); - } - - for (Object element : content) { - if (!(element instanceof ScriptType)) { - log.info("Infobox identifier is '" + infoboxIdentifier + "' but XMLContent does not contain 'Script'."); - throw new SLCommandException(4010); - } - - setCardChannelScript(((ScriptType) element).getResetOrCommandAPDUOrVerifyAPDU()); - } - - if (getCardChannelScript() == null) { - log.info("Infobox identifier is '" + infoboxIdentifier + "' but XMLContent does not contain 'Script'."); - throw new SLCommandException(4010); - } - - } else { - throw new SLCommandException(4002, - SLExceptionMessages.EC4002_INFOBOX_UNKNOWN, - new Object[] { infoboxIdentifier }); + if (req.getBinaryFileParameters() != null && + !(infobox instanceof BinaryFileInfobox)) { + log.info("Got BinaryFileParameters but Infobox type is not BinaryFile."); + throw new SLCommandException(4010); } } - public List getCardChannelScript() { - return cardChannelScript; - } - - public void setCardChannelScript(List cardChannelScript) { - this.cardChannelScript = cardChannelScript; - } - @Override public SLResult execute() { try { - if (INFOBOX_IDENTIFIER_CARD_CHANNEL.equals(getInfoboxIdentifier())) { - - executeCardChannelScript(); - return new InfoboxUpdateResultImpl(); - - } else { - throw new SLCommandException(4002, - SLExceptionMessages.EC4002_INFOBOX_UNKNOWN, - new Object[] { infoboxIdentifier }); - } + return infobox.update(getRequestValue(), getCmdCtx()); } catch (SLCommandException e) { - return new ErrorResultImpl(e, cmdCtx.getLocale()); + return new ErrorResultImpl(e, getCmdCtx().getLocale()); } } - - protected void executeCardChannelScript() throws SLCommandException { - - if (cardChannelScript != null) { - - for (Object element : cardChannelScript) { - if (element instanceof ResetType) { - - } else if (element instanceof CommandAPDUType) { - - } else if (element instanceof VerifyAPDUType) { - - } - } - - } - - } - - @Override - public String getName() { - return "InfoboxUpdateRequest"; - } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java index 80bbdca8..99a3b119 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java @@ -16,6 +16,7 @@ */ package at.gv.egiz.bku.slcommands.impl; +import java.io.UnsupportedEncodingException; import java.util.Locale; import javax.xml.bind.JAXBContext; @@ -32,6 +33,7 @@ import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -45,6 +47,8 @@ import at.gv.egiz.bku.slexceptions.SLBindingException; import at.gv.egiz.bku.slexceptions.SLCommandException; import at.gv.egiz.bku.slexceptions.SLException; import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import at.gv.egiz.bku.utils.DebugOutputStream; +import at.gv.egiz.bku.utils.DebugWriter; /** * This class serves as an abstract base class for the implementation of a @@ -128,6 +132,20 @@ public abstract class SLResultImpl implements SLResult { * @param templates */ protected void writeTo(JAXBElement response, Result result, Templates templates) { + + DebugWriter dw = null; + DebugOutputStream ds = null; + if (log.isTraceEnabled() && result instanceof StreamResult) { + StreamResult streamResult = (StreamResult) result; + if (streamResult.getOutputStream() != null) { + ds = new DebugOutputStream(streamResult.getOutputStream()); + streamResult.setOutputStream(ds); + } + if (streamResult.getWriter() != null) { + dw = new DebugWriter(streamResult.getWriter()); + streamResult.setWriter(dw); + } + } TransformerHandler transformerHandler = null; if (templates != null) { @@ -151,10 +169,36 @@ public abstract class SLResultImpl implements SLResult { writeErrorTo(commandException, result, templates); } + if (ds != null) { + try { + log.trace("Marshalled result:\n" + new String(ds.getBufferedBytes(), "UTF-8")); + } catch (UnsupportedEncodingException e) { + log.trace(e.getMessage()); + } + } + + if (dw != null) { + log.trace("Marshalled result:\n" + dw.getBufferedString()); + } + } protected void writeTo(Node node, Result result, Templates templates) { + DebugWriter dw = null; + DebugOutputStream ds = null; + if (log.isTraceEnabled() && result instanceof StreamResult) { + StreamResult streamResult = (StreamResult) result; + if (streamResult.getOutputStream() != null) { + ds = new DebugOutputStream(streamResult.getOutputStream()); + streamResult.setOutputStream(ds); + } + if (streamResult.getWriter() != null) { + dw = new DebugWriter(streamResult.getWriter()); + streamResult.setWriter(dw); + } + } + if (templates == null) { try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); @@ -179,7 +223,19 @@ public abstract class SLResultImpl implements SLResult { writeErrorTo(new SLException(2008), result, templates); } } + + if (ds != null) { + try { + log.trace("Marshalled result:\n" + new String(ds.getBufferedBytes(), "UTF-8")); + } catch (UnsupportedEncodingException e) { + log.trace(e.getMessage()); + } + } + if (dw != null) { + log.trace("Marshalled result:\n" + dw.getBufferedString()); + } + } protected void writeErrorTo(SLException slException, Result result, Templates templates) { diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java index 969288c1..0c7ce3f5 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java @@ -85,7 +85,7 @@ public class STALHelper { * @param stalRequests * @throws SLCommandException */ - public void transmitSTALRequest(List stalRequests) throws SLCommandException { + public void transmitSTALRequest(List stalRequests) throws SLCommandException { List responses = stal.handleRequest(stalRequests); if (responses == null) { Log log = LogFactory.getLog(this.getClass()); -- cgit v1.2.3 From 5d72bc4d896f4326dfe89e556dcc2b4de7806f4a Mon Sep 17 00:00:00 2001 From: wbauer Date: Tue, 9 Dec 2008 10:16:38 +0000 Subject: changed method visibility to use this class outside the package git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@240 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java index 78e2e7fa..98c2432f 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java @@ -56,7 +56,7 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements /** * The XML document containing the infobox content. */ - Document xmlDocument; + protected Document xmlDocument; /** * Creates the response document from the given binaryContent. @@ -112,7 +112,7 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements /** * @return an XMLResult for marshalling the infobox to */ - Result getXmlResult(boolean preserveSpace) { + public Result getXmlResult(boolean preserveSpace) { xmlDocument = createResponseDocument(null, preserveSpace); @@ -127,7 +127,7 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements * * @param resultBytes */ - void setResultBytes(byte[] resultBytes) { + public void setResultBytes(byte[] resultBytes) { xmlDocument = createResponseDocument(resultBytes, false); -- cgit v1.2.3 From e918d250c1dda9f8b7fccfc6f611b626f65e7a5c Mon Sep 17 00:00:00 2001 From: mcentner Date: Tue, 9 Dec 2008 10:59:08 +0000 Subject: Added method for setting a document as result of InfoboxReadResultFileImpl. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@241 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/InfoboxReadResultFileImpl.java | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java index 98c2432f..e43d99c6 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java @@ -29,6 +29,7 @@ import javax.xml.transform.dom.DOMResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; +import org.w3c.dom.Node; import org.w3c.dom.NodeList; import at.buergerkarte.namespaces.securitylayer._1.Base64XMLContentType; @@ -119,8 +120,25 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements NodeList nodeList = xmlDocument.getElementsByTagNameNS(SLCommand.NAMESPACE_URI, "XMLContent"); return new DOMResult(nodeList.item(0)); - } - + } + + /** + * Creates a new InfoboxReadResponse document and appends + * the given node as child node of the XMLContent element. + * + * @param node the node to be appended as child node of the XMLContnet element + * @param preserveSpace if true the value of the XMLContent's space + * attribute is set to preserve. + */ + public void setResultXMLContent(Node node, boolean preserveSpace) { + + xmlDocument = createResponseDocument(null, preserveSpace); + + NodeList nodeList = xmlDocument.getElementsByTagNameNS(SLCommand.NAMESPACE_URI, "XMLContent"); + nodeList.item(0).appendChild(node); + + } + /** * Creates a new result document for this InfoboxReadResult * and sets the given resultBytes as content. -- cgit v1.2.3 From dbfd110e2e502b561241e7578a7028dce48f961c Mon Sep 17 00:00:00 2001 From: mcentner Date: Tue, 9 Dec 2008 15:50:02 +0000 Subject: Updated InfoboxReadResultFileImpl to cope with nodes from different documents. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@243 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java index e43d99c6..c26bcd0b 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java @@ -135,6 +135,10 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements xmlDocument = createResponseDocument(null, preserveSpace); NodeList nodeList = xmlDocument.getElementsByTagNameNS(SLCommand.NAMESPACE_URI, "XMLContent"); + if (node.getOwnerDocument() != xmlDocument.getOwnerDocument()) { + Document doc = xmlDocument.getOwnerDocument(); + node = doc.importNode(node, true); + } nodeList.item(0).appendChild(node); } -- cgit v1.2.3 From 6f34b1722aa7e6c4a726a7376499a17fd2691f47 Mon Sep 17 00:00:00 2001 From: mcentner Date: Tue, 9 Dec 2008 15:57:42 +0000 Subject: Updated InfoboxReadResultFileImpl to cope with nodes from different documents. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@244 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java index c26bcd0b..d8295227 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java @@ -135,9 +135,8 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements xmlDocument = createResponseDocument(null, preserveSpace); NodeList nodeList = xmlDocument.getElementsByTagNameNS(SLCommand.NAMESPACE_URI, "XMLContent"); - if (node.getOwnerDocument() != xmlDocument.getOwnerDocument()) { - Document doc = xmlDocument.getOwnerDocument(); - node = doc.importNode(node, true); + if (node.getOwnerDocument() != xmlDocument) { + node = xmlDocument.importNode(node, true); } nodeList.item(0).appendChild(node); -- cgit v1.2.3 From 887f6727479f3ae3d89a08ba619f9382b450e4c1 Mon Sep 17 00:00:00 2001 From: mcentner Date: Fri, 12 Dec 2008 11:48:47 +0000 Subject: Updated SMCC to support non-blocking PIN entry. Added SV-Personendaten infobox implementation. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@248 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/AbstractAssocArrayInfobox.java | 96 +++--- .../impl/SVPersonendatenInfoboxImpl.java | 323 +++++++++++++++++++++ 2 files changed, 381 insertions(+), 38 deletions(-) create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SVPersonendatenInfoboxImpl.java (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java index e49ed6c0..e7f96c06 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java @@ -16,12 +16,17 @@ */ package at.gv.egiz.bku.slcommands.impl; +import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.regex.Pattern; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -36,6 +41,7 @@ import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayTy import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadValue; import at.gv.egiz.bku.slcommands.InfoboxReadResult; import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slcommands.SLCommandFactory; import at.gv.egiz.bku.slexceptions.SLCommandException; /** @@ -54,7 +60,7 @@ public abstract class AbstractAssocArrayInfobox extends AbstractInfoboxImpl /** * The search string pattern. */ - public static final String SEARCH_STRING_PATTERN = ".&&[^/](/.&&[^/])*"; + public static final String SEARCH_STRING_PATTERN = "(.&&[^/])+(/.&&[^/])*"; /** * @return the keys available in this infobox. @@ -93,6 +99,11 @@ public abstract class AbstractAssocArrayInfobox extends AbstractInfoboxImpl return Arrays.asList(getKeys()); } + if (!searchString.contains("*")) { + Arrays.asList(getKeys()).contains(searchString); + return Collections.singletonList(searchString); + } + if (Pattern.matches(SEARCH_STRING_PATTERN, searchString)) { // for (int i = 0; i < searchString.length(); i++) { @@ -160,15 +171,10 @@ public abstract class AbstractAssocArrayInfobox extends AbstractInfoboxImpl protected InfoboxReadResult readPairs(ReadPairs readPairs, SLCommandContext cmdCtx) throws SLCommandException { if (readPairs.isValuesAreXMLEntities() && !isValuesAreXMLEntities()) { - log.info("Got valuesAreXMLEntities=" + readPairs + " but infobox type is binary."); + log.info("Got valuesAreXMLEntities=" + readPairs.isValuesAreXMLEntities() + " but infobox type is binary."); throw new SLCommandException(4010); } - if (!readPairs.isValuesAreXMLEntities() && isValuesAreXMLEntities()) { - log.info("Got valuesAreXMLEntities=" + readPairs + " but infobox type is XML."); - throw new SLCommandException(4010); - } - List selectedKeys = selectKeys(readPairs.getSearchString()); if (readPairs.isUserMakesUnique() && selectedKeys.size() > 1) { @@ -177,26 +183,10 @@ public abstract class AbstractAssocArrayInfobox extends AbstractInfoboxImpl throw new SLCommandException(4010); } - ObjectFactory objectFactory = new ObjectFactory(); - - InfoboxReadDataAssocArrayType infoboxReadDataAssocArrayType = objectFactory.createInfoboxReadDataAssocArrayType(); - - Map values = getValues(selectedKeys, cmdCtx); - for (String key : selectedKeys) { - InfoboxAssocArrayPairType infoboxAssocArrayPairType = objectFactory.createInfoboxAssocArrayPairType(); - infoboxAssocArrayPairType.setKey(key); - Object value = values.get(key); - if (value instanceof byte[]) { - infoboxAssocArrayPairType.setBase64Content((byte[]) value); - } else { - infoboxAssocArrayPairType.setXMLContent((XMLContentType) value); - } - infoboxReadDataAssocArrayType.getPair().add(infoboxAssocArrayPairType); - } - - return new InfoboxReadResultImpl(infoboxReadDataAssocArrayType); + return new InfoboxReadResultImpl(marshallPairs(selectedKeys, getValues( + selectedKeys, cmdCtx), readPairs.isValuesAreXMLEntities())); } - + /** * Read the value specified by readPairs. * @@ -213,12 +203,7 @@ public abstract class AbstractAssocArrayInfobox extends AbstractInfoboxImpl protected InfoboxReadResult readValue(ReadValue readValue, SLCommandContext cmdCtx) throws SLCommandException { if (readValue.isValueIsXMLEntity() && !isValuesAreXMLEntities()) { - log.info("Got valuesAreXMLEntities=" + readValue + " but infobox type is binary."); - throw new SLCommandException(4010); - } - - if (!readValue.isValueIsXMLEntity() && isValuesAreXMLEntities()) { - log.info("Got valuesAreXMLEntities=" + readValue + " but infobox type is XML."); + log.info("Got valuesAreXMLEntities=" + readValue.isValueIsXMLEntity() + " but infobox type is binary."); throw new SLCommandException(4010); } @@ -230,24 +215,59 @@ public abstract class AbstractAssocArrayInfobox extends AbstractInfoboxImpl selectedKeys = Collections.emptyList(); } + return new InfoboxReadResultImpl(marshallPairs(selectedKeys, getValues( + selectedKeys, cmdCtx), readValue.isValueIsXMLEntity())); + + } + + protected InfoboxReadDataAssocArrayType marshallPairs(List selectedKeys, Map values, boolean areXMLEntities) throws SLCommandException { + ObjectFactory objectFactory = new ObjectFactory(); - + InfoboxReadDataAssocArrayType infoboxReadDataAssocArrayType = objectFactory.createInfoboxReadDataAssocArrayType(); - Map values = getValues(selectedKeys, cmdCtx); for (String key : selectedKeys) { InfoboxAssocArrayPairType infoboxAssocArrayPairType = objectFactory.createInfoboxAssocArrayPairType(); infoboxAssocArrayPairType.setKey(key); + Object value = values.get(key); - if (value instanceof byte[]) { - infoboxAssocArrayPairType.setBase64Content((byte[]) value); + if (areXMLEntities) { + if (value instanceof byte[]) { + log.info("Got valuesAreXMLEntities=" + areXMLEntities + " but infobox type is binary."); + throw new SLCommandException(4122); + } else { + XMLContentType contentType = objectFactory.createXMLContentType(); + contentType.getContent().add(value); + infoboxAssocArrayPairType.setXMLContent(contentType); + } } else { - infoboxAssocArrayPairType.setXMLContent((XMLContentType) value); + infoboxAssocArrayPairType.setBase64Content((value instanceof byte[]) ? (byte[]) value : marshallValue(value)); } + infoboxReadDataAssocArrayType.getPair().add(infoboxAssocArrayPairType); } + + return infoboxReadDataAssocArrayType; - return new InfoboxReadResultImpl(infoboxReadDataAssocArrayType); + } + + protected byte[] marshallValue(Object jaxbElement) throws SLCommandException { + SLCommandFactory commandFactory = SLCommandFactory.getInstance(); + JAXBContext jaxbContext = commandFactory.getJaxbContext(); + + ByteArrayOutputStream result; + try { + Marshaller marshaller = jaxbContext.createMarshaller(); + + result = new ByteArrayOutputStream(); + marshaller.marshal(jaxbElement, result); + } catch (JAXBException e) { + log.info("Failed to marshall infobox content.", e); + throw new SLCommandException(4122); + } + + return result.toByteArray(); + } @Override diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SVPersonendatenInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SVPersonendatenInfoboxImpl.java new file mode 100644 index 00000000..7e204632 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SVPersonendatenInfoboxImpl.java @@ -0,0 +1,323 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package at.gv.egiz.bku.slcommands.impl; + +import iaik.asn1.ASN; +import iaik.asn1.ASN1Object; +import iaik.asn1.CodingException; +import iaik.asn1.DerCoder; +import iaik.asn1.NumericString; +import iaik.asn1.OCTET_STRING; +import iaik.asn1.ObjectID; +import iaik.asn1.SEQUENCE; +import iaik.asn1.SET; +import iaik.asn1.UNKNOWN; +import iaik.asn1.structures.ChoiceOfTime; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.Charset; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; + +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import at.buergerkarte.namespaces.cardchannel.AttributeList; +import at.buergerkarte.namespaces.cardchannel.AttributeType; +import at.buergerkarte.namespaces.cardchannel.ObjectFactory; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLExceptionMessages; +import at.gv.egiz.stal.InfoboxReadRequest; +import at.gv.egiz.stal.InfoboxReadResponse; +import at.gv.egiz.stal.STALRequest; + +/** + * An implementation of the {@link Infobox} Certificates as + * specified in Security Layer 1.2. + * + * @author mcentner + */ +public class SVPersonendatenInfoboxImpl extends AbstractAssocArrayInfobox { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(SVPersonendatenInfoboxImpl.class); + + public static final String EHIC = "EHIC"; + + public static final String GRUNDDATEN = "Grunddaten"; + + public static final String STATUS = "Status"; + + public static final String SV_PERSONENBINDUNG = "SV-Personenbindung"; + + /** + * The valid keys. + */ + public static final String[] KEYS = new String[] { + GRUNDDATEN, EHIC, STATUS, SV_PERSONENBINDUNG + }; + + @Override + public String getIdentifier() { + return "SV-Personendaten"; + } + + @Override + public String[] getKeys() { + return KEYS; + } + + @Override + public boolean isValuesAreXMLEntities() { + return true; + } + + @Override + public Map getValues(List keys, SLCommandContext cmdCtx) throws SLCommandException { + + STALHelper stalHelper = new STALHelper(cmdCtx.getSTAL()); + + if (keys != null && !keys.isEmpty()) { + + List stalRequests = new ArrayList(); + + // get values + InfoboxReadRequest infoboxReadRequest; + for (int i = 0; i < keys.size(); i++) { + infoboxReadRequest = new InfoboxReadRequest(); + infoboxReadRequest.setInfoboxIdentifier(keys.get(i)); + stalRequests.add(infoboxReadRequest); + } + + stalHelper.transmitSTALRequest(stalRequests); + + Map values = new HashMap(); + + try { + for (int i = 0; i < keys.size(); i++) { + + String key = keys.get(i); + InfoboxReadResponse nextResponse = (InfoboxReadResponse) stalHelper.nextResponse(InfoboxReadResponse.class); + + + ObjectFactory objectFactory = new ObjectFactory(); + + if (EHIC.equals(key)) { + AttributeList attributeList = createAttributeList(nextResponse.getInfoboxValue()); + values.put(key, objectFactory.createEHIC(attributeList)); + } else if (GRUNDDATEN.equals(key)) { + AttributeList attributeList = createAttributeList(nextResponse.getInfoboxValue()); + values.put(key, objectFactory.createGrunddaten(attributeList)); + } else if (SV_PERSONENBINDUNG.equals(key)) { + values.put(key, objectFactory.createSVPersonenbindung(nextResponse.getInfoboxValue())); + } else if (STATUS.equals(key)) { + AttributeList attributeList = createAttributeListFromRecords(nextResponse.getInfoboxValue()); + values.put(key, objectFactory.createStatus(attributeList)); + } + + } + } catch (CodingException e) { + log.info("Failed to decode '" + getIdentifier() + "' infobox.", e); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, + new Object[] { "IdentityLink" }); + + } + + return values; + + } else { + + return new HashMap(); + + } + + + } + + public static AttributeList createAttributeList(byte[] infoboxValue) throws CodingException { + + ObjectFactory objectFactory = new ObjectFactory(); + + ASN1Object asn1 = DerCoder.decode(infoboxValue); + + AttributeList attributeList = objectFactory.createAttributeList(); + List attributes = attributeList.getAttribute(); + + if (asn1.isA(ASN.SEQUENCE)) { + for (int i = 0; i < ((SEQUENCE) asn1).countComponents(); i++) { + + AttributeType attributeType = objectFactory.createAttributeType(); + + if (asn1.getComponentAt(i).isA(ASN.SEQUENCE)) { + SEQUENCE attribute = (SEQUENCE) asn1.getComponentAt(i); + if (attribute.getComponentAt(0).isA(ASN.ObjectID)) { + ObjectID objectId = (ObjectID) attribute.getComponentAt(0); + attributeType.setOid("urn:oid:" + objectId.getID()); + } + if (attribute.getComponentAt(1).isA(ASN.SET)) { + SET values = (SET) attribute.getComponentAt(1); + for (int j = 0; j < values.countComponents(); j++) { + setAttributeValue(attributeType, values.getComponentAt(j)); + } + } + } + + attributes.add(attributeType); + + } + + } + + return attributeList; + + } + + public static AttributeList createAttributeListFromRecords(byte[] infoboxValue) throws CodingException { + + ObjectFactory objectFactory = new ObjectFactory(); + + AttributeList attributeList = objectFactory.createAttributeList(); + List attributes = attributeList.getAttribute(); + + byte[] records = infoboxValue; + + while (records != null && records.length > 0) { + + int length; + + if (records[0] != 0x00) { + + ASN1Object asn1 = DerCoder.decode(records); + + AttributeType attributeType = objectFactory.createAttributeType(); + + if (asn1.isA(ASN.SEQUENCE)) { + SEQUENCE attribute = (SEQUENCE) asn1; + if (attribute.getComponentAt(0).isA(ASN.ObjectID)) { + ObjectID objectId = (ObjectID) attribute.getComponentAt(0); + attributeType.setOid("urn:oid:" + objectId.getID()); + } + if (attribute.getComponentAt(1).isA(ASN.SET)) { + SET values = (SET) attribute.getComponentAt(1); + for (int j = 0; j < values.countComponents(); j++) { + setAttributeValue(attributeType, values.getComponentAt(j)); + } + } + } + + attributes.add(attributeType); + + length = DerCoder.encode(asn1).length; + + } else { + length = 1; + } + + if (length < records.length) { + records = Arrays.copyOfRange(records, length + 1, records.length); + } else { + records = null; + } + + } + + return attributeList; + + } + + private static void setAttributeValue(AttributeType attributeType, ASN1Object value) { + + if (value.isA(ASN.OCTET_STRING)) { + + try { + byte[] octets = ((OCTET_STRING) value).getWholeValue(); + attributeType.setLatin1String(new String(octets, Charset.forName("ISO-8859-1"))); + } catch (IOException e) { + log.info("Failed to set Latin1String.", e); + } + + } else if (value.isA(ASN.NumericString)) { + + attributeType.setNumericString((String) ((NumericString) value).getValue()); + + } else if (value.isA(ASN.GeneralizedTime)) { + + try { + ChoiceOfTime choiceOfTime = new ChoiceOfTime(value); + + GregorianCalendar gregorianCalendar = new GregorianCalendar(); + gregorianCalendar.setTimeZone(TimeZone.getTimeZone("UTC")); + gregorianCalendar.setTime(choiceOfTime.getDate()); + + DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); + XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar); + xmlGregorianCalendar.setTimezone(0); + + attributeType.setGeneralizedTime(xmlGregorianCalendar); + } catch (Exception e) { + log.info("Failed to set GeneralizedTime.", e); + } + + } else if (value.isA(ASN.INTEGER)) { + + attributeType.setInteger((BigInteger) value.getValue()); + + } else if (value.isA(ASN.UTF8String)) { + + attributeType.setUTF8String((String) value.getValue()); + + } else if (value.isA(ASN.PrintableString)) { + + attributeType.setPrintableString((String) value.getValue()); + + } else if (value.isA(ASN.UNKNOWN)) { + + byte[] bytes = (byte[]) ((UNKNOWN) value).getValue(); + + try { + BigInteger bigInteger = new BigInteger(bytes); + String string = bigInteger.toString(16); + + Date date = new SimpleDateFormat("yyyyMMdd").parse(string); + attributeType.setDate(new SimpleDateFormat("yyyy-MM-dd").format(date)); + } catch (Exception e) { + log.info("Failed to set Date.", e); + } + } + + } + + + + + +} -- cgit v1.2.3 From 54aa4703e3d66c5b1a63b8d925fd4c9c1766687c Mon Sep 17 00:00:00 2001 From: clemenso Date: Wed, 28 Jan 2009 19:40:11 +0000 Subject: activation git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@291 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/AbstractAssocArrayInfobox.java | 6 +- .../impl/CreateXMLSignatureResultImpl.java | 145 +++++++-------- .../slcommands/impl/InfoboxReadResultFileImpl.java | 197 +++++++++++---------- .../gv/egiz/bku/slcommands/impl/SLResultImpl.java | 6 +- 4 files changed, 182 insertions(+), 172 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java index e7f96c06..ce03dcf9 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java @@ -16,6 +16,7 @@ */ package at.gv.egiz.bku.slcommands.impl; +import at.gv.egiz.marshal.NamespacePrefixMapperImpl; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Collections; @@ -43,6 +44,8 @@ import at.gv.egiz.bku.slcommands.InfoboxReadResult; import at.gv.egiz.bku.slcommands.SLCommandContext; import at.gv.egiz.bku.slcommands.SLCommandFactory; import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.marshal.MarshallerFactory; +import javax.xml.bind.PropertyException; /** * An abstract base class for {@link Infobox} implementations of type associative array. @@ -257,8 +260,7 @@ public abstract class AbstractAssocArrayInfobox extends AbstractInfoboxImpl ByteArrayOutputStream result; try { - Marshaller marshaller = jaxbContext.createMarshaller(); - + Marshaller marshaller = MarshallerFactory.createMarshaller(jaxbContext); result = new ByteArrayOutputStream(); marshaller.marshal(jaxbElement, result); } catch (JAXBException e) { diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java index 4969c85a..b352a51e 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java @@ -14,8 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package at.gv.egiz.bku.slcommands.impl; - +package at.gv.egiz.bku.slcommands.impl; + +import at.gv.egiz.marshal.NamespacePrefixMapperImpl; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; @@ -34,76 +35,78 @@ import at.buergerkarte.namespaces.securitylayer._1.CreateXMLSignatureResponseTyp import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; import at.gv.egiz.bku.slcommands.SLCommandFactory; import at.gv.egiz.bku.slexceptions.SLRuntimeException; - -/** - * This calls implements the result of the security layer command CreateXMLSignature. - * - * @author mcentner - */ -public class CreateXMLSignatureResultImpl extends SLResultImpl { - - /** - * Logging facility. - */ - private static Log log = LogFactory.getLog(CreateXMLSignatureResultImpl.class); - - /** - * The document containing the XMLSignature. - */ - protected Document doc; - - /** - * Creates a new instance of this CreateXMLSignatureResultImpl with the given - * signature document. - * - * @param document the signature document - * - * @throws NullPointerException if document is null - */ - public CreateXMLSignatureResultImpl(Document document) { - super(); - - if (document == null) { - throw new NullPointerException("Argument 'document' must not be null."); - } - - this.doc = document; - - marshallCreateXMLSignatureResponse(); - } - - /** - * Marshalls the CreateXMLSignatureResponse. - */ - private void marshallCreateXMLSignatureResponse() { - - ObjectFactory factory = new ObjectFactory(); - - CreateXMLSignatureResponseType createCreateXMLSignatureResponseType = factory.createCreateXMLSignatureResponseType(); - JAXBElement createCreateXMLSignatureResponse = factory.createCreateXMLSignatureResponse(createCreateXMLSignatureResponseType); - - DocumentFragment fragment = doc.createDocumentFragment(); - - JAXBContext jaxbContext = SLCommandFactory.getInstance().getJaxbContext(); - try { - Marshaller marshaller = jaxbContext.createMarshaller(); - marshaller.marshal(createCreateXMLSignatureResponse, fragment); - } catch (JAXBException e) { - log.error("Failed to marshall 'CreateXMLSignatureResponse'", e); - throw new SLRuntimeException(e); - } - - Node child = fragment.getFirstChild(); - if (child instanceof Element) { - Node node = doc.replaceChild(child, doc.getDocumentElement()); - child.appendChild(node); - } - - } +import at.gv.egiz.marshal.MarshallerFactory; +import javax.xml.bind.PropertyException; + +/** + * This calls implements the result of the security layer command CreateXMLSignature. + * + * @author mcentner + */ +public class CreateXMLSignatureResultImpl extends SLResultImpl { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(CreateXMLSignatureResultImpl.class); + + /** + * The document containing the XMLSignature. + */ + protected Document doc; + + /** + * Creates a new instance of this CreateXMLSignatureResultImpl with the given + * signature document. + * + * @param document the signature document + * + * @throws NullPointerException if document is null + */ + public CreateXMLSignatureResultImpl(Document document) { + super(); + + if (document == null) { + throw new NullPointerException("Argument 'document' must not be null."); + } + + this.doc = document; + + marshallCreateXMLSignatureResponse(); + } + + /** + * Marshalls the CreateXMLSignatureResponse. + */ + private void marshallCreateXMLSignatureResponse() { + + ObjectFactory factory = new ObjectFactory(); + + CreateXMLSignatureResponseType createCreateXMLSignatureResponseType = factory.createCreateXMLSignatureResponseType(); + JAXBElement createCreateXMLSignatureResponse = factory.createCreateXMLSignatureResponse(createCreateXMLSignatureResponseType); + + DocumentFragment fragment = doc.createDocumentFragment(); + + JAXBContext jaxbContext = SLCommandFactory.getInstance().getJaxbContext(); + try { + Marshaller marshaller = MarshallerFactory.createMarshaller(jaxbContext); + marshaller.marshal(createCreateXMLSignatureResponse, fragment); + } catch (JAXBException e) { + log.error("Failed to marshall 'CreateXMLSignatureResponse'", e); + throw new SLRuntimeException(e); + } + + Node child = fragment.getFirstChild(); + if (child instanceof Element) { + Node node = doc.replaceChild(child, doc.getDocumentElement()); + child.appendChild(node); + } + + } @Override public void writeTo(Result result, Templates templates) { writeTo(doc, result, templates); - } - -} + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java index d8295227..75e44afa 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java @@ -14,8 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package at.gv.egiz.bku.slcommands.impl; - +package at.gv.egiz.bku.slcommands.impl; + +import at.gv.egiz.marshal.NamespacePrefixMapperImpl; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; @@ -40,86 +41,88 @@ import at.gv.egiz.bku.slcommands.InfoboxReadResult; import at.gv.egiz.bku.slcommands.SLCommand; import at.gv.egiz.bku.slcommands.SLCommandFactory; import at.gv.egiz.bku.slexceptions.SLRuntimeException; - -/** - * This class implements the result of the security layer command InfoboxReadRequest. - * - * @author mcentner - */ -public class InfoboxReadResultFileImpl extends SLResultImpl implements - InfoboxReadResult { - - /** - * Logging facility. - */ - protected static Log log = LogFactory.getLog(InfoboxReadResultFileImpl.class); - - /** - * The XML document containing the infobox content. - */ - protected Document xmlDocument; - - /** - * Creates the response document from the given binaryContent. - * - * @param binaryContent the infobox content - * @param preserveSpace the value of the preserveSpace parameter - * - * @return the created response document - */ - private Document createResponseDocument(byte[] binaryContent, boolean preserveSpace) { - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - Document doc; - try { - doc = dbf.newDocumentBuilder().newDocument(); - } catch (ParserConfigurationException e) { - // it should always be possible to create a new Document - log.error("Failed to create XML document.", e); - throw new SLRuntimeException(e); - } - - ObjectFactory factory = new ObjectFactory(); - - Base64XMLContentType base64XMLContentType = factory.createBase64XMLContentType(); - if (binaryContent == null) { - XMLContentType xmlContentType = factory.createXMLContentType(); - if (preserveSpace) { - xmlContentType.setSpace("preserve"); - } - base64XMLContentType.setXMLContent(xmlContentType); - } else { - base64XMLContentType.setBase64Content(binaryContent); - } - InfoboxReadResponseType infoboxReadResponseType = factory.createInfoboxReadResponseType(); - infoboxReadResponseType.setBinaryFileData(base64XMLContentType); - - JAXBElement infoboxReadResponse = factory.createInfoboxReadResponse(infoboxReadResponseType); - - JAXBContext context = SLCommandFactory.getInstance().getJaxbContext(); - try { - Marshaller marshaller = context.createMarshaller(); - marshaller.marshal(infoboxReadResponse, doc); - } catch (JAXBException e) { - log.error("Failed to marshal 'InfoboxReadResponse' document.", e); - throw new SLRuntimeException(e); - } - - return doc; - - } - - - /** - * @return an XMLResult for marshalling the infobox to - */ - public Result getXmlResult(boolean preserveSpace) { - - xmlDocument = createResponseDocument(null, preserveSpace); - - NodeList nodeList = xmlDocument.getElementsByTagNameNS(SLCommand.NAMESPACE_URI, "XMLContent"); - return new DOMResult(nodeList.item(0)); - +import at.gv.egiz.marshal.MarshallerFactory; +import javax.xml.bind.PropertyException; + +/** + * This class implements the result of the security layer command InfoboxReadRequest. + * + * @author mcentner + */ +public class InfoboxReadResultFileImpl extends SLResultImpl implements + InfoboxReadResult { + + /** + * Logging facility. + */ + protected static Log log = LogFactory.getLog(InfoboxReadResultFileImpl.class); + + /** + * The XML document containing the infobox content. + */ + protected Document xmlDocument; + + /** + * Creates the response document from the given binaryContent. + * + * @param binaryContent the infobox content + * @param preserveSpace the value of the preserveSpace parameter + * + * @return the created response document + */ + private Document createResponseDocument(byte[] binaryContent, boolean preserveSpace) { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + Document doc; + try { + doc = dbf.newDocumentBuilder().newDocument(); + } catch (ParserConfigurationException e) { + // it should always be possible to create a new Document + log.error("Failed to create XML document.", e); + throw new SLRuntimeException(e); + } + + ObjectFactory factory = new ObjectFactory(); + + Base64XMLContentType base64XMLContentType = factory.createBase64XMLContentType(); + if (binaryContent == null) { + XMLContentType xmlContentType = factory.createXMLContentType(); + if (preserveSpace) { + xmlContentType.setSpace("preserve"); + } + base64XMLContentType.setXMLContent(xmlContentType); + } else { + base64XMLContentType.setBase64Content(binaryContent); + } + InfoboxReadResponseType infoboxReadResponseType = factory.createInfoboxReadResponseType(); + infoboxReadResponseType.setBinaryFileData(base64XMLContentType); + + JAXBElement infoboxReadResponse = factory.createInfoboxReadResponse(infoboxReadResponseType); + + JAXBContext context = SLCommandFactory.getInstance().getJaxbContext(); + try { + Marshaller marshaller = MarshallerFactory.createMarshaller(context); + marshaller.marshal(infoboxReadResponse, doc); + } catch (JAXBException e) { + log.error("Failed to marshal 'InfoboxReadResponse' document.", e); + throw new SLRuntimeException(e); + } + + return doc; + + } + + + /** + * @return an XMLResult for marshalling the infobox to + */ + public Result getXmlResult(boolean preserveSpace) { + + xmlDocument = createResponseDocument(null, preserveSpace); + + NodeList nodeList = xmlDocument.getElementsByTagNameNS(SLCommand.NAMESPACE_URI, "XMLContent"); + return new DOMResult(nodeList.item(0)); + } /** @@ -142,21 +145,21 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements } - /** - * Creates a new result document for this InfoboxReadResult - * and sets the given resultBytes as content. - * - * @param resultBytes - */ - public void setResultBytes(byte[] resultBytes) { - - xmlDocument = createResponseDocument(resultBytes, false); - - } - + /** + * Creates a new result document for this InfoboxReadResult + * and sets the given resultBytes as content. + * + * @param resultBytes + */ + public void setResultBytes(byte[] resultBytes) { + + xmlDocument = createResponseDocument(resultBytes, false); + + } + @Override public void writeTo(Result result, Templates templates) { writeTo(xmlDocument, result, templates); - } - -} + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java index 99a3b119..0452bddf 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java @@ -41,6 +41,7 @@ import org.w3c.dom.Node; import at.buergerkarte.namespaces.securitylayer._1.ErrorResponseType; import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.gv.egiz.marshal.NamespacePrefixMapperImpl; import at.gv.egiz.bku.slcommands.SLCommandFactory; import at.gv.egiz.bku.slcommands.SLResult; import at.gv.egiz.bku.slexceptions.SLBindingException; @@ -49,6 +50,8 @@ import at.gv.egiz.bku.slexceptions.SLException; import at.gv.egiz.bku.slexceptions.SLRuntimeException; import at.gv.egiz.bku.utils.DebugOutputStream; import at.gv.egiz.bku.utils.DebugWriter; +import at.gv.egiz.marshal.MarshallerFactory; +import javax.xml.bind.PropertyException; /** * This class serves as an abstract base class for the implementation of a @@ -90,8 +93,7 @@ public abstract class SLResultImpl implements SLResult { private Marshaller getMarshaller() { try { JAXBContext context = SLCommandFactory.getInstance().getJaxbContext(); - Marshaller marshaller = context.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + Marshaller marshaller = MarshallerFactory.createMarshaller(context, true); return marshaller; } catch (JAXBException e) { log.fatal("Failed to marshall error response.", e); -- cgit v1.2.3 From 90f7f3ea1674e7cd5ead84247ca881ca101ba72a Mon Sep 17 00:00:00 2001 From: clemenso Date: Wed, 11 Feb 2009 20:03:29 +0000 Subject: div. changes for A-Trust Activation Support (User-Agent header, GetStatusRequest, ...) git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@296 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/CardChannelInfoboxImpl.java | 2 +- .../bku/slcommands/impl/GetStatusCommandImpl.java | 79 ++++++++++++++++++++++ .../bku/slcommands/impl/GetStatusResultImpl.java | 52 ++++++++++++++ 3 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusCommandImpl.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusResultImpl.java (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CardChannelInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CardChannelInfoboxImpl.java index 4b1cc779..19b84ac7 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CardChannelInfoboxImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CardChannelInfoboxImpl.java @@ -118,7 +118,7 @@ public class CardChannelInfoboxImpl extends AbstractBinaryFileInfobox { ByteArrayOutputStream redirectedStream = ((at.gv.egiz.slbinding.impl.XMLContentType) content).getRedirectedStream(); if (redirectedStream != null) { - + if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusCommandImpl.java new file mode 100644 index 00000000..46bfe18b --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusCommandImpl.java @@ -0,0 +1,79 @@ +/* + * Copyright 2008 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package at.gv.egiz.bku.slcommands.impl; + +import at.buergerkarte.namespaces.securitylayer._1.GetStatusRequestType; +import at.gv.egiz.bku.slcommands.GetStatusCommand; +import at.gv.egiz.bku.slcommands.SLCommandContext; +import at.gv.egiz.bku.slcommands.SLResult; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLException; +import at.gv.egiz.stal.ErrorResponse; +import at.gv.egiz.stal.STAL; +import at.gv.egiz.stal.STALResponse; +import at.gv.egiz.stal.StatusRequest; +import at.gv.egiz.stal.StatusResponse; +import java.util.Collections; +import java.util.List; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * + * @author Clemens Orthacker + */ +public class GetStatusCommandImpl extends SLCommandImpl implements GetStatusCommand { + + protected static Log log = LogFactory.getLog(GetStatusCommandImpl.class); + + @Override + public String getName() { + return "GetStatusRequest"; + } + + @Override + public SLResult execute() { + + //ignore maxDelay and TokenStatus +// GetStatusRequestType req = getRequestValue(); + + log.debug("execute GetStatusRequest"); + + StatusRequest stalRequest = new StatusRequest(); + + STAL stal = cmdCtx.getSTAL(); + + List responses = stal.handleRequest(Collections.singletonList(stalRequest)); + + if (responses != null && responses.size() == 1) { + STALResponse stalResponse = responses.get(0); + if (stalResponse instanceof StatusResponse) { + boolean ready = ((StatusResponse) stalResponse).isCardReady(); + log.trace("received status response cardReady: " + ready); + return new GetStatusResultImpl(ready); + } else if (stalResponse instanceof ErrorResponse) { + log.debug("received error response"); + SLCommandException ex = new SLCommandException(((ErrorResponse) stalResponse).getErrorCode()); + return new ErrorResultImpl(ex, cmdCtx.getLocale()); + } + } + log.error("received unexpected responses"); + return new ErrorResultImpl(new SLCommandException(4000), cmdCtx.getLocale()); + + } +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusResultImpl.java new file mode 100644 index 00000000..fddd3b0b --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusResultImpl.java @@ -0,0 +1,52 @@ +/* + * Copyright 2008 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package at.gv.egiz.bku.slcommands.impl; + +import at.buergerkarte.namespaces.securitylayer._1.GetStatusResponseType; +import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; +import at.buergerkarte.namespaces.securitylayer._1.TokenStatusType; +import at.gv.egiz.bku.slcommands.GetStatusResult; +import javax.xml.bind.JAXBElement; +import javax.xml.transform.Result; +import javax.xml.transform.Templates; + +/** + * + * @author Clemens Orthacker + */ +public class GetStatusResultImpl extends SLResultImpl implements GetStatusResult { + + protected ObjectFactory of; + protected GetStatusResponseType responseType; + + public GetStatusResultImpl(boolean ready) { + of = new ObjectFactory(); + responseType = of.createGetStatusResponseType(); + if (ready) { + responseType.setTokenStatus(TokenStatusType.READY); + } else { + responseType.setTokenStatus(TokenStatusType.REMOVED); + } + + } + + @Override + public void writeTo(Result result, Templates templates) { + JAXBElement response = of.createGetStatusResponse(responseType); + writeTo(response, result, templates); + } +} -- cgit v1.2.3 From 6576428966f1e3d688269a407b072fb01f9f7647 Mon Sep 17 00:00:00 2001 From: clemenso Date: Thu, 26 Feb 2009 19:39:00 +0000 Subject: 1.1 candidate (activation) git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@309 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../egiz/bku/slcommands/impl/xsect/DataObject.java | 2078 ++++++++++---------- .../egiz/bku/slcommands/impl/xsect/Signature.java | 5 +- 2 files changed, 1095 insertions(+), 988 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java index ae4918ce..b64306aa 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java @@ -14,98 +14,105 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package at.gv.egiz.bku.slcommands.impl.xsect; - -import iaik.xml.crypto.dom.DOMCryptoContext; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.SequenceInputStream; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; +package at.gv.egiz.bku.slcommands.impl.xsect; + +import iaik.xml.crypto.dom.DOMCryptoContext; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.SequenceInputStream; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.net.URISyntaxException; +import java.nio.charset.Charset; +import java.security.InvalidAlgorithmParameterException; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.dom.DOMStructure; -import javax.xml.crypto.dsig.CanonicalizationMethod; -import javax.xml.crypto.dsig.DigestMethod; -import javax.xml.crypto.dsig.Reference; -import javax.xml.crypto.dsig.Transform; -import javax.xml.crypto.dsig.XMLObject; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; -import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec; -import javax.xml.crypto.dsig.spec.XPathType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.DOMConfiguration; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.Text; -import org.w3c.dom.bootstrap.DOMImplementationRegistry; -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSException; -import org.w3c.dom.ls.LSInput; -import org.w3c.dom.ls.LSOutput; -import org.w3c.dom.ls.LSParser; -import org.w3c.dom.ls.LSSerializer; - -import at.buergerkarte.namespaces.securitylayer._1.Base64XMLLocRefOptRefContentType; -import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; -import at.buergerkarte.namespaces.securitylayer._1.MetaInfoType; -import at.buergerkarte.namespaces.securitylayer._1.TransformsInfoType; -import at.gv.egiz.bku.binding.HttpUtil; -import at.gv.egiz.bku.slexceptions.SLCommandException; -import at.gv.egiz.bku.slexceptions.SLRequestException; -import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.dom.DOMStructure; +import javax.xml.crypto.dsig.CanonicalizationMethod; +import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.dsig.Reference; +import javax.xml.crypto.dsig.Transform; +import javax.xml.crypto.dsig.XMLObject; +import javax.xml.crypto.dsig.spec.TransformParameterSpec; +import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec; +import javax.xml.crypto.dsig.spec.XPathType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3._2000._09.xmldsig_.TransformType; +import org.w3._2000._09.xmldsig_.TransformsType; +import org.w3c.dom.DOMConfiguration; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.Text; +import org.w3c.dom.bootstrap.DOMImplementationRegistry; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSException; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSParser; +import org.w3c.dom.ls.LSSerializer; + +import at.buergerkarte.namespaces.securitylayer._1.Base64XMLLocRefOptRefContentType; +import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; +import at.buergerkarte.namespaces.securitylayer._1.MetaInfoType; +import at.buergerkarte.namespaces.securitylayer._1.TransformsInfoType; +import at.gv.egiz.bku.binding.HttpUtil; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.bku.slexceptions.SLRequestException; +import at.gv.egiz.bku.slexceptions.SLRuntimeException; import at.gv.egiz.bku.slexceptions.SLViewerException; -import at.gv.egiz.bku.utils.urldereferencer.StreamData; -import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; +import at.gv.egiz.bku.utils.urldereferencer.StreamData; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; import at.gv.egiz.bku.viewer.ValidationException; import at.gv.egiz.bku.viewer.Validator; import at.gv.egiz.bku.viewer.ValidatorFactory; -import at.gv.egiz.dom.DOMUtils; -import at.gv.egiz.slbinding.impl.XMLContentType; - -/** - * This class represents a DataObject of an XML-Signature - * created by the security layer command CreateXMLSignature. - * - * @author mcentner - */ -public class DataObject { - - /** - * Logging facility. - */ - private static Log log = LogFactory.getLog(DataObject.class); - - /** - * DOM Implementation. - */ - private static final String DOM_LS_3_0 = "LS 3.0"; - - /** - * The array of the default preferred MIME type order. - */ - private static final String[] DEFAULT_PREFFERED_MIME_TYPES = - new String[] { +import at.gv.egiz.dom.DOMUtils; +import at.gv.egiz.marshal.NamespacePrefix; +import at.gv.egiz.marshal.NamespacePrefixMapperImpl; +import at.gv.egiz.slbinding.impl.XMLContentType; +import javax.xml.namespace.NamespaceContext; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +/** + * This class represents a DataObject of an XML-Signature + * created by the security layer command CreateXMLSignature. + * + * @author mcentner + */ +public class DataObject { + + /** + * Logging facility. + */ + private static Log log = LogFactory.getLog(DataObject.class); + + /** + * DOM Implementation. + */ + private static final String DOM_LS_3_0 = "LS 3.0"; + + /** + * The array of the default preferred MIME type order. + */ + private static final String[] DEFAULT_PREFFERED_MIME_TYPES = + new String[] { "text/plain", - "application/xhtml+xml" + "application/xhtml+xml" }; /** @@ -149,87 +156,87 @@ public class DataObject { validMimeTypes = mediaTypes; } - /** - * The DOM implementation used. - */ - private DOMImplementationLS domImplLS; - - /** - * The signature context. - */ - private SignatureContext ctx; - - /** - * The Reference for this DataObject. - */ - private XSECTReference reference; - - /** - * The XMLObject for this DataObject. - */ - private XMLObject xmlObject; - - /** - * The MIME-Type of the digest input. - */ - private String mimeType; - - /** - * An optional description of the digest input. - */ - private String description; - - /** - * Creates a new instance. - * - * @param document the document of the target signature - */ - public DataObject(SignatureContext signatureContext) { - this.ctx = signatureContext; - - DOMImplementationRegistry registry; - try { - registry = DOMImplementationRegistry.newInstance(); - } catch (Exception e) { - log.error("Failed to get DOMImplementationRegistry.", e); - throw new SLRuntimeException("Failed to get DOMImplementationRegistry."); - } - - domImplLS = (DOMImplementationLS) registry.getDOMImplementation(DOM_LS_3_0); - if (domImplLS == null) { - log.error("Failed to get DOMImplementation " + DOM_LS_3_0); - throw new SLRuntimeException("Failed to get DOMImplementation " + DOM_LS_3_0); - } - - } - - /** - * @return the reference - */ - public Reference getReference() { - return reference; - } - - /** - * @return the xmlObject - */ - public XMLObject getXmlObject() { - return xmlObject; - } - - /** - * @return the mimeType - */ - public String getMimeType() { - return mimeType; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } + /** + * The DOM implementation used. + */ + private DOMImplementationLS domImplLS; + + /** + * The signature context. + */ + private SignatureContext ctx; + + /** + * The Reference for this DataObject. + */ + private XSECTReference reference; + + /** + * The XMLObject for this DataObject. + */ + private XMLObject xmlObject; + + /** + * The MIME-Type of the digest input. + */ + private String mimeType; + + /** + * An optional description of the digest input. + */ + private String description; + + /** + * Creates a new instance. + * + * @param document the document of the target signature + */ + public DataObject(SignatureContext signatureContext) { + this.ctx = signatureContext; + + DOMImplementationRegistry registry; + try { + registry = DOMImplementationRegistry.newInstance(); + } catch (Exception e) { + log.error("Failed to get DOMImplementationRegistry.", e); + throw new SLRuntimeException("Failed to get DOMImplementationRegistry."); + } + + domImplLS = (DOMImplementationLS) registry.getDOMImplementation(DOM_LS_3_0); + if (domImplLS == null) { + log.error("Failed to get DOMImplementation " + DOM_LS_3_0); + throw new SLRuntimeException("Failed to get DOMImplementation " + DOM_LS_3_0); + } + + } + + /** + * @return the reference + */ + public Reference getReference() { + return reference; + } + + /** + * @return the xmlObject + */ + public XMLObject getXmlObject() { + return xmlObject; + } + + /** + * @return the mimeType + */ + public String getMimeType() { + return mimeType; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } public void validateHashDataInput() throws SLViewerException { @@ -293,823 +300,920 @@ public class DataObject { } } - - /** - * Configures this DataObject with the information provided within the given - * sl:DataObjectInfo. - * - * @param dataObjectInfo - * the sl:DataObjectInfo - * - * @throws SLCommandException - * if configuring this DataObject with the information provided in - * the sl:DataObjectInfo fails. - * @throws SLRequestException - * if the information provided in the sl:DataObjectInfo - * does not conform to the security layer specification. - * @throws NullPointerException - * if dataObjectInfo is null - */ - public void setDataObjectInfo(DataObjectInfoType dataObjectInfo) throws SLCommandException, SLRequestException { - - Base64XMLLocRefOptRefContentType dataObject = dataObjectInfo.getDataObject(); - String structure = dataObjectInfo.getStructure(); - - // select and unmarshal an appropriate transformation path if provided - // and set the final data meta information - XSECTTransforms transforms = createTransformsAndSetFinalDataMetaInfo(dataObjectInfo.getTransformsInfo()); - - if ("enveloping".equals(structure)) { - - // configure this DataObject as an enveloped DataObject - setEnvelopedDataObject(dataObject, transforms); - - } else if ("detached".equals(structure)) { - - // configure this DataObject as an detached DataObject - setDetachedDataObject(dataObject, transforms); - - } - // other values are not allowed by the schema and are therefore ignored - - } - - /** - * Configures this DataObject as an enveloped DataObject with the information - * provided within the given sl:DataObject. - * - * @param dataObject - * the sl:DataObject - * @param transforms - * an optional Transforms element (may be - * null) - * - * @throws SLCommandException - * if configuring this DataObject with the information provided in - * the sl:DataObject fails. - * @throws SLRequestException - * if the information provided in the sl:DataObject - * does not conform to the security layer specification. - * @throws NullPointerException - * if dataObject is null - */ - private void setEnvelopedDataObject( - Base64XMLLocRefOptRefContentType dataObject, XSECTTransforms transforms) - throws SLCommandException, SLRequestException { - - String reference = dataObject.getReference(); - if (reference == null) { - // - // case A - // - // The Reference attribute is not used; the content of sl:DataObject represents the data object. - // If the data object is XML-coded (the sl:XMLContent element is used in sl:DataObject), then it - // must be incorporated in the signature structure as parsed XML. - // - - if (dataObject.getBase64Content() != null) { - - log.debug("Adding DataObject (Base64Content) without a reference URI."); - - // create XMLObject - XMLObject xmlObject = createXMLObject(new ByteArrayInputStream(dataObject.getBase64Content())); - - setXMLObjectAndReferenceBase64(xmlObject, transforms); - - } else if (dataObject.getXMLContent() != null) { - - log.debug("Adding DataObject (XMLContent) without a reference URI."); - - // create XMLObject - DocumentFragment content = parseDataObject((XMLContentType) dataObject.getXMLContent()); - XMLObject xmlObject = createXMLObject(content); - - setXMLObjectAndReferenceXML(xmlObject, transforms); - - } else if (dataObject.getLocRefContent() != null) { - - log.debug("Adding DataObject (LocRefContent) without a reference URI."); - - setEnvelopedDataObject(dataObject.getLocRefContent(), transforms); - - } else { - - // not allowed - log.info("XML structure of the command request contains an " + - "invalid combination of optional elements or attributes. " + - "DataObject of structure='enveloped' without a reference must contain content."); - throw new SLRequestException(3003); - - } - - } else { - - if (dataObject.getBase64Content() == null && - dataObject.getXMLContent() == null && - dataObject.getLocRefContent() == null) { - - // - // case B - // - // The Reference attribute contains a URI that must be resolved by the - // Citizen Card Environment to obtain the data object. - // The content of sl:DataObject remains empty - // - - log.debug("Adding DataObject from reference URI '" + reference + "'."); - - setEnvelopedDataObject(reference, transforms); - - } else { - - // not allowed - log.info("XML structure of the command request contains an " + - "invalid combination of optional elements or attributes. " + - "DataObject of structure='enveloped' with reference must not contain content."); - throw new SLRequestException(3003); - - } - - - } - - } - - /** - * Configures this DataObject as an enveloped DataObject with the content to - * be dereferenced from the given reference. - * - * @param reference - * the reference URI - * @param transforms - * an optional Transforms element (may be - * null) - * - * @throws SLCommandException - * if dereferencing the given reference fails, or if - * configuring this DataObject with the data dereferenced from the - * given reference fails. - * @throws NullPointerException - * if reference is null - */ - private void setEnvelopedDataObject(String reference, XSECTTransforms transforms) throws SLCommandException { - - if (reference == null) { - throw new NullPointerException("Argument 'reference' must not be null."); - } - - // dereference URL - URLDereferencer dereferencer = URLDereferencer.getInstance(); - - StreamData streamData; - try { - streamData = dereferencer.dereference(reference, ctx.getDereferencerContext()); - } catch (IOException e) { - log.info("Failed to dereference XMLObject from '" + reference + "'.", e); - throw new SLCommandException(4110); - } - - Node childNode; - - String contentType = streamData.getContentType(); - if (contentType.startsWith("text/xml")) { - - // If content type is text/xml parse content. - String charset = HttpUtil.getCharset(contentType, true); - - Document doc = parseDataObject(streamData.getStream(), charset); - - childNode = doc.getDocumentElement(); - - if (childNode == null) { - log.info("Failed to parse XMLObject from '" + reference + "'."); - throw new SLCommandException(4111); - } - - XMLObject xmlObject = createXMLObject(childNode); - - setXMLObjectAndReferenceXML(xmlObject, transforms); - - } else { - - // Include content Base64 encoded. - XMLObject xmlObject = createXMLObject(streamData.getStream()); - - setXMLObjectAndReferenceBase64(xmlObject, transforms); - - } - - } - - /** - * Configures this DataObject as an detached DataObject with the information - * provided in the given sl:DataObject and optionally - * transforms. - * - * @param dataObject - * the sl:DataObject - * @param transforms - * an optional Transforms object, may be null - * - * @throws SLCommandException - * if configuring this DataObject with the information provided in - * the sl:DataObject fails. - * @throws SLRequestException - * if the information provided in the sl:DataObject - * does not conform to the security layer specification. - * @throws NullPointerException - * if dataObject is null - */ - private void setDetachedDataObject( - Base64XMLLocRefOptRefContentType dataObject, XSECTTransforms transforms) - throws SLCommandException, SLRequestException { - - String referenceURI = dataObject.getReference(); - - if (referenceURI == null) { - - // not allowed - log.info("XML structure of the command request contains an " + - "invalid combination of optional elements or attributes. " + - "DataObject of structure='detached' must contain a reference."); - throw new SLRequestException(3003); - - } else { - - DigestMethod dm; - try { - dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); - } catch (NoSuchAlgorithmException e) { - log.error("Failed to get DigestMethod.", e); - throw new SLCommandException(4006); - } catch (InvalidAlgorithmParameterException e) { - log.error("Failed to get DigestMethod.", e); - throw new SLCommandException(4006); - } - - String idValue = ctx.getIdValueFactory().createIdValue("Reference"); - - reference = new XSECTReference(referenceURI, dm, transforms, null, idValue); - - // case D: - // - // The Reference attribute contains a URI that is used by the Citizen Card - // Environment to code the reference to the data object as part of the XML - // signature (attribute URI in the dsig:Reference) element. The content of - // sl:DataObject represents the data object. - - if (dataObject.getLocRefContent() != null) { - String locRef = dataObject.getLocRefContent(); - try { - this.reference.setDereferencer(new LocRefDereferencer(ctx.getDereferencerContext(), locRef)); - } catch (URISyntaxException e) { - log.info("Invalid URI '" + locRef + "' in DataObject.", e); - throw new SLCommandException(4003); - } catch (IllegalArgumentException e) { - log.info("LocRef URI of '" + locRef + "' not supported in DataObject. ", e); - throw new SLCommandException(4003); - } - } else if (dataObject.getBase64Content() != null) { - byte[] base64Content = dataObject.getBase64Content(); - this.reference.setDereferencer(new ByteArrayDereferencer(base64Content)); - } else if (dataObject.getXMLContent() != null) { - XMLContentType xmlContent = (XMLContentType) dataObject.getXMLContent(); - byte[] bytes = xmlContent.getRedirectedStream().toByteArray(); - this.reference.setDereferencer(new ByteArrayDereferencer(bytes)); - } else { - - // case C: - // - // The Reference attribute contains a URI that must be resolved by the - // Citizen Card Environment to obtain the data object. The Reference - // attribute contains a URI that is used by the Citizen Card Environment - // to code the reference to the data object as part of the XML signature - // (attribute URI in the dsig:Reference) element. The content of - // sl:DataObject remains empty. - - } - - } - } - - /** - * Returns the preferred sl:TransformInfo from the given list of - * transformInfos, or null if none of the given - * transformInfos is preferred over the others. - * - * @param transformsInfos - * a list of sl:TransformInfos - * - * @return the selected sl:TransformInfo or null, if - * none is preferred over the others - */ - private TransformsInfoType selectPreferredTransformsInfo(List transformsInfos) { - - Map mimeTypes = new HashMap(); - - StringBuilder debugString = null; - if (log.isDebugEnabled()) { - debugString = new StringBuilder(); - debugString.append("Got " + transformsInfos.size() + " TransformsInfo(s):"); - } - - for (TransformsInfoType transformsInfoType : transformsInfos) { - MetaInfoType finalDataMetaInfo = transformsInfoType.getFinalDataMetaInfo(); - String mimeType = finalDataMetaInfo.getMimeType(); - String description = finalDataMetaInfo.getDescription(); - mimeTypes.put(mimeType, transformsInfoType); - if (debugString != null) { - debugString.append("\n FinalDataMetaInfo: MIME-Type="); - debugString.append(mimeType); - if (description != null) { - debugString.append(" "); - debugString.append(description); - } - } - } - - if (debugString != null) { - log.debug(debugString); - } - - // look for preferred transform - for (String mimeType : DEFAULT_PREFFERED_MIME_TYPES) { - if (mimeTypes.containsKey(mimeType)) { - return mimeTypes.get(mimeType); - } - } - - // no preferred transform - return null; - - } - - /** - * Create an instance of ds:Transforms from the given - * sl:TransformsInfo. - * - * @param transformsInfo - * the sl:TransformsInfo - * - * @return a corresponding unmarshalled ds:Transforms, or - * null if the given sl:TransformsInfo does - * not contain a dsig:Transforms element - * - * @throws SLRequestException - * if the ds:Transforms in the given - * transformsInfo are not valid or cannot be parsed. - * - * @throws MarshalException - * if the ds:Transforms in the given - * transformsInfo cannot be unmarshalled. - */ - private XSECTTransforms createTransforms(TransformsInfoType transformsInfo) throws SLRequestException, MarshalException { - - ByteArrayOutputStream redirectedStream = ((at.gv.egiz.slbinding.impl.TransformsInfoType) transformsInfo).getRedirectedStream(); - byte[] transformBytes = (redirectedStream != null) ? redirectedStream.toByteArray() : null; - - if (transformBytes != null && transformBytes.length > 0) { - - // debug - if (log.isTraceEnabled()) { - StringBuilder sb = new StringBuilder(); - sb.append("Trying to parse transforms:\n"); - sb.append(new String(transformBytes, Charset.forName("UTF-8"))); - log.trace(sb); - } - - DOMImplementationLS domImplLS = DOMUtils.getDOMImplementationLS(); - LSInput input = domImplLS.createLSInput(); - input.setByteStream(new ByteArrayInputStream(transformBytes)); - - LSParser parser = domImplLS.createLSParser( - DOMImplementationLS.MODE_SYNCHRONOUS, null); - DOMConfiguration domConfig = parser.getDomConfig(); - SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); - domConfig.setParameter("error-handler", errorHandler); - domConfig.setParameter("validate", Boolean.FALSE); - - Document document; - try { - document = parser.parse(input); - } catch (DOMException e) { - log.info("Failed to parse dsig:Transforms.", e); - throw new SLRequestException(3002); - } catch (LSException e) { - log.info("Failed to parse dsig:Transforms.", e); - throw new SLRequestException(3002); - } - - // adopt ds:Transforms - Element documentElement = document.getDocumentElement(); - Node adoptedTransforms = ctx.getDocument().adoptNode(documentElement); - - DOMCryptoContext context = new DOMCryptoContext(); - - // unmarshall ds:Transforms - return new XSECTTransforms(context, adoptedTransforms); - - } else { - return null; - } - - } - - /** - * Sets the mimeType and the description value - * for this DataObject. - * - * @param metaInfoType the sl:FinalMetaDataInfo - * - * @throws NullPointerException if metaInfoType is null - */ - private void setFinalDataMetaInfo(MetaInfoType metaInfoType) { - - this.mimeType = metaInfoType.getMimeType(); - this.description = metaInfoType.getDescription(); - - } - - /** - * Selects an appropriate transformation path (if present) from the given list - * of sl:TransformInfos, sets the corresponding final data meta info and - * returns the corresponding unmarshalled ds:Transforms. - * - * @param transformsInfos the sl:TransformInfos - * - * @return the unmarshalled ds:Transforms, or null if - * no transformation path has been selected. - * - * @throws SLRequestException if the given list ds:TransformsInfo contains - * an invalid ds:Transforms element, or no suitable transformation path - * can be found. - */ - private XSECTTransforms createTransformsAndSetFinalDataMetaInfo( - List transformsInfos) throws SLRequestException { - - TransformsInfoType preferredTransformsInfo = selectPreferredTransformsInfo(transformsInfos); - // try preferred transform - if (preferredTransformsInfo != null) { - - try { - XSECTTransforms transforms = createTransforms(preferredTransformsInfo); - setFinalDataMetaInfo(preferredTransformsInfo.getFinalDataMetaInfo()); - return transforms; - } catch (MarshalException e) { - - String mimeType = preferredTransformsInfo.getFinalDataMetaInfo().getMimeType(); - log.info("Failed to unmarshal preferred transformation path (MIME-Type=" - + mimeType + ").", e); - - } - - } - - // look for another suitable transformation path - for (TransformsInfoType transformsInfoType : transformsInfos) { - - try { - XSECTTransforms transforms = createTransforms(transformsInfoType); - setFinalDataMetaInfo(transformsInfoType.getFinalDataMetaInfo()); - return transforms; - } catch (MarshalException e) { - - String mimeType = transformsInfoType.getFinalDataMetaInfo().getMimeType(); - log.info("Failed to unmarshal transformation path (MIME-Type=" - + mimeType + ").", e); - } - - } - - // no suitable transformation path found - throw new SLRequestException(3003); - - } - - /** - * Create an XMLObject with the Base64 encoding of the given - * content. - * - * @param content - * the to-be Base64 encoded content - * @return an XMLObject with the Base64 encoded content - */ - private XMLObject createXMLObject(InputStream content) { - - Text textNode; - try { - textNode = at.gv.egiz.dom.DOMUtils.createBase64Text(content, ctx.getDocument()); - } catch (IOException e) { - log.error(e); - throw new SLRuntimeException(e); - } - - DOMStructure structure = new DOMStructure(textNode); - - String idValue = ctx.getIdValueFactory().createIdValue("Object"); - - return ctx.getSignatureFactory().newXMLObject(Collections.singletonList(structure), idValue, null, null); - - } - - /** - * Create an XMLObject with the given content node. - * - * @param content the content node - * - * @return an XMLObject with the given content - */ - private XMLObject createXMLObject(Node content) { - - String idValue = ctx.getIdValueFactory().createIdValue("Object"); - - List structures = Collections.singletonList(new DOMStructure(content)); - - return ctx.getSignatureFactory().newXMLObject(structures, idValue, null, null); - - } - - /** - * Sets the given xmlObject and creates and sets a corresponding - * Reference. - *

- * A transform to Base64-decode the xmlObject's content is inserted at the top - * of to the optional transforms if given, or to a newly created - * Transforms element if transforms is - * null. - * - * @param xmlObject - * the XMLObject - * @param transforms - * an optional Transforms element (may be - * null) - * - * @throws SLCommandException - * if creating the Reference fails - * @throws NullPointerException - * if xmlObject is null - */ - private void setXMLObjectAndReferenceBase64(XMLObject xmlObject, XSECTTransforms transforms) throws SLCommandException { - - // create reference URI - // - // NOTE: the ds:Object can be referenced directly, as the Base64 transform - // operates on the text() of the input nodelist. - // - String referenceURI = "#" + xmlObject.getId(); - - // create Base64 Transform - Transform transform; - try { - transform = ctx.getSignatureFactory().newTransform(Transform.BASE64, (TransformParameterSpec) null); - } catch (NoSuchAlgorithmException e) { - // algorithm must be present - throw new SLRuntimeException(e); - } catch (InvalidAlgorithmParameterException e) { - // algorithm does not take parameters - throw new SLRuntimeException(e); - } - - if (transforms == null) { - transforms = new XSECTTransforms(Collections.singletonList(transform)); - } else { - transforms.insertTransform(transform); - } - - DigestMethod dm; - try { - dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); - } catch (NoSuchAlgorithmException e) { - log.error("Failed to get DigestMethod.", e); - throw new SLCommandException(4006); - } catch (InvalidAlgorithmParameterException e) { - log.error("Failed to get DigestMethod.", e); - throw new SLCommandException(4006); - } - String id = ctx.getIdValueFactory().createIdValue("Reference"); - - this.xmlObject = xmlObject; - this.reference = new XSECTReference(referenceURI, dm, transforms, null, id); - - } - - /** - * Sets the given xmlObject and creates and sets a corresponding - * Reference. - *

- * A transform to select the xmlObject's content is inserted at the top of to - * the optional transforms if given, or to a newly created - * Transforms element if transforms is - * null. - *

- * - * @param xmlObject - * the XMLObject - * @param transforms - * an optional Transforms element (may be - * null) - * - * @throws SLCommandException - * if creating the Reference fails - * @throws NullPointerException - * if xmlObject is null - */ - private void setXMLObjectAndReferenceXML(XMLObject xmlObject, XSECTTransforms transforms) throws SLCommandException { - - // create reference URI - String referenceURI = "#" + xmlObject.getId(); - - // create Transform to select ds:Object's children - Transform xpathTransform; - Transform c14nTransform; - try { - - XPathType xpath = new XPathType("id(\"" + xmlObject.getId() + "\")/node()", XPathType.Filter.INTERSECT); - List xpaths = Collections.singletonList(xpath); - XPathFilter2ParameterSpec params = new XPathFilter2ParameterSpec(xpaths); - - xpathTransform = ctx.getSignatureFactory().newTransform(Transform.XPATH2, params); - - // add exclusive canonicalization to avoid signing the namespace context of the ds:Object - c14nTransform = ctx.getSignatureFactory().newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); - - } catch (NoSuchAlgorithmException e) { - // algorithm must be present - throw new SLRuntimeException(e); - } catch (InvalidAlgorithmParameterException e) { - // params must be appropriate - throw new SLRuntimeException(e); - } - - if (transforms == null) { - List newTransfroms = new ArrayList(); - newTransfroms.add(xpathTransform); - newTransfroms.add(c14nTransform); - transforms = new XSECTTransforms(newTransfroms); - } else { - transforms.insertTransform(xpathTransform); - } - - DigestMethod dm; - try { - dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); - } catch (NoSuchAlgorithmException e) { - log.error("Failed to get DigestMethod.", e); - throw new SLCommandException(4006); - } catch (InvalidAlgorithmParameterException e) { - log.error("Failed to get DigestMethod.", e); - throw new SLCommandException(4006); - } - String id = ctx.getIdValueFactory().createIdValue("Reference"); - - this.xmlObject = xmlObject; - this.reference = new XSECTReference(referenceURI, dm, transforms, null, id); - - } - - /** - * Parses the given xmlContent and returns a corresponding - * document fragment. - * - *

- * The to-be parsed content is surrounded by ... elements to - * allow for mixed (e.g. Text and Element) content in XMLContent. - *

- * - * @param xmlContent - * the XMLContent to-be parsed - * - * @return a document fragment containing the parsed nodes - * - * @throws SLCommandException - * if parsing the given xmlContent fails - * - * @throws NullPointerException - * if xmlContent is null - */ - private DocumentFragment parseDataObject(XMLContentType xmlContent) throws SLCommandException { - - ByteArrayOutputStream redirectedStream = xmlContent.getRedirectedStream(); - - // Note: We can assume a fixed character encoding of UTF-8 for the - // content of the redirect stream as the content has already been parsed - // and serialized again to the redirect stream. - - List inputStreams = new ArrayList(); - try { - // dummy start element - inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); - - // content - inputStreams.add(new ByteArrayInputStream(redirectedStream.toByteArray())); - - // dummy end element - inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - throw new SLRuntimeException(e); - } - - SequenceInputStream inputStream = new SequenceInputStream(Collections.enumeration(inputStreams)); - - // parse DataObject - Document doc = parseDataObject(inputStream, "UTF-8"); - - Element documentElement = doc.getDocumentElement(); - - if (documentElement == null || - !"dummy".equals(documentElement.getLocalName())) { - log.info("Failed to parse DataObject XMLContent."); - throw new SLCommandException(4111); - } - - DocumentFragment fragment = doc.createDocumentFragment(); - while (documentElement.getFirstChild() != null) { - fragment.appendChild(documentElement.getFirstChild()); - } - - // log parsed document - if (log.isTraceEnabled()) { - - StringWriter writer = new StringWriter(); - - writer.write("DataObject:\n"); - - LSOutput output = domImplLS.createLSOutput(); - output.setCharacterStream(writer); - output.setEncoding("UTF-8"); - LSSerializer serializer = domImplLS.createLSSerializer(); - serializer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE); - serializer.write(fragment, output); - - log.trace(writer.toString()); - } - - return fragment; - - } - - /** - * Parses the given inputStream using the given - * encoding and returns the parsed document. - * - * @param inputStream - * the to-be parsed input - * - * @param encoding - * the encoding to be used for parsing the given - * inputStream - * - * @return the parsed document - * - * @throws SLCommandException - * if parsing the inputStream fails. - * - * @throws NullPointerException - * if inputStram is null - */ - private Document parseDataObject(InputStream inputStream, String encoding) throws SLCommandException { - - LSInput input = domImplLS.createLSInput(); - input.setByteStream(inputStream); - - if (encoding != null) { - input.setEncoding(encoding); - } - - LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); - DOMConfiguration domConfig = parser.getDomConfig(); - SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); - domConfig.setParameter("error-handler", errorHandler); - domConfig.setParameter("validate", Boolean.FALSE); - - Document doc; - try { - doc = parser.parse(input); - } catch (DOMException e) { - log.info("Existing XML document cannot be parsed.", e); - throw new SLCommandException(4111); - } catch (LSException e) { - log.info("Existing XML document cannot be parsed. ", e); - throw new SLCommandException(4111); - } - - if (errorHandler.hasErrors()) { - // log errors - if (log.isInfoEnabled()) { - List errorMessages = errorHandler.getErrorMessages(); - StringBuffer sb = new StringBuffer(); - for (String errorMessage : errorMessages) { - sb.append(" "); - sb.append(errorMessage); - } - log.info("Existing XML document cannot be parsed. " + sb.toString()); - } - throw new SLCommandException(4111); - } - - return doc; - - } - - -} + + /** + * Configures this DataObject with the information provided within the given + * sl:DataObjectInfo. + * + * @param dataObjectInfo + * the sl:DataObjectInfo + * + * @throws SLCommandException + * if configuring this DataObject with the information provided in + * the sl:DataObjectInfo fails. + * @throws SLRequestException + * if the information provided in the sl:DataObjectInfo + * does not conform to the security layer specification. + * @throws NullPointerException + * if dataObjectInfo is null + */ + public void setDataObjectInfo(DataObjectInfoType dataObjectInfo) throws SLCommandException, SLRequestException { + + Base64XMLLocRefOptRefContentType dataObject = dataObjectInfo.getDataObject(); + String structure = dataObjectInfo.getStructure(); + + // select and unmarshal an appropriate transformation path if provided + // and set the final data meta information + XSECTTransforms transforms = createTransformsAndSetFinalDataMetaInfo(dataObjectInfo.getTransformsInfo()); + + if ("enveloping".equals(structure)) { + + // configure this DataObject as an enveloped DataObject + setEnvelopedDataObject(dataObject, transforms); + + } else if ("detached".equals(structure)) { + + // configure this DataObject as an detached DataObject + setDetachedDataObject(dataObject, transforms); + + } + // other values are not allowed by the schema and are therefore ignored + + } + + private byte[] getTransformsBytes(at.gv.egiz.slbinding.impl.TransformsInfoType ti) { + return ti.getRedirectedStream().toByteArray(); +// byte[] transformsBytes = ti.getRedirectedStream().toByteArray(); +// +// if (transformsBytes == null || transformsBytes.length == 0) { +// return null; +// } +// +// String dsigPrefix = ti.getNamespaceContext().getNamespaceURI("http://www.w3.org/2000/09/xmldsig#"); +// byte[] pre, post; +// if (dsigPrefix == null) { +// log.trace("XMLDSig not declared in outside dsig:Transforms"); +// pre = "".getBytes(); +// post = "".getBytes(); +// } else { +// log.trace("XMLDSig bound to prefix " + dsigPrefix); +// pre = ("").getBytes(); +// post = "".getBytes(); +// } +// +// byte[] workaround = new byte[pre.length + transformsBytes.length + post.length]; +// System.arraycopy(pre, 0, workaround, 0, pre.length); +// System.arraycopy(transformsBytes, 0, workaround, pre.length, transformsBytes.length); +// System.arraycopy(post, 0, workaround, pre.length + transformsBytes.length, post.length); +// return workaround; + } + + /** + * Configures this DataObject as an enveloped DataObject with the information + * provided within the given sl:DataObject. + * + * @param dataObject + * the sl:DataObject + * @param transforms + * an optional Transforms element (may be + * null) + * + * @throws SLCommandException + * if configuring this DataObject with the information provided in + * the sl:DataObject fails. + * @throws SLRequestException + * if the information provided in the sl:DataObject + * does not conform to the security layer specification. + * @throws NullPointerException + * if dataObject is null + */ + private void setEnvelopedDataObject( + Base64XMLLocRefOptRefContentType dataObject, XSECTTransforms transforms) + throws SLCommandException, SLRequestException { + + String reference = dataObject.getReference(); + if (reference == null) { + // + // case A + // + // The Reference attribute is not used; the content of sl:DataObject represents the data object. + // If the data object is XML-coded (the sl:XMLContent element is used in sl:DataObject), then it + // must be incorporated in the signature structure as parsed XML. + // + + if (dataObject.getBase64Content() != null) { + + log.debug("Adding DataObject (Base64Content) without a reference URI."); + + // create XMLObject + XMLObject xmlObject = createXMLObject(new ByteArrayInputStream(dataObject.getBase64Content())); + + setXMLObjectAndReferenceBase64(xmlObject, transforms); + + } else if (dataObject.getXMLContent() != null) { + + log.debug("Adding DataObject (XMLContent) without a reference URI."); + + // create XMLObject + DocumentFragment content = parseDataObject((XMLContentType) dataObject.getXMLContent()); + XMLObject xmlObject = createXMLObject(content); + + setXMLObjectAndReferenceXML(xmlObject, transforms); + + } else if (dataObject.getLocRefContent() != null) { + + log.debug("Adding DataObject (LocRefContent) without a reference URI."); + + setEnvelopedDataObject(dataObject.getLocRefContent(), transforms); + + } else { + + // not allowed + log.info("XML structure of the command request contains an " + + "invalid combination of optional elements or attributes. " + + "DataObject of structure='enveloped' without a reference must contain content."); + throw new SLRequestException(3003); + + } + + } else { + + if (dataObject.getBase64Content() == null && + dataObject.getXMLContent() == null && + dataObject.getLocRefContent() == null) { + + // + // case B + // + // The Reference attribute contains a URI that must be resolved by the + // Citizen Card Environment to obtain the data object. + // The content of sl:DataObject remains empty + // + + log.debug("Adding DataObject from reference URI '" + reference + "'."); + + setEnvelopedDataObject(reference, transforms); + + } else { + + // not allowed + log.info("XML structure of the command request contains an " + + "invalid combination of optional elements or attributes. " + + "DataObject of structure='enveloped' with reference must not contain content."); + throw new SLRequestException(3003); + + } + + + } + + } + + /** + * Configures this DataObject as an enveloped DataObject with the content to + * be dereferenced from the given reference. + * + * @param reference + * the reference URI + * @param transforms + * an optional Transforms element (may be + * null) + * + * @throws SLCommandException + * if dereferencing the given reference fails, or if + * configuring this DataObject with the data dereferenced from the + * given reference fails. + * @throws NullPointerException + * if reference is null + */ + private void setEnvelopedDataObject(String reference, XSECTTransforms transforms) throws SLCommandException { + + if (reference == null) { + throw new NullPointerException("Argument 'reference' must not be null."); + } + + // dereference URL + URLDereferencer dereferencer = URLDereferencer.getInstance(); + + StreamData streamData; + try { + streamData = dereferencer.dereference(reference, ctx.getDereferencerContext()); + } catch (IOException e) { + log.info("Failed to dereference XMLObject from '" + reference + "'.", e); + throw new SLCommandException(4110); + } + + Node childNode; + + String contentType = streamData.getContentType(); + if (contentType.startsWith("text/xml")) { + + // If content type is text/xml parse content. + String charset = HttpUtil.getCharset(contentType, true); + + Document doc = parseDataObject(streamData.getStream(), charset); + + childNode = doc.getDocumentElement(); + + if (childNode == null) { + log.info("Failed to parse XMLObject from '" + reference + "'."); + throw new SLCommandException(4111); + } + + XMLObject xmlObject = createXMLObject(childNode); + + setXMLObjectAndReferenceXML(xmlObject, transforms); + + } else { + + // Include content Base64 encoded. + XMLObject xmlObject = createXMLObject(streamData.getStream()); + + setXMLObjectAndReferenceBase64(xmlObject, transforms); + + } + + } + + /** + * Configures this DataObject as an detached DataObject with the information + * provided in the given sl:DataObject and optionally + * transforms. + * + * @param dataObject + * the sl:DataObject + * @param transforms + * an optional Transforms object, may be null + * + * @throws SLCommandException + * if configuring this DataObject with the information provided in + * the sl:DataObject fails. + * @throws SLRequestException + * if the information provided in the sl:DataObject + * does not conform to the security layer specification. + * @throws NullPointerException + * if dataObject is null + */ + private void setDetachedDataObject( + Base64XMLLocRefOptRefContentType dataObject, XSECTTransforms transforms) + throws SLCommandException, SLRequestException { + + String referenceURI = dataObject.getReference(); + + if (referenceURI == null) { + + // not allowed + log.info("XML structure of the command request contains an " + + "invalid combination of optional elements or attributes. " + + "DataObject of structure='detached' must contain a reference."); + throw new SLRequestException(3003); + + } else { + + DigestMethod dm; + try { + dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } + + String idValue = ctx.getIdValueFactory().createIdValue("Reference"); + + reference = new XSECTReference(referenceURI, dm, transforms, null, idValue); + + // case D: + // + // The Reference attribute contains a URI that is used by the Citizen Card + // Environment to code the reference to the data object as part of the XML + // signature (attribute URI in the dsig:Reference) element. The content of + // sl:DataObject represents the data object. + + if (dataObject.getLocRefContent() != null) { + String locRef = dataObject.getLocRefContent(); + try { + this.reference.setDereferencer(new LocRefDereferencer(ctx.getDereferencerContext(), locRef)); + } catch (URISyntaxException e) { + log.info("Invalid URI '" + locRef + "' in DataObject.", e); + throw new SLCommandException(4003); + } catch (IllegalArgumentException e) { + log.info("LocRef URI of '" + locRef + "' not supported in DataObject. ", e); + throw new SLCommandException(4003); + } + } else if (dataObject.getBase64Content() != null) { + byte[] base64Content = dataObject.getBase64Content(); + this.reference.setDereferencer(new ByteArrayDereferencer(base64Content)); + } else if (dataObject.getXMLContent() != null) { + XMLContentType xmlContent = (XMLContentType) dataObject.getXMLContent(); + byte[] bytes = xmlContent.getRedirectedStream().toByteArray(); + this.reference.setDereferencer(new ByteArrayDereferencer(bytes)); + } else { + + // case C: + // + // The Reference attribute contains a URI that must be resolved by the + // Citizen Card Environment to obtain the data object. The Reference + // attribute contains a URI that is used by the Citizen Card Environment + // to code the reference to the data object as part of the XML signature + // (attribute URI in the dsig:Reference) element. The content of + // sl:DataObject remains empty. + + } + + } + } + + /** + * Returns the preferred sl:TransformInfo from the given list of + * transformInfos, or null if none of the given + * transformInfos is preferred over the others. + * + * @param transformsInfos + * a list of sl:TransformInfos + * + * @return the selected sl:TransformInfo or null, if + * none is preferred over the others + */ + private TransformsInfoType selectPreferredTransformsInfo(List transformsInfos) { + + Map mimeTypes = new HashMap(); + + StringBuilder debugString = null; + if (log.isDebugEnabled()) { + debugString = new StringBuilder(); + debugString.append("Got " + transformsInfos.size() + " TransformsInfo(s):"); + } + + for (TransformsInfoType transformsInfoType : transformsInfos) { + MetaInfoType finalDataMetaInfo = transformsInfoType.getFinalDataMetaInfo(); + String mimeType = finalDataMetaInfo.getMimeType(); + String description = finalDataMetaInfo.getDescription(); + mimeTypes.put(mimeType, transformsInfoType); + if (debugString != null) { + debugString.append("\n FinalDataMetaInfo: MIME-Type="); + debugString.append(mimeType); + if (description != null) { + debugString.append(" "); + debugString.append(description); + } + } + } + + if (debugString != null) { + log.debug(debugString); + } + + // look for preferred transform + for (String mimeType : DEFAULT_PREFFERED_MIME_TYPES) { + if (mimeTypes.containsKey(mimeType)) { + return mimeTypes.get(mimeType); + } + } + + // no preferred transform + return null; + + } + + /** + * Create an instance of ds:Transforms from the given + * sl:TransformsInfo. + * + * @param transformsInfo + * the sl:TransformsInfo + * + * @return a corresponding unmarshalled ds:Transforms, or + * null if the given sl:TransformsInfo does + * not contain a dsig:Transforms element + * + * @throws SLRequestException + * if the ds:Transforms in the given + * transformsInfo are not valid or cannot be parsed. + * + * @throws MarshalException + * if the ds:Transforms in the given + * transformsInfo cannot be unmarshalled. + */ + private XSECTTransforms createTransforms(TransformsInfoType transformsInfo) throws SLRequestException, MarshalException { + + byte[] transforms = getTransformsBytes((at.gv.egiz.slbinding.impl.TransformsInfoType) transformsInfo); + + if (transforms != null && transforms.length > 0) { + // debug + if (log.isTraceEnabled()) { + StringBuilder sb = new StringBuilder(); + sb.append("Trying to parse transforms:\n"); + sb.append(new String(transforms, Charset.forName("UTF-8"))); + log.trace(sb); + } + + DOMImplementationLS domImplLS = DOMUtils.getDOMImplementationLS(); + LSInput input = domImplLS.createLSInput(); + input.setByteStream(new ByteArrayInputStream(transforms)); + + LSParser parser = domImplLS.createLSParser( + DOMImplementationLS.MODE_SYNCHRONOUS, null); + DOMConfiguration domConfig = parser.getDomConfig(); + SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); + domConfig.setParameter("error-handler", errorHandler); + domConfig.setParameter("validate", Boolean.FALSE); + + Document document; + try { + document = parser.parse(input); + } catch (DOMException e) { + log.info("Failed to parse dsig:Transforms.", e); + throw new SLRequestException(3002); + } catch (LSException e) { + log.info("Failed to parse dsig:Transforms.", e); + throw new SLRequestException(3002); + } + + // adopt ds:Transforms + Element transformsElt = document.getDocumentElement(); + Node adoptedTransforms = ctx.getDocument().adoptNode(transformsElt); + + DOMCryptoContext context = new DOMCryptoContext(); + + // unmarshall ds:Transforms + return new XSECTTransforms(context, adoptedTransforms); + + } else { + return null; + } + + +// TransformsType transformsType = transformsInfo.getTransforms(); +// if (transformsType == null) { +// return null; +// } +// List transformList = transformsType.getTransform(); +// +// DOMImplementationLS domImplLS = DOMUtils.getDOMImplementationLS(); +//// Document transformsDoc = ((DOMImplementation) domImplLS).createDocument("http://www.w3.org/2000/09/xmldsig#", "Transforms", null); +//// Element transforms = transformsDoc.getDocumentElement(); +// Document transformsDoc = DOMUtils.createDocument(); +// Element transforms = transformsDoc.createElementNS( +// "http://www.w3.org/2000/09/xmldsig#", +// Signature.XMLDSIG_PREFIX + ":Transforms"); +// transformsDoc.appendChild(transforms); +// +// for (TransformType transformType : transformList) { +// log.trace("found " + transformType.getClass().getName()); +// Element transform = transformsDoc.createElementNS( +// "http://www.w3.org/2000/09/xmldsig#", +// Signature.XMLDSIG_PREFIX + ":Transform"); +// String algorithm = transformType.getAlgorithm(); +// if (algorithm != null) { +// log.trace("found algorithm " + algorithm); +// transform.setAttribute("Algorithm", algorithm); +// } +// +// at.gv.egiz.slbinding.impl.TransformType t = (at.gv.egiz.slbinding.impl.TransformType) transformType; +// byte[] redirectedBytes = t.getRedirectedStream().toByteArray(); +// if (redirectedBytes != null && redirectedBytes.length > 0) { +// if (log.isTraceEnabled()) { +// StringBuilder sb = new StringBuilder(); +// sb.append("Trying to parse dsig:Transform:\n"); +// sb.append(new String(redirectedBytes, Charset.forName("UTF-8"))); +// log.trace(sb); +// } +// LSInput input = domImplLS.createLSInput(); +// input.setByteStream(new ByteArrayInputStream(redirectedBytes)); +// +// LSParser parser = domImplLS.createLSParser( +// DOMImplementationLS.MODE_SYNCHRONOUS, null); +// DOMConfiguration domConfig = parser.getDomConfig(); +// SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); +// domConfig.setParameter("error-handler", errorHandler); +// domConfig.setParameter("validate", Boolean.FALSE); +// +// try { +// Document redirectedDoc = parser.parse(input); +// Node redirected = transformsDoc.adoptNode(redirectedDoc.getDocumentElement()); +// transform.appendChild(redirected); +// +// //not supported by Xerces2.9.1 +//// Node redirected = parser.parseWithContext(input, transform, LSParser.ACTION_APPEND_AS_CHILDREN); +// +// } catch (DOMException e) { +// log.info("Failed to parse dsig:Transform.", e); +// throw new SLRequestException(3002); +// } catch (LSException e) { +// log.info("Failed to parse dsig:Transform.", e); +// throw new SLRequestException(3002); +// } +// } +// transforms.appendChild(transform); +// } +// +// //adopt ds:Transforms +// Node adoptedTransforms = ctx.getDocument().adoptNode(transforms); +// DOMCryptoContext context = new DOMCryptoContext(); +// +// // unmarshall ds:Transforms +// return new XSECTTransforms(context, adoptedTransforms); + + } + + /** + * Sets the mimeType and the description value + * for this DataObject. + * + * @param metaInfoType the sl:FinalMetaDataInfo + * + * @throws NullPointerException if metaInfoType is null + */ + private void setFinalDataMetaInfo(MetaInfoType metaInfoType) { + + this.mimeType = metaInfoType.getMimeType(); + this.description = metaInfoType.getDescription(); + + } + + /** + * Selects an appropriate transformation path (if present) from the given list + * of sl:TransformInfos, sets the corresponding final data meta info and + * returns the corresponding unmarshalled ds:Transforms. + * + * @param transformsInfos the sl:TransformInfos + * + * @return the unmarshalled ds:Transforms, or null if + * no transformation path has been selected. + * + * @throws SLRequestException if the given list ds:TransformsInfo contains + * an invalid ds:Transforms element, or no suitable transformation path + * can be found. + */ + private XSECTTransforms createTransformsAndSetFinalDataMetaInfo( + List transformsInfos) throws SLRequestException { + + TransformsInfoType preferredTransformsInfo = selectPreferredTransformsInfo(transformsInfos); + // try preferred transform + if (preferredTransformsInfo != null) { + + try { + XSECTTransforms transforms = createTransforms(preferredTransformsInfo); + setFinalDataMetaInfo(preferredTransformsInfo.getFinalDataMetaInfo()); + return transforms; + } catch (MarshalException e) { + + String mimeType = preferredTransformsInfo.getFinalDataMetaInfo().getMimeType(); + log.info("Failed to unmarshal preferred transformation path (MIME-Type=" + + mimeType + ").", e); + + } + + } + + // look for another suitable transformation path + for (TransformsInfoType transformsInfoType : transformsInfos) { + + try { + XSECTTransforms transforms = createTransforms(transformsInfoType); + setFinalDataMetaInfo(transformsInfoType.getFinalDataMetaInfo()); + return transforms; + } catch (MarshalException e) { + + String mimeType = transformsInfoType.getFinalDataMetaInfo().getMimeType(); + log.info("Failed to unmarshal transformation path (MIME-Type=" + + mimeType + ").", e); + } + + } + + // no suitable transformation path found + throw new SLRequestException(3003); + + } + + /** + * Create an XMLObject with the Base64 encoding of the given + * content. + * + * @param content + * the to-be Base64 encoded content + * @return an XMLObject with the Base64 encoded content + */ + private XMLObject createXMLObject(InputStream content) { + + Text textNode; + try { + textNode = at.gv.egiz.dom.DOMUtils.createBase64Text(content, ctx.getDocument()); + } catch (IOException e) { + log.error(e); + throw new SLRuntimeException(e); + } + + DOMStructure structure = new DOMStructure(textNode); + + String idValue = ctx.getIdValueFactory().createIdValue("Object"); + + return ctx.getSignatureFactory().newXMLObject(Collections.singletonList(structure), idValue, null, null); + + } + + /** + * Create an XMLObject with the given content node. + * + * @param content the content node + * + * @return an XMLObject with the given content + */ + private XMLObject createXMLObject(Node content) { + + String idValue = ctx.getIdValueFactory().createIdValue("Object"); + + List structures = Collections.singletonList(new DOMStructure(content)); + + return ctx.getSignatureFactory().newXMLObject(structures, idValue, null, null); + + } + + /** + * Sets the given xmlObject and creates and sets a corresponding + * Reference. + *

+ * A transform to Base64-decode the xmlObject's content is inserted at the top + * of to the optional transforms if given, or to a newly created + * Transforms element if transforms is + * null. + * + * @param xmlObject + * the XMLObject + * @param transforms + * an optional Transforms element (may be + * null) + * + * @throws SLCommandException + * if creating the Reference fails + * @throws NullPointerException + * if xmlObject is null + */ + private void setXMLObjectAndReferenceBase64(XMLObject xmlObject, XSECTTransforms transforms) throws SLCommandException { + + // create reference URI + // + // NOTE: the ds:Object can be referenced directly, as the Base64 transform + // operates on the text() of the input nodelist. + // + String referenceURI = "#" + xmlObject.getId(); + + // create Base64 Transform + Transform transform; + try { + transform = ctx.getSignatureFactory().newTransform(Transform.BASE64, (TransformParameterSpec) null); + } catch (NoSuchAlgorithmException e) { + // algorithm must be present + throw new SLRuntimeException(e); + } catch (InvalidAlgorithmParameterException e) { + // algorithm does not take parameters + throw new SLRuntimeException(e); + } + + if (transforms == null) { + transforms = new XSECTTransforms(Collections.singletonList(transform)); + } else { + transforms.insertTransform(transform); + } + + DigestMethod dm; + try { + dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } + String id = ctx.getIdValueFactory().createIdValue("Reference"); + + this.xmlObject = xmlObject; + this.reference = new XSECTReference(referenceURI, dm, transforms, null, id); + + } + + /** + * Sets the given xmlObject and creates and sets a corresponding + * Reference. + *

+ * A transform to select the xmlObject's content is inserted at the top of to + * the optional transforms if given, or to a newly created + * Transforms element if transforms is + * null. + *

+ * + * @param xmlObject + * the XMLObject + * @param transforms + * an optional Transforms element (may be + * null) + * + * @throws SLCommandException + * if creating the Reference fails + * @throws NullPointerException + * if xmlObject is null + */ + private void setXMLObjectAndReferenceXML(XMLObject xmlObject, XSECTTransforms transforms) throws SLCommandException { + + // create reference URI + String referenceURI = "#" + xmlObject.getId(); + + // create Transform to select ds:Object's children + Transform xpathTransform; + Transform c14nTransform; + try { + + XPathType xpath = new XPathType("id(\"" + xmlObject.getId() + "\")/node()", XPathType.Filter.INTERSECT); + List xpaths = Collections.singletonList(xpath); + XPathFilter2ParameterSpec params = new XPathFilter2ParameterSpec(xpaths); + + xpathTransform = ctx.getSignatureFactory().newTransform(Transform.XPATH2, params); + + // add exclusive canonicalization to avoid signing the namespace context of the ds:Object + c14nTransform = ctx.getSignatureFactory().newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); + + } catch (NoSuchAlgorithmException e) { + // algorithm must be present + throw new SLRuntimeException(e); + } catch (InvalidAlgorithmParameterException e) { + // params must be appropriate + throw new SLRuntimeException(e); + } + + if (transforms == null) { + List newTransfroms = new ArrayList(); + newTransfroms.add(xpathTransform); + newTransfroms.add(c14nTransform); + transforms = new XSECTTransforms(newTransfroms); + } else { + transforms.insertTransform(xpathTransform); + } + + DigestMethod dm; + try { + dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get DigestMethod.", e); + throw new SLCommandException(4006); + } + String id = ctx.getIdValueFactory().createIdValue("Reference"); + + this.xmlObject = xmlObject; + this.reference = new XSECTReference(referenceURI, dm, transforms, null, id); + + } + + /** + * Parses the given xmlContent and returns a corresponding + * document fragment. + * + *

+ * The to-be parsed content is surrounded by ... elements to + * allow for mixed (e.g. Text and Element) content in XMLContent. + *

+ * + * @param xmlContent + * the XMLContent to-be parsed + * + * @return a document fragment containing the parsed nodes + * + * @throws SLCommandException + * if parsing the given xmlContent fails + * + * @throws NullPointerException + * if xmlContent is null + */ + private DocumentFragment parseDataObject(XMLContentType xmlContent) throws SLCommandException { + + ByteArrayOutputStream redirectedStream = xmlContent.getRedirectedStream(); + + // Note: We can assume a fixed character encoding of UTF-8 for the + // content of the redirect stream as the content has already been parsed + // and serialized again to the redirect stream. + + List inputStreams = new ArrayList(); + try { + // dummy start element + inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); + + // content + inputStreams.add(new ByteArrayInputStream(redirectedStream.toByteArray())); + + // dummy end element + inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + throw new SLRuntimeException(e); + } + + SequenceInputStream inputStream = new SequenceInputStream(Collections.enumeration(inputStreams)); + + // parse DataObject + Document doc = parseDataObject(inputStream, "UTF-8"); + + Element documentElement = doc.getDocumentElement(); + + if (documentElement == null || + !"dummy".equals(documentElement.getLocalName())) { + log.info("Failed to parse DataObject XMLContent."); + throw new SLCommandException(4111); + } + + DocumentFragment fragment = doc.createDocumentFragment(); + while (documentElement.getFirstChild() != null) { + fragment.appendChild(documentElement.getFirstChild()); + } + + // log parsed document + if (log.isTraceEnabled()) { + + StringWriter writer = new StringWriter(); + + writer.write("DataObject:\n"); + + LSOutput output = domImplLS.createLSOutput(); + output.setCharacterStream(writer); + output.setEncoding("UTF-8"); + LSSerializer serializer = domImplLS.createLSSerializer(); + serializer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE); + serializer.write(fragment, output); + + log.trace(writer.toString()); + } + + return fragment; + + } + + /** + * Parses the given inputStream using the given + * encoding and returns the parsed document. + * + * @param inputStream + * the to-be parsed input + * + * @param encoding + * the encoding to be used for parsing the given + * inputStream + * + * @return the parsed document + * + * @throws SLCommandException + * if parsing the inputStream fails. + * + * @throws NullPointerException + * if inputStram is null + */ + private Document parseDataObject(InputStream inputStream, String encoding) throws SLCommandException { + + LSInput input = domImplLS.createLSInput(); + input.setByteStream(inputStream); + + if (encoding != null) { + input.setEncoding(encoding); + } + + LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); + DOMConfiguration domConfig = parser.getDomConfig(); + SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); + domConfig.setParameter("error-handler", errorHandler); + domConfig.setParameter("validate", Boolean.FALSE); + + Document doc; + try { + doc = parser.parse(input); + } catch (DOMException e) { + log.info("Existing XML document cannot be parsed.", e); + throw new SLCommandException(4111); + } catch (LSException e) { + log.info("Existing XML document cannot be parsed. ", e); + throw new SLCommandException(4111); + } + + if (errorHandler.hasErrors()) { + // log errors + if (log.isInfoEnabled()) { + List errorMessages = errorHandler.getErrorMessages(); + StringBuffer sb = new StringBuffer(); + for (String errorMessage : errorMessages) { + sb.append(" "); + sb.append(errorMessage); + } + log.info("Existing XML document cannot be parsed. " + sb.toString()); + } + throw new SLCommandException(4111); + } + + return doc; + + } + + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java index 8baa0137..9182e824 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java @@ -87,6 +87,8 @@ import at.gv.egiz.bku.utils.urldereferencer.StreamData; import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; import at.gv.egiz.dom.DOMUtils; +import at.gv.egiz.marshal.NamespacePrefix; +import at.gv.egiz.marshal.NamespacePrefixMapperImpl; import at.gv.egiz.slbinding.impl.XMLContentType; import at.gv.egiz.stal.STAL; import at.gv.egiz.xades.QualifyingPropertiesException; @@ -99,6 +101,7 @@ import at.gv.egiz.xades.QualifyingPropertiesFactory; * @author mcentner */ public class Signature { + public static final String XMLDSIG_PREFIX = "dsig"; /** * Logging facility. @@ -407,7 +410,7 @@ public class Signature { signContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); - signContext.putNamespacePrefix(XMLSignature.XMLNS, "dsig"); + signContext.putNamespacePrefix(XMLSignature.XMLNS,XMLDSIG_PREFIX); signContext.setURIDereferencer(new URIDereferncerAdapter(ctx.getDereferencerContext())); -- cgit v1.2.3 From 2882e14d19cfa58ea382083434210aaf0cfea3e3 Mon Sep 17 00:00:00 2001 From: wbauer Date: Fri, 13 Mar 2009 07:49:49 +0000 Subject: Fixed Bug#405 and added according test case Fixed Bug#402 Added Feature#403 git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@320 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java | 1 - 1 file changed, 1 deletion(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java index a6399c9b..f5394157 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java @@ -105,7 +105,6 @@ public class LocRefDereferencer implements URIDereferencer { throw new URIReferenceException("Failed to dereference URI '" + locRef + "'. " + e.getMessage(), e); } - return new OctetStreamData(streamData.getStream(), locRef, streamData .getContentType()); } -- cgit v1.2.3 From 275aae71fbac34cee00f009cd9c1a02d2786a662 Mon Sep 17 00:00:00 2001 From: mcentner Date: Tue, 11 Aug 2009 08:01:51 +0000 Subject: Fixed Bug#463 https://egovlabs.gv.at/tracker/index.php?func=detail&aid=463&group_id=13&atid=134. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@416 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java index 20d20c9d..c3a40713 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java @@ -278,9 +278,8 @@ public class IdentityLinkInfoboxImpl extends AbstractBinaryFileInfobox { new Object[] { issuerTemplate }); } } - } else { - result.setResultBytes(resultBytes.toByteArray()); - } + } + result.setResultBytes(resultBytes.toByteArray()); } return result; -- cgit v1.2.3 From 2dc37cef3cb0f5aa4dcc7a3bb28259181e6f5b3e Mon Sep 17 00:00:00 2001 From: mcentner Date: Wed, 12 Aug 2009 14:16:58 +0000 Subject: Fixed Bug#463 https://egovlabs.gv.at/tracker/index.php?func=detail&aid=463&group_id=13&atid=134. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@417 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/IdentityLinkInfoboxImpl.java | 57 +++++++++++----------- 1 file changed, 29 insertions(+), 28 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java index c3a40713..7a82e43f 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java @@ -172,9 +172,29 @@ public class IdentityLinkInfoboxImpl extends AbstractBinaryFileInfobox { InfoboxReadResultFileImpl result = new InfoboxReadResultFileImpl(); ByteArrayOutputStream resultBytes = null; - Result xmlResult = (isXMLEntity() || getDomainIdentifier() != null) - ? result.getXmlResult(true) - : new StreamResult((resultBytes = new ByteArrayOutputStream())); + Result xmlResult; + if (isXMLEntity()) { + // we will return the result as XML entity + xmlResult = result.getXmlResult(true); + } else { + // we will return the result as binary data + if (getDomainIdentifier() != null) { + // we need an XML result to be able to replace the domain identifier below + Document doc; + try { + doc = dbf.newDocumentBuilder().newDocument(); + } catch (ParserConfigurationException e) { + // it should always be possible to create a new Document + log.error("Failed to create XML document.", e); + throw new SLRuntimeException(e); + } + xmlResult = new DOMResult(doc); + } else { + resultBytes = new ByteArrayOutputStream(); + xmlResult = new StreamResult(resultBytes); + } + } + try { log.trace("Trying to transform identitylink"); identityLinkTransformer.transformIdLink(issuerTemplate, new DOMSource(document), xmlResult); @@ -235,23 +255,9 @@ public class IdentityLinkInfoboxImpl extends AbstractBinaryFileInfobox { if (!isXMLEntity()) { if (resultBytes == null) { resultBytes = new ByteArrayOutputStream(); - if (xmlResult instanceof DOMResult) { Node node = ((DOMResult) xmlResult).getNode(); - Node nextSibling = ((DOMResult) xmlResult).getNextSibling(); - - DOMSource xmlSource; - if (nextSibling != null) { - xmlSource = new DOMSource(nextSibling.getPreviousSibling()); - } else if (node != null) { - xmlSource = new DOMSource(node.getFirstChild()); - } else { - log - .error("IssuerTemplate transformation returned no node."); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } + DOMSource xmlSource = new DOMSource(node); TransformerFactory transformerFactory = TransformerFactory.newInstance(); try { Transformer transformer = transformerFactory.newTransformer(); @@ -267,16 +273,11 @@ public class IdentityLinkInfoboxImpl extends AbstractBinaryFileInfobox { SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, new Object[] { issuerTemplate }); } - } else if (xmlResult instanceof StreamResult) { - OutputStream outputStream = ((StreamResult) xmlResult).getOutputStream(); - if (outputStream instanceof ByteArrayOutputStream) { - result.setResultBytes(((ByteArrayOutputStream) outputStream).toByteArray()); - } else { - log.error("ContentIsXMLEntity is set to 'false'. However, an XMLResult has already been set."); - throw new SLCommandException(4000, - SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, - new Object[] { issuerTemplate }); - } + } else { + log.error("ContentIsXMLEntity is set to 'false'. However, an XMLResult has already been set."); + throw new SLCommandException(4000, + SLExceptionMessages.EC4000_UNCLASSIFIED_IDLINK_TRANSFORMATION_FAILED, + new Object[] { issuerTemplate }); } } result.setResultBytes(resultBytes.toByteArray()); -- cgit v1.2.3 From bd070e82c276afb8c1c3a9ddc3b5712783760881 Mon Sep 17 00:00:00 2001 From: mcentner Date: Tue, 29 Sep 2009 17:36:06 +0000 Subject: Logging issues fixed: - Added possibility to configure logging of BKUWebstart. Logging is now configured from log4j configuration deployed with BKUWebstart in a first step. In a second step the webstart launcher looks for a log4j configuration file in the user's mooca configuration directory and updates the log4j configuration. - Logging of IAIK PKI properly initialized. IAIK PKI does not mess with the log4j configuration any longer. - Changed log4j accordingly (an appender is now needed as IAIK PKI does not reconfigure log4j any longer). Added css-stylesheet to ErrorResponses issued by the BKU to improve the presentation to the user. Changed dependencies of BKUWebStart (see Issue#469 https://egovlabs.gv.at/tracker/index.php?func=detail&aid=469&group_id=13&atid=134). DataURLConnection now uses the request encoding of SL < 1.2. application/x-www-form-urlencoded is now used as default encoding method. multipart/form-data is used only if transfer parameters are present in the request that require a Content-Type parameter. This can only be set with multipart/form-data. This is not in conformance with SL 1.2, however it should improve compatibility with applications. Therefore, removed the ability to configure the DataURLConnection implementation class. DataURLConnection now uses a streaming implementation for encoding of application/x-www-form-urlencoded requests. XWWWFormUrlImputDecoder now uses a streaming implementation for decoding of application/x-www-form-urlencoded requests. Fixed Bug in SLResultPart that caused a binary response to be provided as parameter "XMLResponse" in a multipart/form-data encoded request to DataURL. SLCommandFactory now supports unmarshalling of SL < 1.2 requests in order issue meaningful error messages. Therefore, the marshaling context for response marshaling had to be separated from the marshaling context for requests in order to avoid the marshaling of SL < 1.2 namespace prefixes in SL 1.2 responses. Target attribute in QualifiedProperties is now marshaled. (see Issue#470 https://egovlabs.gv.at/tracker/index.php?func=detail&aid=470&group_id=13&atid=134) Reporting of XML validation errors improved. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@510 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/AbstractAssocArrayInfobox.java | 13 +-- .../impl/CreateXMLSignatureResultImpl.java | 15 ++-- .../egiz/bku/slcommands/impl/ErrorResultImpl.java | 6 +- .../bku/slcommands/impl/GetStatusCommandImpl.java | 2 - .../bku/slcommands/impl/GetStatusResultImpl.java | 4 +- .../slcommands/impl/IdentityLinkInfoboxImpl.java | 1 - .../slcommands/impl/InfoboxReadResultFileImpl.java | 15 ++-- .../bku/slcommands/impl/InfoboxReadResultImpl.java | 4 +- .../slcommands/impl/InfoboxUpdateResultImpl.java | 4 +- .../slcommands/impl/NullOperationResultImpl.java | 4 +- .../gv/egiz/bku/slcommands/impl/SLResultImpl.java | 94 +++++++++++++--------- .../egiz/bku/slcommands/impl/xsect/DataObject.java | 1 - .../egiz/bku/slcommands/impl/xsect/Signature.java | 18 ++--- 13 files changed, 88 insertions(+), 93 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java index ce03dcf9..9a4536e6 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractAssocArrayInfobox.java @@ -16,7 +16,6 @@ */ package at.gv.egiz.bku.slcommands.impl; -import at.gv.egiz.marshal.NamespacePrefixMapperImpl; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Collections; @@ -24,7 +23,6 @@ import java.util.List; import java.util.Map; import java.util.regex.Pattern; -import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; @@ -42,10 +40,8 @@ import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayTy import at.buergerkarte.namespaces.securitylayer._1.InfoboxReadParamsAssocArrayType.ReadValue; import at.gv.egiz.bku.slcommands.InfoboxReadResult; import at.gv.egiz.bku.slcommands.SLCommandContext; -import at.gv.egiz.bku.slcommands.SLCommandFactory; +import at.gv.egiz.bku.slcommands.SLMarshallerFactory; import at.gv.egiz.bku.slexceptions.SLCommandException; -import at.gv.egiz.marshal.MarshallerFactory; -import javax.xml.bind.PropertyException; /** * An abstract base class for {@link Infobox} implementations of type associative array. @@ -255,13 +251,10 @@ public abstract class AbstractAssocArrayInfobox extends AbstractInfoboxImpl } protected byte[] marshallValue(Object jaxbElement) throws SLCommandException { - SLCommandFactory commandFactory = SLCommandFactory.getInstance(); - JAXBContext jaxbContext = commandFactory.getJaxbContext(); - ByteArrayOutputStream result; + Marshaller marshaller = SLMarshallerFactory.getInstance().createMarshaller(false); + ByteArrayOutputStream result = new ByteArrayOutputStream(); try { - Marshaller marshaller = MarshallerFactory.createMarshaller(jaxbContext); - result = new ByteArrayOutputStream(); marshaller.marshal(jaxbElement, result); } catch (JAXBException e) { log.info("Failed to marshall infobox content.", e); diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java index b352a51e..19df4334 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/CreateXMLSignatureResultImpl.java @@ -16,8 +16,6 @@ */ package at.gv.egiz.bku.slcommands.impl; -import at.gv.egiz.marshal.NamespacePrefixMapperImpl; -import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; @@ -33,10 +31,8 @@ import org.w3c.dom.Node; import at.buergerkarte.namespaces.securitylayer._1.CreateXMLSignatureResponseType; import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; -import at.gv.egiz.bku.slcommands.SLCommandFactory; +import at.gv.egiz.bku.slcommands.SLMarshallerFactory; import at.gv.egiz.bku.slexceptions.SLRuntimeException; -import at.gv.egiz.marshal.MarshallerFactory; -import javax.xml.bind.PropertyException; /** * This calls implements the result of the security layer command CreateXMLSignature. @@ -86,10 +82,9 @@ public class CreateXMLSignatureResultImpl extends SLResultImpl { JAXBElement createCreateXMLSignatureResponse = factory.createCreateXMLSignatureResponse(createCreateXMLSignatureResponseType); DocumentFragment fragment = doc.createDocumentFragment(); - - JAXBContext jaxbContext = SLCommandFactory.getInstance().getJaxbContext(); + + Marshaller marshaller = SLMarshallerFactory.getInstance().createMarshaller(false); try { - Marshaller marshaller = MarshallerFactory.createMarshaller(jaxbContext); marshaller.marshal(createCreateXMLSignatureResponse, fragment); } catch (JAXBException e) { log.error("Failed to marshall 'CreateXMLSignatureResponse'", e); @@ -105,8 +100,8 @@ public class CreateXMLSignatureResultImpl extends SLResultImpl { } @Override - public void writeTo(Result result, Templates templates) { - writeTo(doc, result, templates); + public void writeTo(Result result, Templates templates, boolean fragment) { + writeTo(doc, result, templates, fragment); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java index 5d0f0de0..aedde238 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/ErrorResultImpl.java @@ -56,11 +56,11 @@ public class ErrorResultImpl extends SLResultImpl implements ErrorResult { } @Override - public void writeTo(Result result, Templates templates) { + public void writeTo(Result result, Templates templates, boolean fragment) { if (locale == null) { - writeErrorTo(slException, result, templates); + writeErrorTo(slException, result, templates, fragment); } else { - writeErrorTo(slException, result, templates, locale); + writeErrorTo(slException, result, templates, locale, fragment); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusCommandImpl.java index 46bfe18b..0c2b96f9 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusCommandImpl.java @@ -19,10 +19,8 @@ package at.gv.egiz.bku.slcommands.impl; import at.buergerkarte.namespaces.securitylayer._1.GetStatusRequestType; import at.gv.egiz.bku.slcommands.GetStatusCommand; -import at.gv.egiz.bku.slcommands.SLCommandContext; import at.gv.egiz.bku.slcommands.SLResult; import at.gv.egiz.bku.slexceptions.SLCommandException; -import at.gv.egiz.bku.slexceptions.SLException; import at.gv.egiz.stal.ErrorResponse; import at.gv.egiz.stal.STAL; import at.gv.egiz.stal.STALResponse; diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusResultImpl.java index fddd3b0b..fb1f627f 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/GetStatusResultImpl.java @@ -45,8 +45,8 @@ public class GetStatusResultImpl extends SLResultImpl implements GetStatusResult } @Override - public void writeTo(Result result, Templates templates) { + public void writeTo(Result result, Templates templates, boolean fragment) { JAXBElement response = of.createGetStatusResponse(responseType); - writeTo(response, result, templates); + writeTo(response, result, templates, fragment); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java index 7a82e43f..160e9589 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/IdentityLinkInfoboxImpl.java @@ -18,7 +18,6 @@ package at.gv.egiz.bku.slcommands.impl; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.OutputStream; import java.net.MalformedURLException; import java.security.cert.X509Certificate; import java.util.ArrayList; diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java index 75e44afa..422b424f 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultFileImpl.java @@ -16,8 +16,6 @@ */ package at.gv.egiz.bku.slcommands.impl; -import at.gv.egiz.marshal.NamespacePrefixMapperImpl; -import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; @@ -39,10 +37,8 @@ import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; import at.buergerkarte.namespaces.securitylayer._1.XMLContentType; import at.gv.egiz.bku.slcommands.InfoboxReadResult; import at.gv.egiz.bku.slcommands.SLCommand; -import at.gv.egiz.bku.slcommands.SLCommandFactory; +import at.gv.egiz.bku.slcommands.SLMarshallerFactory; import at.gv.egiz.bku.slexceptions.SLRuntimeException; -import at.gv.egiz.marshal.MarshallerFactory; -import javax.xml.bind.PropertyException; /** * This class implements the result of the security layer command InfoboxReadRequest. @@ -98,10 +94,9 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements infoboxReadResponseType.setBinaryFileData(base64XMLContentType); JAXBElement infoboxReadResponse = factory.createInfoboxReadResponse(infoboxReadResponseType); - - JAXBContext context = SLCommandFactory.getInstance().getJaxbContext(); + + Marshaller marshaller = SLMarshallerFactory.getInstance().createMarshaller(false); try { - Marshaller marshaller = MarshallerFactory.createMarshaller(context); marshaller.marshal(infoboxReadResponse, doc); } catch (JAXBException e) { log.error("Failed to marshal 'InfoboxReadResponse' document.", e); @@ -158,8 +153,8 @@ public class InfoboxReadResultFileImpl extends SLResultImpl implements } @Override - public void writeTo(Result result, Templates templates) { - writeTo(xmlDocument, result, templates); + public void writeTo(Result result, Templates templates, boolean fragment) { + writeTo(xmlDocument, result, templates, fragment); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java index e508941d..271ec955 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxReadResultImpl.java @@ -55,10 +55,10 @@ public class InfoboxReadResultImpl extends SLResultImpl implements InfoboxReadRe } @Override - public void writeTo(Result result, Templates templates) { + public void writeTo(Result result, Templates templates, boolean fragment) { ObjectFactory objectFactory = new ObjectFactory(); JAXBElement response = objectFactory.createInfoboxReadResponse(infoboxReadResponse); - writeTo(response, result, templates); + writeTo(response, result, templates, fragment); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateResultImpl.java index 15064756..e12536ba 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxUpdateResultImpl.java @@ -36,8 +36,8 @@ public class InfoboxUpdateResultImpl extends SLResultImpl implements } @Override - public void writeTo(Result result, Templates templates) { - writeTo(RESPONSE, result, templates); + public void writeTo(Result result, Templates templates, boolean fragment) { + writeTo(RESPONSE, result, templates, fragment); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java index 05986f85..87733e39 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/NullOperationResultImpl.java @@ -41,8 +41,8 @@ public class NullOperationResultImpl extends SLResultImpl implements NullOperati } @Override - public void writeTo(Result result, Templates templates) { - writeTo(RESPONSE, result, templates); + public void writeTo(Result result, Templates templates, boolean fragment) { + super.writeTo(RESPONSE, result, templates, fragment); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java index 0452bddf..0077b7b2 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/SLResultImpl.java @@ -17,12 +17,14 @@ package at.gv.egiz.bku.slcommands.impl; import java.io.UnsupportedEncodingException; +import java.math.BigInteger; import java.util.Locale; -import javax.xml.bind.JAXBContext; +import javax.xml.XMLConstants; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; +import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; @@ -41,17 +43,15 @@ import org.w3c.dom.Node; import at.buergerkarte.namespaces.securitylayer._1.ErrorResponseType; import at.buergerkarte.namespaces.securitylayer._1.ObjectFactory; -import at.gv.egiz.marshal.NamespacePrefixMapperImpl; -import at.gv.egiz.bku.slcommands.SLCommandFactory; +import at.gv.egiz.bku.slcommands.SLMarshallerFactory; import at.gv.egiz.bku.slcommands.SLResult; import at.gv.egiz.bku.slexceptions.SLBindingException; import at.gv.egiz.bku.slexceptions.SLCommandException; import at.gv.egiz.bku.slexceptions.SLException; import at.gv.egiz.bku.slexceptions.SLRuntimeException; +import at.gv.egiz.bku.slexceptions.SLVersionException; import at.gv.egiz.bku.utils.DebugOutputStream; import at.gv.egiz.bku.utils.DebugWriter; -import at.gv.egiz.marshal.MarshallerFactory; -import javax.xml.bind.PropertyException; /** * This class serves as an abstract base class for the implementation of a @@ -90,20 +90,18 @@ public abstract class SLResultImpl implements SLResult { return resultingMimeType; } - private Marshaller getMarshaller() { - try { - JAXBContext context = SLCommandFactory.getInstance().getJaxbContext(); - Marshaller marshaller = MarshallerFactory.createMarshaller(context, true); - return marshaller; - } catch (JAXBException e) { - log.fatal("Failed to marshall error response.", e); - throw new SLRuntimeException("Failed to marshall error response.", e); - } + @Override + public void writeTo(Result result, boolean fragment) { + writeTo(result, null, false); } + @Override + public abstract void writeTo(Result result, Templates templates, boolean fragment); + private TransformerHandler getTransformerHandler(Templates templates, Result result) throws SLException { try { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); + transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(templates); transformerHandler.setResult(result); return transformerHandler; @@ -119,12 +117,6 @@ public abstract class SLResultImpl implements SLResult { } } - @Override - public void writeTo(Result result) { - writeTo(result, null); - } - - /** * Writes the given response to the SAX result using * the given transform templates. @@ -133,7 +125,7 @@ public abstract class SLResultImpl implements SLResult { * @param result * @param templates */ - protected void writeTo(JAXBElement response, Result result, Templates templates) { + protected void writeTo(JAXBElement response, Result result, Templates templates, boolean fragment) { DebugWriter dw = null; DebugOutputStream ds = null; @@ -154,11 +146,11 @@ public abstract class SLResultImpl implements SLResult { try { transformerHandler = getTransformerHandler(templates, result); } catch (SLException e) { - writeErrorTo(e, result, templates); + writeErrorTo(e, result, templates, fragment); } } - Marshaller marshaller = getMarshaller(); + Marshaller marshaller = SLMarshallerFactory.getInstance().createMarshaller(true); try { if (transformerHandler != null) { marshaller.marshal(response, transformerHandler); @@ -168,7 +160,7 @@ public abstract class SLResultImpl implements SLResult { } catch (JAXBException e) { log.info("Failed to marshall " + response.getName() + " result." , e); SLCommandException commandException = new SLCommandException(4000); - writeErrorTo(commandException, result, templates); + writeErrorTo(commandException, result, templates, fragment); } if (ds != null) { @@ -185,7 +177,7 @@ public abstract class SLResultImpl implements SLResult { } - protected void writeTo(Node node, Result result, Templates templates) { + protected void writeTo(Node node, Result result, Templates templates, boolean fragment) { DebugWriter dw = null; DebugOutputStream ds = null; @@ -205,24 +197,30 @@ public abstract class SLResultImpl implements SLResult { try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); + if (fragment) { + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + } transformer.transform(new DOMSource(node), result); } catch (TransformerConfigurationException e) { log.error("Failed to create Transformer.", e); - writeErrorTo(new SLException(4000), result, null); + writeErrorTo(new SLException(4000), result, null, fragment); } catch (TransformerException e) { log.error("Failed to transform result.", e); - writeErrorTo(new SLException(4000), result, null); + writeErrorTo(new SLException(4000), result, null, fragment); } } else { try { Transformer transformer = templates.newTransformer(); + if (fragment) { + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + } transformer.transform(new DOMSource(node), result); } catch (TransformerConfigurationException e) { log.info("Failed to create transformer.", e); - writeErrorTo(new SLException(2008), result, templates); + writeErrorTo(new SLException(2008), result, templates, fragment); } catch (TransformerException e) { log.error("Failed to transform result.", e); - writeErrorTo(new SLException(2008), result, templates); + writeErrorTo(new SLException(2008), result, templates, fragment); } } @@ -240,11 +238,11 @@ public abstract class SLResultImpl implements SLResult { } - protected void writeErrorTo(SLException slException, Result result, Templates templates) { - writeErrorTo(slException, result, templates, Locale.getDefault()); + protected void writeErrorTo(SLException slException, Result result, Templates templates, boolean fragment) { + writeErrorTo(slException, result, templates, Locale.getDefault(), fragment); } - protected void writeErrorTo(SLException slException, Result result, Templates templates, Locale locale) { + protected void writeErrorTo(SLException slException, Result result, Templates templates, Locale locale, boolean fragment) { TransformerHandler transformerHandler = null; if (templates != null) { @@ -256,13 +254,33 @@ public abstract class SLResultImpl implements SLResult { } } - ObjectFactory factory = new ObjectFactory(); - ErrorResponseType responseType = factory.createErrorResponseType(); - responseType.setErrorCode(slException.getErrorCode()); - responseType.setInfo(slException.getLocalizedMessage(locale)); - JAXBElement response = factory.createErrorResponse(responseType); + Object response; + + Marshaller marshaller; + if (slException instanceof SLVersionException + && ("http://www.buergerkarte.at/namespaces/securitylayer/20020225#" + .equals(((SLVersionException) slException).getNamespaceURI()) || + "http://www.buergerkarte.at/namespaces/securitylayer/20020831#" + .equals(((SLVersionException) slException).getNamespaceURI()))) { + // issue ErrorResponse in the legacy namespace + at.buergerkarte.namespaces.securitylayer._20020225_.ObjectFactory factory + = new at.buergerkarte.namespaces.securitylayer._20020225_.ObjectFactory(); + at.buergerkarte.namespaces.securitylayer._20020225_.ErrorResponseType errorResponseType = factory + .createErrorResponseType(); + errorResponseType.setErrorCode(BigInteger.valueOf(slException + .getErrorCode())); + errorResponseType.setInfo(slException.getLocalizedMessage(locale)); + response = factory.createErrorResponse(errorResponseType); + marshaller = SLMarshallerFactory.getInstance().createLegacyMarshaller(true, fragment); + } else { + ObjectFactory factory = new ObjectFactory(); + ErrorResponseType responseType = factory.createErrorResponseType(); + responseType.setErrorCode(slException.getErrorCode()); + responseType.setInfo(slException.getLocalizedMessage(locale)); + response = factory.createErrorResponse(responseType); + marshaller = SLMarshallerFactory.getInstance().createMarshaller(true, fragment); + } - Marshaller marshaller = getMarshaller(); try { if (transformerHandler != null) { marshaller.marshal(response, transformerHandler); diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java index b64306aa..2088a684 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java @@ -81,7 +81,6 @@ import at.gv.egiz.bku.viewer.ValidationException; import at.gv.egiz.bku.viewer.Validator; import at.gv.egiz.bku.viewer.ValidatorFactory; import at.gv.egiz.dom.DOMUtils; -import at.gv.egiz.marshal.NamespacePrefix; import at.gv.egiz.marshal.NamespacePrefixMapperImpl; import at.gv.egiz.slbinding.impl.XMLContentType; import javax.xml.namespace.NamespaceContext; diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java index 9182e824..26ddb153 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java @@ -16,7 +16,6 @@ */ package at.gv.egiz.bku.slcommands.impl.xsect; -import at.gv.egiz.stal.HashDataInput; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -31,9 +30,7 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; @@ -87,8 +84,6 @@ import at.gv.egiz.bku.utils.urldereferencer.StreamData; import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; import at.gv.egiz.dom.DOMUtils; -import at.gv.egiz.marshal.NamespacePrefix; -import at.gv.egiz.marshal.NamespacePrefixMapperImpl; import at.gv.egiz.slbinding.impl.XMLContentType; import at.gv.egiz.stal.STAL; import at.gv.egiz.xades.QualifyingPropertiesException; @@ -327,6 +322,8 @@ public class Signature { */ public void buildXMLSignature() throws SLCommandException { + String signatureId = ctx.getIdValueFactory().createIdValue("Signature"); + List objects = new ArrayList(); List references = new ArrayList(); @@ -340,7 +337,7 @@ public class Signature { } } - addXAdESObjectAndReference(objects, references); + addXAdESObjectAndReference(objects, references, signatureId); XMLSignatureFactory signatureFactory = ctx.getSignatureFactory(); AlgorithmMethodFactory algorithmMethodFactory = ctx.getAlgorithmMethodFactory(); @@ -369,7 +366,6 @@ public class Signature { ki = kif.newKeyInfo(Collections.singletonList(x509Data)); } - String signatureId = ctx.getIdValueFactory().createIdValue("Signature"); String signatureValueId = ctx.getIdValueFactory().createIdValue("SignatureValue"); xmlSignature = signatureFactory.newXMLSignature(si, ki, objects, signatureId, signatureValueId); @@ -588,7 +584,7 @@ public class Signature { * @param references * the list of ds:References to add the created * ds:Reference to - * + * @param signatureId TODO * @throws SLCommandException * if creating and adding the XAdES * QualifyingProperties fails @@ -596,7 +592,7 @@ public class Signature { * if objects or references is * null */ - private void addXAdESObjectAndReference(List objects, List references) throws SLCommandException { + private void addXAdESObjectAndReference(List objects, List references, String signatureId) throws SLCommandException { QualifyingPropertiesFactory factory = QualifyingPropertiesFactory.getInstance(); @@ -630,9 +626,11 @@ public class Signature { } } + String target = "#" + signatureId; + JAXBElement qualifyingProperties; try { - qualifyingProperties = factory.createQualifyingProperties111(date, signingCertificates, idValue, dataObjectFormats); + qualifyingProperties = factory.createQualifyingProperties111(target, date, signingCertificates, idValue, dataObjectFormats); } catch (QualifyingPropertiesException e) { log.error("Failed to create QualifyingProperties.", e); throw new SLCommandException(4000); -- cgit v1.2.3 From 68941b57df2caeead67a5bede2ef5a635d07db32 Mon Sep 17 00:00:00 2001 From: mcentner Date: Wed, 11 Nov 2009 15:51:08 +0000 Subject: Added support for SHA-256 and partial support for e-card G3, BELPIC and Italian cards. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@540 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../at/gv/egiz/bku/slcommands/impl/STALHelper.java | 26 ++++++- .../impl/xsect/AlgorithmMethodFactoryImpl.java | 86 ++++++++++++++++------ .../bku/slcommands/impl/xsect/STALProvider.java | 6 +- .../egiz/bku/slcommands/impl/xsect/Signature.java | 23 ++++-- 4 files changed, 111 insertions(+), 30 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java index 0c7ce3f5..e903c608 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/STALHelper.java @@ -18,8 +18,15 @@ package at.gv.egiz.bku.slcommands.impl; import iaik.asn1.CodingException; import iaik.asn1.DerCoder; +import iaik.utils.Base64OutputStream; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.StringWriter; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; @@ -174,7 +181,24 @@ public class STALHelper { try { certificates.add((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(cert))); } catch (CertificateException e) { - log.info("Failed to decode certificate.", e); + if (log.isDebugEnabled()) { + ByteArrayOutputStream certDump = new ByteArrayOutputStream(); + OutputStreamWriter writer = new OutputStreamWriter(certDump); + try { + writer.write("-----BEGIN CERTIFICATE-----\n"); + writer.flush(); + Base64OutputStream b64os = new Base64OutputStream(certDump); + b64os.write(cert); + b64os.flush(); + writer.write("\n-----END CERTIFICATE-----"); + writer.flush(); + } catch (IOException e1) { + log.info("Failed to decode certificate.", e); + } + log.debug("Failed to decode certificate.\n" + certDump.toString(), e); + } else { + log.info("Failed to decode certificate.", e); + } throw new SLCommandException(4000, SLExceptionMessages.EC4000_UNCLASSIFIED_INFOBOX_INVALID, new Object[] { "Certificates" }); diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java index 6b963465..061fe707 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java @@ -16,18 +16,23 @@ */ package at.gv.egiz.bku.slcommands.impl.xsect; -import iaik.xml.crypto.XmldsigMore; - -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; - -import javax.xml.crypto.dsig.CanonicalizationMethod; -import javax.xml.crypto.dsig.DigestMethod; -import javax.xml.crypto.dsig.SignatureMethod; -import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; -import javax.xml.crypto.dsig.spec.DigestMethodParameterSpec; -import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; +import iaik.security.ecc.interfaces.ECDSAParams; +import iaik.xml.crypto.XmldsigMore; + +import java.security.InvalidAlgorithmParameterException; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.ECParameterSpec; + +import javax.xml.crypto.dsig.CanonicalizationMethod; +import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.dsig.SignatureMethod; +import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; +import javax.xml.crypto.dsig.spec.DigestMethodParameterSpec; +import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; /** * An implementation of the AlgorithmMethod factory that uses the signing @@ -40,7 +45,12 @@ public class AlgorithmMethodFactoryImpl implements AlgorithmMethodFactory { /** * The signature algorithm URI. */ - private String signatureAlgorithmURI; + private String signatureAlgorithmURI; + + /** + * the digest algorithm URI. + */ + private String digestAlgorithmURI = DigestMethod.SHA1; /** * The algorithm parameters for the signature algorithm. @@ -51,23 +61,55 @@ public class AlgorithmMethodFactoryImpl implements AlgorithmMethodFactory { * Creates a new AlgrithmMethodFactory with the given * signingCertificate. * - * @param siginingCertificate + * @param signingCertificate * * @throws NoSuchAlgorithmException * if the public key algorithm of the given * signingCertificate is not supported */ - public AlgorithmMethodFactoryImpl(X509Certificate siginingCertificate) + public AlgorithmMethodFactoryImpl(X509Certificate signingCertificate) throws NoSuchAlgorithmException { - - String algorithm = siginingCertificate.getPublicKey().getAlgorithm(); + + PublicKey publicKey = signingCertificate.getPublicKey(); + String algorithm = publicKey.getAlgorithm(); if ("DSA".equals(algorithm)) { signatureAlgorithmURI = SignatureMethod.DSA_SHA1; - } else if ("RSA".equals(algorithm)) { - signatureAlgorithmURI = SignatureMethod.RSA_SHA1; - } else if (("EC".equals(algorithm)) || ("ECDSA".equals(algorithm))) { - signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA1; + } else if ("RSA".equals(algorithm)) { + + int keyLength = 0; + if (publicKey instanceof RSAPublicKey) { + keyLength = ((RSAPublicKey) publicKey).getModulus().bitLength(); + } + + if (keyLength >= 2048) { + signatureAlgorithmURI = XmldsigMore.SIGNATURE_RSA_SHA256; + digestAlgorithmURI = DigestMethod.SHA256; + } else { + signatureAlgorithmURI = SignatureMethod.RSA_SHA1; + } + + } else if (("EC".equals(algorithm)) || ("ECDSA".equals(algorithm))) { + + int fieldSize = 0; + if (publicKey instanceof iaik.security.ecc.ecdsa.ECPublicKey) { + ECDSAParams params = ((iaik.security.ecc.ecdsa.ECPublicKey) publicKey).getParameter(); + fieldSize = params.getG().getCurve().getField().getSize().bitLength(); + } else if (publicKey instanceof ECPublicKey) { + ECParameterSpec params = ((ECPublicKey) publicKey).getParams(); + fieldSize = params.getCurve().getField().getFieldSize(); + } + + if (fieldSize < 256) { + signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA1; + } else if (fieldSize < 512) { + signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA256; + digestAlgorithmURI = DigestMethod.SHA256; + } else { + signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA512; + digestAlgorithmURI = DigestMethod.SHA512; + } + } else { throw new NoSuchAlgorithmException("Public key algorithm '" + algorithm + "' not supported."); @@ -104,7 +146,7 @@ public class AlgorithmMethodFactoryImpl implements AlgorithmMethodFactory { throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { return signatureContext.getSignatureFactory().newDigestMethod( - DigestMethod.SHA1, (DigestMethodParameterSpec) null); + digestAlgorithmURI, (DigestMethodParameterSpec) null); } /* diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java index 0ab30530..42c6a4c5 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java @@ -49,7 +49,11 @@ public class STALProvider extends Provider { map.put("Signature." + SignatureMethod.RSA_SHA1, IMPL_PACKAGE_NAME + ".STALSignature"); map.put("Signature." + XmldsigMore.SIGNATURE_ECDSA_SHA1, - IMPL_PACKAGE_NAME + ".STALSignature"); + IMPL_PACKAGE_NAME + ".STALSignature"); + map.put("Signature." + XmldsigMore.SIGNATURE_RSA_SHA256, + IMPL_PACKAGE_NAME + ".STALSignature"); + map.put("Signature." + XmldsigMore.SIGNATURE_ECDSA_SHA256, + IMPL_PACKAGE_NAME + ".STALSignature"); AccessController.doPrivileged(new PrivilegedAction() { @Override diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java index 26ddb153..3cebb6a3 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java @@ -628,9 +628,20 @@ public class Signature { String target = "#" + signatureId; + DigestMethod dm; + try { + dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); + } catch (NoSuchAlgorithmException e) { + log.error("Failed to get DigestMethod algorithm.", e); + throw new SLCommandException(4006); + } catch (InvalidAlgorithmParameterException e) { + log.error("Failed to get DigestMethod algorithm.", e); + throw new SLCommandException(4006); + } + JAXBElement qualifyingProperties; try { - qualifyingProperties = factory.createQualifyingProperties111(target, date, signingCertificates, idValue, dataObjectFormats); + qualifyingProperties = factory.createQualifyingProperties111(target, date, signingCertificates, idValue, dataObjectFormats, dm); } catch (QualifyingPropertiesException e) { log.error("Failed to create QualifyingProperties.", e); throw new SLCommandException(4000); @@ -665,7 +676,10 @@ public class Signature { String referenceURI = "#xmlns(xades=http://uri.etsi.org/01903/v1.1.1%23)%20xpointer(id('" + objectIdValue + "')/child::xades:QualifyingProperties/child::xades:SignedProperties)"; - DigestMethod dm; + + String referenceIdValue = ctx.getIdValueFactory().createIdValue("Reference"); + String referenceType = QualifyingPropertiesFactory.SIGNED_PROPERTIES_REFERENCE_TYPE_V1_1_1; + try { dm = ctx.getAlgorithmMethodFactory().createDigestMethod(ctx); } catch (NoSuchAlgorithmException e) { @@ -675,10 +689,7 @@ public class Signature { log.error("Failed to get DigestMethod algorithm.", e); throw new SLCommandException(4006); } - - String referenceIdValue = ctx.getIdValueFactory().createIdValue("Reference"); - String referenceType = QualifyingPropertiesFactory.SIGNED_PROPERTIES_REFERENCE_TYPE_V1_1_1; - + Reference reference = ctx.getSignatureFactory().newReference(referenceURI, dm, null, referenceType, referenceIdValue); references.add(reference); -- cgit v1.2.3 From 5406f90edc47fecff0ff9a00b64b8740b6ac02f8 Mon Sep 17 00:00:00 2001 From: mcentner Date: Fri, 13 Nov 2009 10:28:00 +0000 Subject: SHA-2 disabled for the moment. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@542 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../impl/xsect/AlgorithmMethodFactoryImpl.java | 19 ++++++++++++------- .../egiz/bku/slcommands/impl/xsect/STALProvider.java | 3 +++ 2 files changed, 15 insertions(+), 7 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java index 061fe707..8391e450 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java @@ -41,7 +41,12 @@ import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; * @author mcentner */ public class AlgorithmMethodFactoryImpl implements AlgorithmMethodFactory { - + + /** + * Use SHA-2? + */ + private static boolean SHA2 = false; + /** * The signature algorithm URI. */ @@ -82,7 +87,7 @@ public class AlgorithmMethodFactoryImpl implements AlgorithmMethodFactory { keyLength = ((RSAPublicKey) publicKey).getModulus().bitLength(); } - if (keyLength >= 2048) { + if (SHA2 && keyLength >= 2048) { signatureAlgorithmURI = XmldsigMore.SIGNATURE_RSA_SHA256; digestAlgorithmURI = DigestMethod.SHA256; } else { @@ -100,14 +105,14 @@ public class AlgorithmMethodFactoryImpl implements AlgorithmMethodFactory { fieldSize = params.getCurve().getField().getFieldSize(); } - if (fieldSize < 256) { - signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA1; - } else if (fieldSize < 512) { + if (SHA2 && fieldSize >= 512) { + signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA512; + digestAlgorithmURI = DigestMethod.SHA512; + } else if (SHA2 && fieldSize >= 256) { signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA256; digestAlgorithmURI = DigestMethod.SHA256; } else { - signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA512; - digestAlgorithmURI = DigestMethod.SHA512; + signatureAlgorithmURI = XmldsigMore.SIGNATURE_ECDSA_SHA1; } } else { diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java index 42c6a4c5..9fb9a3f1 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java @@ -54,6 +54,9 @@ public class STALProvider extends Provider { IMPL_PACKAGE_NAME + ".STALSignature"); map.put("Signature." + XmldsigMore.SIGNATURE_ECDSA_SHA256, IMPL_PACKAGE_NAME + ".STALSignature"); + map.put("Signature." + XmldsigMore.SIGNATURE_ECDSA_SHA512, + IMPL_PACKAGE_NAME + ".STALSignature"); + AccessController.doPrivileged(new PrivilegedAction() { @Override -- cgit v1.2.3 From b7dd29046e232e4d42623655efc28965cce942b8 Mon Sep 17 00:00:00 2001 From: clemenso Date: Fri, 13 Nov 2009 15:13:21 +0000 Subject: git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@546 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java index 2088a684..89124d16 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java @@ -293,8 +293,7 @@ public class DataObject { } } else { - log.info("MIME media type '" + mediaType + "' is not a valid digest input."); - throw new SLViewerException(5001); + log.debug("MIME media type '" + mediaType + "' is not a s/valid/SUPPORTED digest input, omitting validation."); } } -- cgit v1.2.3 From 5af9b75dccc1b52d1382fe0f2df30affd509f5b9 Mon Sep 17 00:00:00 2001 From: clemenso Date: Tue, 24 Nov 2009 18:48:00 +0000 Subject: Filenames derived from reference URI git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@553 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../slcommands/impl/DataObjectHashDataInput.java | 6 ++ .../egiz/bku/slcommands/impl/xsect/DataObject.java | 88 ++++++++++++++++++++-- 2 files changed, 86 insertions(+), 8 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java index 1a9b56fb..57358ba0 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/DataObjectHashDataInput.java @@ -50,4 +50,10 @@ public class DataObjectHashDataInput implements HashDataInput { return HttpUtil.getCharset(dataObject.getMimeType(), false); } + @Override + public String getFilename() { + //TODO obtain filename from dataObject, if not set return null or get filename (extension!) from mimetype + return dataObject.getFilename(); + } + } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java index 89124d16..6e84081e 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java @@ -49,8 +49,6 @@ import javax.xml.crypto.dsig.spec.XPathType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.w3._2000._09.xmldsig_.TransformType; -import org.w3._2000._09.xmldsig_.TransformsType; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMException; import org.w3c.dom.Document; @@ -71,6 +69,7 @@ import at.buergerkarte.namespaces.securitylayer._1.DataObjectInfoType; import at.buergerkarte.namespaces.securitylayer._1.MetaInfoType; import at.buergerkarte.namespaces.securitylayer._1.TransformsInfoType; import at.gv.egiz.bku.binding.HttpUtil; +import at.gv.egiz.bku.gui.viewer.MimeTypes; import at.gv.egiz.bku.slexceptions.SLCommandException; import at.gv.egiz.bku.slexceptions.SLRequestException; import at.gv.egiz.bku.slexceptions.SLRuntimeException; @@ -81,11 +80,11 @@ import at.gv.egiz.bku.viewer.ValidationException; import at.gv.egiz.bku.viewer.Validator; import at.gv.egiz.bku.viewer.ValidatorFactory; import at.gv.egiz.dom.DOMUtils; -import at.gv.egiz.marshal.NamespacePrefixMapperImpl; import at.gv.egiz.slbinding.impl.XMLContentType; -import javax.xml.namespace.NamespaceContext; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; +import java.io.File; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; /** * This class represents a DataObject of an XML-Signature @@ -184,7 +183,9 @@ public class DataObject { * An optional description of the digest input. */ private String description; - + + private String filename; + /** * Creates a new instance. * @@ -230,6 +231,10 @@ public class DataObject { return mimeType; } + public String getFilename() { + return filename; + } + /** * @return the description */ @@ -336,7 +341,74 @@ public class DataObject { } // other values are not allowed by the schema and are therefore ignored - + + this.filename = deriveFilename(); + } + + /** + * Extract filename from reference URI + * or propose reference Id with an apropriate (mime-type) file extension + * + * @return if neither reference nor id can be extracted return null (or data.extension?) + */ + private String deriveFilename() { + + String filename = null; + + if (reference != null) { + if (reference.getURI() != null && !"".equals(reference.getURI())) { + try { + log.info("deriving filename from reference URI " + reference.getURI()); + URI refURI = new URI(reference.getURI()); + + if (refURI.isOpaque()) { + // could check scheme component, but also allow other schemes (e.g. testlocal) + log.trace("opaque reference URI, use scheme-specific part as filename"); + filename = refURI.getSchemeSpecificPart(); + if (!hasExtension(filename)) { + filename += MimeTypes.getExtension(mimeType); + } + // else hierarchical URI: + // for shorthand xpointer use fragment as filename, + // for any other xpointer use reference Id and + // for any other hierarchical (absolute or relative) use filename (ignore fragment, see xmldsig section 4.3.3.2: fragments not recommendet) + } else if ("".equals(refURI.getPath()) && + refURI.getFragment() != null && + refURI.getFragment().indexOf('(') < 0) { // exclude (schemebased) xpointer expressions + log.trace("fragment (shorthand xpointer) URI, use fragment as filename"); + filename = refURI.getFragment(); + if(!hasExtension(filename)) { + filename += MimeTypes.getExtension(mimeType); + } + } else if (!"".equals(refURI.getPath())) { + log.trace("hierarchical URI with path component, use path as filename"); + File refFile = new File(refURI.getPath()); + filename = refFile.getName(); + if(!hasExtension(filename)) { + filename += MimeTypes.getExtension(mimeType); + } + } else { + log.info("failed to derive filename from URI '" + refURI + "', derive filename from reference ID"); + filename = reference.getId() + MimeTypes.getExtension(mimeType); + } + } catch (URISyntaxException ex) { + log.error("failed to derive filename from invalid URI " + ex.getMessage()); + filename = reference.getId() + MimeTypes.getExtension(mimeType); + } + } else { + log.info("same-document URI, derive filename from reference ID"); + filename = reference.getId() + MimeTypes.getExtension(mimeType); + } + } else { + log.error("failed to derive filename, no reference created"); + } + log.debug("derived filename for reference " + reference.getId() + ": " + filename); + return filename; + } + + private static boolean hasExtension(String filename) { + int extDelimiterInd = filename.lastIndexOf('.'); + return extDelimiterInd >= 0 && extDelimiterInd >= filename.length() - 4; } private byte[] getTransformsBytes(at.gv.egiz.slbinding.impl.TransformsInfoType ti) { -- cgit v1.2.3 From fb20464dc8dc024568b439c460485c700137e0e2 Mon Sep 17 00:00:00 2001 From: clemenso Date: Tue, 29 Dec 2009 09:39:56 +0000 Subject: log level for debug messages git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@562 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java index 6e84081e..a57a11dd 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java @@ -388,7 +388,7 @@ public class DataObject { filename += MimeTypes.getExtension(mimeType); } } else { - log.info("failed to derive filename from URI '" + refURI + "', derive filename from reference ID"); + log.debug("failed to derive filename from URI '" + refURI + "', derive filename from reference ID"); filename = reference.getId() + MimeTypes.getExtension(mimeType); } } catch (URISyntaxException ex) { @@ -396,7 +396,7 @@ public class DataObject { filename = reference.getId() + MimeTypes.getExtension(mimeType); } } else { - log.info("same-document URI, derive filename from reference ID"); + log.debug("same-document URI, derive filename from reference ID"); filename = reference.getId() + MimeTypes.getExtension(mimeType); } } else { -- cgit v1.2.3 From 4a334069beb85654e3cb35aef7e4508e04127036 Mon Sep 17 00:00:00 2001 From: mcentner Date: Tue, 26 Jan 2010 16:22:56 +0000 Subject: MOCCA 1.2.11 with SHA-2 enabled. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/branches/mocca-1.2.11-sha2/mocca-1.2.11@599 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../impl/AbstractInfoboxCommandImpl.java | 21 ++++- .../egiz/bku/slcommands/impl/InfoboxFactory.java | 95 ++++------------------ 2 files changed, 37 insertions(+), 79 deletions(-) (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java index 8a7edb71..b8e4030d 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/AbstractInfoboxCommandImpl.java @@ -32,6 +32,25 @@ public abstract class AbstractInfoboxCommandImpl extends SLCommandImpl { * The infobox implementation. */ protected Infobox infobox; + + /** + * The infobox factory. + */ + protected InfoboxFactory infoboxFactory; + + /** + * @return the infoboxFactory + */ + public InfoboxFactory getInfoboxFactory() { + return infoboxFactory; + } + + /** + * @param infoboxFactory the infoboxFactory to set + */ + public void setInfoboxFactory(InfoboxFactory infoboxFactory) { + this.infoboxFactory = infoboxFactory; + } @Override public void init(SLCommandContext ctx, Object request) @@ -40,7 +59,7 @@ public abstract class AbstractInfoboxCommandImpl extends SLCommandImpl { String infoboxIdentifier = getInfoboxIdentifier(getRequestValue()); - infobox = InfoboxFactory.getInstance().createInfobox(infoboxIdentifier); + infobox = infoboxFactory.createInfobox(infoboxIdentifier); } /** diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java index e9736f6d..fdf94297 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/InfoboxFactory.java @@ -17,7 +17,6 @@ package at.gv.egiz.bku.slcommands.impl; import java.util.HashMap; -import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -39,68 +38,24 @@ public class InfoboxFactory { private static Log log = LogFactory.getLog(InfoboxFactory.class); /** - * The singleton instance of this InfoboxFactory. + * The mapping of Infobox name to concrete Infobox factory. */ - private static InfoboxFactory instance; - - /** - * @return an instance of this InfoboxFactory - */ - public synchronized static InfoboxFactory getInstance() { - if (instance == null) { - instance = new InfoboxFactory(); - } - return instance; - } - - /** - * The mapping of infobox identifier to implementation class. - */ - private HashMap> implementations; - - /** - * Private constructor. - */ - private InfoboxFactory() { - } - - /** - * Sets the mapping of infobox identifier to implementation class name. - * - * @param infoboxImplMap - * a mapping of infobox identifiers to implementation class names - * - * @throws ClassNotFoundException - * if implementation class is not an instance of {@link Infobox} - */ - @SuppressWarnings("unchecked") - public void setInfoboxImpl(Map infoboxImplMap) throws ClassNotFoundException { - HashMap> implMap = new HashMap>(); - ClassLoader cl = getClass().getClassLoader(); - for (String key : infoboxImplMap.keySet()) { - Class impl = (Class) cl.loadClass(infoboxImplMap.get(key)); - log.debug("Registering infobox '" + key + "' implementation '" + impl.getCanonicalName() + "'."); - implMap.put(key, impl); - } - implementations = implMap; - } - + private HashMap infoboxFactories = new HashMap(); + /** - * Returns the configured implementation class for the given - * infoboxIdentifier. - * - * @param infoboxIdentifier - * the infobox identifier - * - * @return the implementation class for the given infobox identifier or - * null if there is no implementation class configured + * @param infoboxFactories the infoboxFactories to set */ - public Class getImplClass(String infoboxIdentifier) { - if (implementations != null) { - return implementations.get(infoboxIdentifier); - } else { - return null; + public void setInfoboxFactories( + HashMap factories) { + if (log.isDebugEnabled()) { + StringBuilder sb = new StringBuilder(); + sb.append("Registered infobox factories for"); + for (String name : factories.keySet()) { + sb.append("\n " + name + " : " + factories.get(name).getClass()); + } + log.debug(sb); } + this.infoboxFactories = factories; } /** @@ -119,31 +74,15 @@ public class InfoboxFactory { */ public Infobox createInfobox(String infoboxIdentifier) throws SLCommandException, SLRuntimeException { - Class implClass = getImplClass(infoboxIdentifier); - if (implClass == null) { - // infobox not supported + AbstractInfoboxFactory factory = infoboxFactories.get(infoboxIdentifier); + if (factory == null) { log.info("Unsupported infobox '" + infoboxIdentifier + "."); throw new SLCommandException(4002, SLExceptionMessages.EC4002_INFOBOX_UNKNOWN, new Object[] { infoboxIdentifier }); } - // try to instantiate - Infobox infobox; - try { - infobox = implClass.newInstance(); - log.debug("Infobox '" + infobox.getIdentifier() + "' created."); - } catch (InstantiationException e) { - // unexpected error - log.error("Failed to instantiate infobox implementation.", e); - throw new SLRuntimeException(e); - } catch (IllegalAccessException e) { - // unexpected error - log.error("Failed to instantiate infobox implementation.", e); - throw new SLRuntimeException(e); - } - - return infobox; + return factory.createInfobox(); } -- cgit v1.2.3