Search in sources :

Example 31 with WSMarshaller

use of org.openecard.ws.marshal.WSMarshaller in project open-ecard by ecsec.

the class MiddlewareConfig method getCardInfoTemplate.

/**
 * Returns the CardInfo-Template as CardInfoType.
 *
 * @return CardInfo-Template or {@code null} if template can not be parsed.
 */
@Nonnull
private synchronized CardInfoType getCardInfoTemplate() {
    CardInfoType cardInfo;
    try {
        WSMarshaller m = MARSHALLER.deref();
        assert (m != null);
        Document doc = CIF_DOC.deref();
        cardInfo = m.unmarshal(doc, CardInfoType.class).getValue();
        return cardInfo;
    } catch (WSMarshallerException ex) {
        String msg = "Can not parse CardInfo-Document.";
        LOG.error(msg, ex);
        throw new RuntimeException(CARD_IMAGE_PATH, ex);
    } catch (InterruptedException ex) {
        String msg = "Shutdown requested while retrieving CIF template.";
        LOG.debug(msg);
        throw new RuntimeException(msg);
    } catch (NullPointerException ex) {
        String msg = "Marshaller and/ or CIF Template could not be loaded correctly.";
        LOG.error(msg, ex);
        throw new RuntimeException(msg);
    }
}
Also used : CardInfoType(iso.std.iso_iec._24727.tech.schema.CardInfoType) WSMarshallerException(org.openecard.ws.marshal.WSMarshallerException) WSMarshaller(org.openecard.ws.marshal.WSMarshaller) Document(org.w3c.dom.Document) Nonnull(javax.annotation.Nonnull)

Example 32 with WSMarshaller

use of org.openecard.ws.marshal.WSMarshaller in project open-ecard by ecsec.

the class PACETest method executePACE_PIN.

@Test(enabled = false)
public void executePACE_PIN() throws UnsupportedDataTypeException, JAXBException, SAXException, WSMarshallerException {
    ClientEnv env = new ClientEnv();
    MessageDispatcher dispatcher = new MessageDispatcher(env);
    IFD ifd = new IFD();
    SwingUserConsent gui = new SwingUserConsent(new SwingDialogWrapper());
    ifd.setGUI(gui);
    env.setIFD(ifd);
    env.setDispatcher(dispatcher);
    ifd.addProtocol(ECardConstants.Protocol.PACE, new PACEProtocolFactory());
    EstablishContext eCtx = new EstablishContext();
    byte[] ctxHandle = ifd.establishContext(eCtx).getContextHandle();
    ListIFDs listIFDs = new ListIFDs();
    listIFDs.setContextHandle(ctxHandle);
    String ifdName = ifd.listIFDs(listIFDs).getIFDName().get(0);
    Connect connect = new Connect();
    connect.setContextHandle(ctxHandle);
    connect.setIFDName(ifdName);
    connect.setSlot(BigInteger.ZERO);
    byte[] slotHandle = ifd.connect(connect).getSlotHandle();
    // PinID: 02 = CAN, 03 = PIN
    String xmlCall = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<iso:EstablishChannel xmlns:iso=\"urn:iso:std:iso-iec:24727:tech:schema\">\n" + "  <iso:SlotHandle>" + ByteUtils.toHexString(slotHandle) + "</iso:SlotHandle>\n" + "  <iso:AuthenticationProtocolData Protocol=\"urn:oid:0.4.0.127.0.7.2.2.4\">\n" + "    <iso:PinID>02</iso:PinID>\n" + "    <iso:CHAT>7f4c12060904007f0007030102025305300301ffb7</iso:CHAT>\n" + // Remove PIN element to active the GUI
    "    <iso:PIN>142390</iso:PIN>\n" + // + "    <iso:PIN>123456</iso:PIN>\n"
    "  </iso:AuthenticationProtocolData>\n" + "</iso:EstablishChannel>";
    WSMarshaller m = WSMarshallerFactory.createInstance();
    EstablishChannel eCh = (EstablishChannel) m.unmarshal(m.str2doc(xmlCall));
    EstablishChannelResponse eChR = ifd.establishChannel(eCh);
    LOG.info("PACE result: {}", eChR.getResult().getResultMajor());
    try {
        LOG.info("{}", eChR.getResult().getResultMinor());
        LOG.info("{}", eChR.getResult().getResultMessage().getValue());
    } catch (Exception ignore) {
    }
}
Also used : ListIFDs(iso.std.iso_iec._24727.tech.schema.ListIFDs) IFD(org.openecard.ifd.scio.IFD) Connect(iso.std.iso_iec._24727.tech.schema.Connect) EstablishChannelResponse(iso.std.iso_iec._24727.tech.schema.EstablishChannelResponse) WSMarshaller(org.openecard.ws.marshal.WSMarshaller) JAXBException(javax.xml.bind.JAXBException) SAXException(org.xml.sax.SAXException) UnsupportedDataTypeException(javax.activation.UnsupportedDataTypeException) WSMarshallerException(org.openecard.ws.marshal.WSMarshallerException) ClientEnv(org.openecard.common.ClientEnv) MessageDispatcher(org.openecard.transport.dispatcher.MessageDispatcher) SwingDialogWrapper(org.openecard.gui.swing.SwingDialogWrapper) EstablishChannel(iso.std.iso_iec._24727.tech.schema.EstablishChannel) SwingUserConsent(org.openecard.gui.swing.SwingUserConsent) EstablishContext(iso.std.iso_iec._24727.tech.schema.EstablishContext) Test(org.testng.annotations.Test)

Example 33 with WSMarshaller

use of org.openecard.ws.marshal.WSMarshaller in project open-ecard by ecsec.

the class CryptoMarkerTypeTest method testCryptoMarkerType.

/**
 * Simple test for CryptoMarkerType.
 * After creating the CryptoMarker of the PrK.CH.AUT_signPKCS1_V1_5 DID in the the
 * ESIGN application of the EGK we check if the get-methods return the expected values.
 *
 * @throws Exception
 *             when something in this test went unexpectedly wrong
 */
@Test
public void testCryptoMarkerType() throws Exception {
    WSMarshaller marshaller = WSMarshallerFactory.createInstance();
    // setup the iso cryptoMarker type
    iso.std.iso_iec._24727.tech.schema.CryptoMarkerType cryptoMarker = new iso.std.iso_iec._24727.tech.schema.CryptoMarkerType();
    cryptoMarker.setProtocol("urn:oid:1.3.162.15480.3.0.25");
    // algorithm info
    AlgorithmInfoType algType = new AlgorithmInfoType();
    algType.setAlgorithm("signPKCS1_V1_5");
    AlgorithmIdentifierType aIdType = new AlgorithmIdentifierType();
    aIdType.setAlgorithm("http://ws.openecard.org/alg/rsa");
    algType.setAlgorithmIdentifier(aIdType);
    algType.getSupportedOperations().add("Compute-signature");
    algType.setCardAlgRef(new byte[] { (byte) 0x02 });
    QName elemName = new QName("urn:iso:std:iso-iec:24727:tech:schema", "AlgorithmInfo");
    JAXBElement<AlgorithmInfoType> algInfo = new JAXBElement<>(elemName, AlgorithmInfoType.class, algType);
    Element algInfoElem = marshaller.marshal(algInfo).getDocumentElement();
    cryptoMarker.getAny().add(algInfoElem);
    // key info
    elemName = new QName("urn:iso:std:iso-iec:24727:tech:schema", "KeyInfo");
    CryptoKeyInfoType cryptoKey = new CryptoKeyInfoType();
    KeyRefType keyref = new KeyRefType();
    keyref.setKeyRef(new byte[] { (byte) 0x02 });
    cryptoKey.setKeyRef(keyref);
    JAXBElement<CryptoKeyInfoType> keyInfoElem = new JAXBElement<>(elemName, CryptoKeyInfoType.class, cryptoKey);
    Element keyrefElem = marshaller.marshal(keyInfoElem).getDocumentElement();
    cryptoMarker.getAny().add(keyrefElem);
    // signature generation info
    elemName = new QName("urn:iso:std:iso-iec:24727:tech:schema", "SignatureGenerationInfo");
    JAXBElement<String> sigGenInfoElem = new JAXBElement<>(elemName, String.class, "MSE_KEY_DS PSO_CDS");
    Element sigGenElem = marshaller.marshal(sigGenInfoElem).getDocumentElement();
    cryptoMarker.getAny().add(sigGenElem);
    // certificate references if available
    elemName = new QName("urn:iso:std:iso-iec:24727:tech:schema", "CertificateRef");
    CertificateRefType certRef = new CertificateRefType();
    certRef.setDataSetName("EF.C.CH.AUT");
    JAXBElement<CertificateRefType> certRefType = new JAXBElement<>(elemName, CertificateRefType.class, certRef);
    Element certRefElement = marshaller.marshal(certRefType).getDocumentElement();
    cryptoMarker.getAny().add(certRefElement);
    // perform the tests
    CryptoMarkerType cryptoMarkerNew = new CryptoMarkerType(cryptoMarker);
    assertTrue(cryptoMarkerNew.getAlgorithmInfo().getSupportedOperations().size() > 0);
    assertEquals(cryptoMarkerNew.getSignatureGenerationInfo(), new String[] { "MSE_KEY_DS", "PSO_CDS" });
    assertEquals(cryptoMarkerNew.getCryptoKeyInfo().getKeyRef().getKeyRef(), new byte[] { 0x02 });
    assertEquals(cryptoMarkerNew.getAlgorithmInfo().getAlgorithmIdentifier().getAlgorithm(), "http://ws.openecard.org/alg/rsa");
    assertNull(cryptoMarkerNew.getLegacyKeyName());
    assertNotNull(cryptoMarkerNew.getHashGenerationInfo());
    assertEquals(cryptoMarkerNew.getHashGenerationInfo(), HashGenerationInfoType.NOT_ON_CARD);
    assertEquals(cryptoMarkerNew.getCertificateRefs().get(0).getDataSetName(), "EF.C.CH.AUT");
    // assertEquals(cryptoMarker.getStateInfo(), "");
    assertEquals(cryptoMarker.getProtocol(), ECardConstants.Protocol.GENERIC_CRYPTO);
}
Also used : KeyRefType(iso.std.iso_iec._24727.tech.schema.KeyRefType) QName(javax.xml.namespace.QName) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) WSMarshaller(org.openecard.ws.marshal.WSMarshaller) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) JAXBElement(javax.xml.bind.JAXBElement) CertificateRefType(iso.std.iso_iec._24727.tech.schema.CertificateRefType) CryptoKeyInfoType(iso.std.iso_iec._24727.tech.schema.CryptoKeyInfoType) AlgorithmInfoType(iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType) AlgorithmIdentifierType(iso.std.iso_iec._24727.tech.schema.AlgorithmIdentifierType) Test(org.testng.annotations.Test)

Example 34 with WSMarshaller

use of org.openecard.ws.marshal.WSMarshaller in project open-ecard by ecsec.

the class AddonBundleDescriptionTest method setup.

@BeforeSuite
public void setup() throws IOException, WSMarshallerException, SAXException {
    // read the test xml
    InputStream descriptionStream = FileUtils.resolveResourceAsStream(AddonBundleDescriptionTest.class, TEST_DESCRIPTION);
    String s = FileUtils.toString(descriptionStream);
    // unmarshal it and check fields of POJO
    WSMarshaller marshaller = WSMarshallerFactory.createInstance();
    marshaller.removeAllTypeClasses();
    marshaller.addXmlTypeClass(AddonSpecification.class);
    Object o = marshaller.unmarshal(marshaller.str2doc(s));
    addonBundleDescription = (AddonSpecification) o;
}
Also used : InputStream(java.io.InputStream) WSMarshaller(org.openecard.ws.marshal.WSMarshaller) BeforeSuite(org.testng.annotations.BeforeSuite)

Example 35 with WSMarshaller

use of org.openecard.ws.marshal.WSMarshaller in project open-ecard by ecsec.

the class TCTokenHandler method handleActivate.

/**
 * Activates the client according to the received TCToken.
 *
 * @param request The activation request containing the TCToken.
 * @return The response containing the result of the activation process.
 * @throws InvalidRedirectUrlException Thrown in case no redirect URL could be determined.
 * @throws SecurityViolationException
 * @throws NonGuiException
 */
public TCTokenResponse handleActivate(TCTokenRequest request) throws InvalidRedirectUrlException, SecurityViolationException, NonGuiException {
    TCToken token = request.getTCToken();
    if (LOG.isDebugEnabled()) {
        try {
            WSMarshaller m = WSMarshallerFactory.createInstance();
            LOG.debug("TCToken:\n{}", m.doc2str(m.marshal(token)));
        } catch (TransformerException | WSMarshallerException ex) {
        // it's no use
        }
    }
    final DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
    boolean performChecks = isPerformTR03112Checks(request);
    if (!performChecks) {
        LOG.warn("Checks according to BSI TR03112 3.4.2, 3.4.4 (TCToken specific) and 3.4.5 are disabled.");
    }
    boolean isObjectActivation = request.getTCTokenURL() == null;
    if (isObjectActivation) {
        LOG.warn("Checks according to BSI TR03112 3.4.4 (TCToken specific) are disabled.");
    }
    dynCtx.put(TR03112Keys.TCTOKEN_CHECKS, performChecks);
    dynCtx.put(TR03112Keys.OBJECT_ACTIVATION, isObjectActivation);
    dynCtx.put(TR03112Keys.TCTOKEN_SERVER_CERTIFICATES, request.getCertificates());
    ConnectionHandleType connectionHandle = null;
    TCTokenResponse response = new TCTokenResponse();
    response.setTCToken(token);
    byte[] requestedContextHandle = request.getContextHandle();
    String ifdName = request.getIFDName();
    BigInteger requestedSlotIndex = request.getSlotIndex();
    // we know exactly which card we want
    ConnectionHandleType requestedHandle = new ConnectionHandleType();
    requestedHandle.setContextHandle(requestedContextHandle);
    requestedHandle.setIFDName(ifdName);
    requestedHandle.setSlotIndex(requestedSlotIndex);
    Set<CardStateEntry> matchingHandles = cardStates.getMatchingEntries(requestedHandle);
    if (!matchingHandles.isEmpty()) {
        connectionHandle = matchingHandles.toArray(new CardStateEntry[] {})[0].handleCopy();
    }
    if (connectionHandle == null) {
        String msg = LANG_TOKEN.translationForKey("cancel");
        LOG.error(msg);
        response.setResult(WSHelper.makeResultError(ResultMinor.CANCELLATION_BY_USER, msg));
        // fill in values, so it is usuable by the transport module
        response = determineRefreshURL(request, response);
        response.finishResponse(true);
        return response;
    }
    try {
        // process binding and follow redirect addresses afterwards
        response = processBinding(request, connectionHandle);
        // fill in values, so it is usuable by the transport module
        response = determineRefreshURL(request, response);
        response.finishResponse(isObjectActivation);
        return response;
    } catch (DispatcherException w) {
        LOG.error(w.getMessage(), w);
        response.setResultCode(BindingResultCode.INTERNAL_ERROR);
        response.setResult(WSHelper.makeResultError(ResultMinor.CLIENT_ERROR, w.getMessage()));
        showErrorMessage(w.getMessage());
        throw new NonGuiException(response, w.getMessage(), w);
    } catch (PAOSException w) {
        LOG.error(w.getMessage(), w);
        // find actual error to display to the user
        Throwable innerException = w.getCause();
        if (innerException == null) {
            innerException = w;
        } else if (innerException instanceof ExecutionException) {
            innerException = innerException.getCause();
        }
        String errorMsg = innerException.getLocalizedMessage();
        // fix NPE when null is returned instead of a message
        errorMsg = errorMsg == null ? "" : errorMsg;
        switch(errorMsg) {
            case "The target server failed to respond":
                errorMsg = LANG_TR.translationForKey(NO_RESPONSE_FROM_SERVER);
                break;
            case ECardConstants.Minor.App.INT_ERROR + " ==> Unknown eCard exception occurred.":
                errorMsg = LANG_TR.translationForKey(UNKNOWN_ECARD_ERROR);
                break;
            case "Internal TLS error, this could be an attack":
                errorMsg = LANG_TR.translationForKey(INTERNAL_TLS_ERROR);
                break;
        }
        if (innerException instanceof WSException) {
            WSException ex = (WSException) innerException;
            errorMsg = createResponseFromWsEx(ex, response);
        } else if (innerException instanceof PAOSConnectionException) {
            response.setResult(WSHelper.makeResultError(ResultMinor.TRUSTED_CHANNEL_ESTABLISCHMENT_FAILED, w.getLocalizedMessage()));
        } else {
            errorMsg = createMessageFromUnknownError(w);
            response.setResult(WSHelper.makeResultError(ResultMinor.CLIENT_ERROR, w.getMessage()));
        }
        showErrorMessage(errorMsg);
        try {
            // fill in values, so it is usuable by the transport module
            response = determineRefreshURL(request, response);
            response.finishResponse(true);
        } catch (InvalidRedirectUrlException ex) {
            LOG.error(ex.getMessage(), ex);
            response.setResultCode(BindingResultCode.INTERNAL_ERROR);
            response.setResult(WSHelper.makeResultError(ResultMinor.CLIENT_ERROR, ex.getLocalizedMessage()));
            throw new NonGuiException(response, ex.getMessage(), ex);
        } catch (SecurityViolationException ex) {
            String msg2 = "The RefreshAddress contained in the TCToken is invalid. Redirecting to the " + "CommunicationErrorAddress.";
            LOG.error(msg2, ex);
            response.setResultCode(BindingResultCode.REDIRECT);
            response.setResult(WSHelper.makeResultError(ResultMinor.COMMUNICATION_ERROR, msg2));
            response.addAuxResultData(AuxDataKeys.REDIRECT_LOCATION, ex.getBindingResult().getAuxResultData().get(AuxDataKeys.REDIRECT_LOCATION));
        }
        return response;
    }
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) InvalidRedirectUrlException(org.openecard.binding.tctoken.ex.InvalidRedirectUrlException) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) WSMarshallerException(org.openecard.ws.marshal.WSMarshallerException) SecurityViolationException(org.openecard.binding.tctoken.ex.SecurityViolationException) WSMarshaller(org.openecard.ws.marshal.WSMarshaller) DispatcherException(org.openecard.common.interfaces.DispatcherException) PAOSException(org.openecard.transport.paos.PAOSException) PAOSConnectionException(org.openecard.transport.paos.PAOSConnectionException) BigInteger(java.math.BigInteger) WSException(org.openecard.common.WSHelper.WSException) NonGuiException(org.openecard.binding.tctoken.ex.NonGuiException) ExecutionException(java.util.concurrent.ExecutionException) TransformerException(javax.xml.transform.TransformerException) DynamicContext(org.openecard.common.DynamicContext)

Aggregations

WSMarshaller (org.openecard.ws.marshal.WSMarshaller)36 Test (org.testng.annotations.Test)28 Document (org.w3c.dom.Document)21 IOException (java.io.IOException)12 InternationalStringType (oasis.names.tc.dss._1_0.core.schema.InternationalStringType)6 WSMarshallerException (org.openecard.ws.marshal.WSMarshallerException)6 Element (org.w3c.dom.Element)6 BigInteger (java.math.BigInteger)5 Result (oasis.names.tc.dss._1_0.core.schema.Result)5 EstablishChannel (iso.std.iso_iec._24727.tech.schema.EstablishChannel)4 StringReader (java.io.StringReader)4 Connect (iso.std.iso_iec._24727.tech.schema.Connect)3 ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)3 DIDAuthenticateResponse (iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse)3 EstablishChannelResponse (iso.std.iso_iec._24727.tech.schema.EstablishChannelResponse)3 EstablishContext (iso.std.iso_iec._24727.tech.schema.EstablishContext)3 DocumentBuilder (javax.xml.parsers.DocumentBuilder)3 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)3 ChannelHandleType (iso.std.iso_iec._24727.tech.schema.ChannelHandleType)2 ControlIFD (iso.std.iso_iec._24727.tech.schema.ControlIFD)2