Search in sources :

Example 6 with Sign

use of iso.std.iso_iec._24727.tech.schema.Sign in project open-ecard by ecsec.

the class SignStep method performLegacySignature.

/**
 * The method performs the SignatureCreation if no standard commands are possible.
 * This method creates a signature with APDUs which are not covered by the methods defined in TR-03112 part 7.
 *
 * @param cryptoMarker A {@link CryptoMarkerType} object containing the information about the creation of a signature
 *   in a legacy way.
 * @param slotHandle A slotHandle identifying the current card.
 * @param templateCTX A Map containing the context data for the evaluation of the template variables. This object
 *   contains per default the message to sign and the {@link TLVFunction}.
 * @return A {@link SignResponse} object containing the signature of the <b>message</b>.
 * @throws APDUTemplateException Thrown if the evaluation of the {@link CardCommandTemplate} failed.
 * @throws APDUException Thrown if one of the commands to execute failed.
 * @throws WSHelper.WSException Thrown if the checkResult method of WSHelper failed.
 */
private SignResponse performLegacySignature(CryptoMarkerType cryptoMarker, ConnectionHandleType connectionHandle, BaseTemplateContext templateCTX) throws APDUTemplateException, APDUException, WSHelper.WSException {
    SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK());
    List<Object> legacyCommands = cryptoMarker.getLegacySignatureGenerationInfo();
    CardCommandAPDU cmdAPDU;
    CardResponseAPDU responseAPDU = null;
    byte[] slotHandle = connectionHandle.getSlotHandle();
    byte[] signedMessage;
    for (Object next : legacyCommands) {
        if (next instanceof CardCallTemplateType) {
            CardCallTemplateType cctt = (CardCallTemplateType) next;
            CardCommandTemplate template = new CardCommandTemplate(cctt);
            cmdAPDU = template.evaluate(templateCTX);
            responseAPDU = cmdAPDU.transmit(dispatcher, slotHandle, Collections.<byte[]>emptyList());
        } else if (next instanceof APICommand) {
            sendAPICommand(connectionHandle, (APICommand) next);
        }
    }
    signedMessage = responseAPDU.getData();
    // check if further response data is available
    while (responseAPDU.getTrailer()[0] == (byte) 0x61) {
        CardCommandAPDU getResponseData = new CardCommandAPDU((byte) 0x00, (byte) 0xC0, (byte) 0x00, (byte) 0x00, responseAPDU.getTrailer()[1]);
        responseAPDU = getResponseData.transmit(dispatcher, slotHandle, Collections.<byte[]>emptyList());
        signedMessage = Arrays.concatenate(signedMessage, responseAPDU.getData());
    }
    if (!Arrays.areEqual(responseAPDU.getTrailer(), new byte[] { (byte) 0x90, (byte) 0x00 })) {
        String minor = SALErrorUtils.getMinor(responseAPDU.getTrailer());
        response.setResult(WSHelper.makeResultError(minor, responseAPDU.getStatusMessage()));
        return response;
    }
    // fix output format
    String outForm = cryptoMarker.getLegacyOutputFormat();
    if (outForm != null) {
        switch(outForm) {
            case "rawRS":
                signedMessage = encodeRawRS(signedMessage);
                break;
            default:
                LOG.warn("Unsupport outputFormat={} specified in LegacySignatureGenerationInfo.", outForm);
        }
    }
    response.setSignature(signedMessage);
    return response;
}
Also used : CardCommandAPDU(org.openecard.common.apdu.common.CardCommandAPDU) CardCallTemplateType(iso.std.iso_iec._24727.tech.schema.CardCallTemplateType) SignResponse(iso.std.iso_iec._24727.tech.schema.SignResponse) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) CardCommandTemplate(org.openecard.common.apdu.common.CardCommandTemplate) APICommand(iso.std.iso_iec._24727.tech.schema.LegacySignatureGenerationType.APICommand)

Example 7 with Sign

use of iso.std.iso_iec._24727.tech.schema.Sign in project open-ecard by ecsec.

the class TinySALTest method testSign.

/**
 * Test of sign method, of class TinySAL.
 */
@Test(enabled = TESTS_ENABLED)
public void testSign() {
    System.out.println("sign");
    Sign parameters = new Sign();
    SignResponse result = instance.sign(parameters);
    assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor());
}
Also used : SignResponse(iso.std.iso_iec._24727.tech.schema.SignResponse) Sign(iso.std.iso_iec._24727.tech.schema.Sign) Test(org.testng.annotations.Test)

Example 8 with Sign

use of iso.std.iso_iec._24727.tech.schema.Sign in project open-ecard by ecsec.

the class MiddlewareSAL method sign.

@Override
public SignResponse sign(Sign request) {
    SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK());
    try {
        ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
        CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
        byte[] application = cardStateEntry.getImplicitlySelectedApplicationIdentifier();
        byte[] slotHandle = connectionHandle.getSlotHandle();
        String didName = SALUtils.getDIDName(request);
        byte[] message = request.getMessage();
        Assert.assertIncorrectParameter(message, "The parameter Message is empty.");
        DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, application);
        Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
        CryptoMarkerType marker = new CryptoMarkerType(didStructure.getDIDMarker());
        String keyLabel = marker.getLegacyKeyName();
        MwSession session = managedSessions.get(slotHandle);
        for (MwPrivateKey key : session.getPrivateKeys()) {
            String nextLabel = "";
            try {
                nextLabel = key.getKeyLabel();
            } catch (CryptokiException ex) {
                LOG.warn("Error reading key label.", ex);
            }
            LOG.debug("Try to match keys '{}' == '{}'", keyLabel, nextLabel);
            if (keyLabel.equals(nextLabel)) {
                long sigAlg = getPKCS11Alg(marker.getAlgorithmInfo());
                byte[] sig = key.sign(sigAlg, message);
                response.setSignature(sig);
                // set PIN to unauthenticated
                setPinNotAuth(cardStateEntry);
                return response;
            }
        }
        // TODO: use other exception
        String msg = String.format("The given DIDName %s references an unknown key.", didName);
        throw new IncorrectParameterException(msg);
    } catch (ECardException e) {
        LOG.debug(e.getMessage(), e);
        response.setResult(e.getResult());
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throwThreadKillException(e);
        response.setResult(WSHelper.makeResult(e));
    }
    return response;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) ThreadTerminateException(org.openecard.common.ThreadTerminateException) InitializationException(org.openecard.mdlw.sal.exceptions.InitializationException) ECardException(org.openecard.common.ECardException) FinalizationException(org.openecard.mdlw.sal.exceptions.FinalizationException) PinBlockedException(org.openecard.mdlw.sal.exceptions.PinBlockedException) CryptokiException(org.openecard.mdlw.sal.exceptions.CryptokiException) NamedEntityNotFoundException(org.openecard.common.sal.exception.NamedEntityNotFoundException) UnknownProtocolException(org.openecard.common.sal.exception.UnknownProtocolException) TokenException(org.openecard.mdlw.sal.exceptions.TokenException) WSMarshallerException(org.openecard.ws.marshal.WSMarshallerException) IncorrectParameterException(org.openecard.common.sal.exception.IncorrectParameterException) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) PinIncorrectException(org.openecard.mdlw.sal.exceptions.PinIncorrectException) ECardException(org.openecard.common.ECardException) SignResponse(iso.std.iso_iec._24727.tech.schema.SignResponse) CryptokiException(org.openecard.mdlw.sal.exceptions.CryptokiException) IncorrectParameterException(org.openecard.common.sal.exception.IncorrectParameterException) DIDStructureType(iso.std.iso_iec._24727.tech.schema.DIDStructureType)

Example 9 with Sign

use of iso.std.iso_iec._24727.tech.schema.Sign in project open-ecard by ecsec.

the class CIFCreator method createCryptoDID.

private DIDInfoType createCryptoDID(List<MwCertificate> mwCerts, SignatureAlgorithms sigalg) throws WSMarshallerException, CryptokiException {
    LOG.debug("Creating Crypto DID object.");
    DIDInfoType di = new DIDInfoType();
    String keyLabel = mwCerts.get(0).getLabel();
    // create differential identity
    DifferentialIdentityType did = new DifferentialIdentityType();
    di.setDifferentialIdentity(did);
    String didName = keyLabel + "_" + mwCerts.get(0).getLabel() + "_" + sigalg.getJcaAlg();
    LOG.debug("DIDName: {}", didName);
    did.setDIDName(didName);
    did.setDIDProtocol("urn:oid:1.3.162.15480.3.0.25");
    did.setDIDScope(DIDScopeType.LOCAL);
    // create crypto marker
    CryptoMarkerBuilder markerBuilder = new CryptoMarkerBuilder();
    // add AlgorithmInfo
    AlgorithmInfoType algInfo = new AlgorithmInfoType();
    algInfo.setAlgorithm(sigalg.getJcaAlg());
    AlgorithmIdentifierType algIdentifier = new AlgorithmIdentifierType();
    algIdentifier.setAlgorithm(sigalg.getAlgId());
    algInfo.setAlgorithmIdentifier(algIdentifier);
    algInfo.getSupportedOperations().add("Compute-signature");
    markerBuilder.setAlgInfo(algInfo);
    markerBuilder.setLegacyKeyname(keyLabel);
    // add certificates
    for (MwCertificate nextCert : mwCerts) {
        try {
            CertificateRefType certRef = new CertificateRefType();
            certRef.setDataSetName(nextCert.getLabel());
            markerBuilder.getCertRefs().add(certRef);
        } catch (CryptokiException ex) {
            LOG.warn("Certificate chain is not complete.");
            break;
        }
    }
    // wrap crypto marker and add to parent
    CryptoMarkerType marker = markerBuilder.build();
    DIDMarkerType markerWrapper = new DIDMarkerType();
    markerWrapper.setCryptoMarker(marker);
    did.setDIDMarker(markerWrapper);
    // create acl
    AccessControlListType acl = new AccessControlListType();
    di.setDIDACL(acl);
    List<AccessRuleType> rules = acl.getAccessRule();
    rules.add(createRuleTrue(AuthorizationServiceActionName.ACL_LIST));
    rules.add(createRuleTrue(DifferentialIdentityServiceActionName.DID_GET));
    // create sign rule with PIN reference
    AccessRuleType signRule = createRuleTrue(CryptographicServiceActionName.SIGN);
    signRule.setSecurityCondition(createDidCond(PIN_NAME));
    rules.add(signRule);
    return di;
}
Also used : CryptoMarkerBuilder(org.openecard.mdlw.sal.didfactory.CryptoMarkerBuilder) AccessControlListType(iso.std.iso_iec._24727.tech.schema.AccessControlListType) CryptoMarkerType(iso.std.iso_iec._24727.tech.schema.CryptoMarkerType) CertificateRefType(iso.std.iso_iec._24727.tech.schema.CertificateRefType) DIDMarkerType(iso.std.iso_iec._24727.tech.schema.DIDMarkerType) DifferentialIdentityType(iso.std.iso_iec._24727.tech.schema.DifferentialIdentityType) DIDInfoType(iso.std.iso_iec._24727.tech.schema.DIDInfoType) AlgorithmInfoType(iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType) CryptokiException(org.openecard.mdlw.sal.exceptions.CryptokiException) AlgorithmIdentifierType(iso.std.iso_iec._24727.tech.schema.AlgorithmIdentifierType) AccessRuleType(iso.std.iso_iec._24727.tech.schema.AccessRuleType)

Example 10 with Sign

use of iso.std.iso_iec._24727.tech.schema.Sign in project open-ecard by ecsec.

the class ACLResolver method getMissingDids.

private List<DIDStructureType> getMissingDids(List<AccessRuleType> acls, TargetNameType target) throws WSException, SecurityConditionUnsatisfiable {
    // find the sign acl
    ArrayList<AccessRuleType> tmpAcls = new ArrayList<>();
    for (AccessRuleType next : acls) {
        if (target.getDIDName() != null) {
            CryptographicServiceActionName action = next.getAction().getCryptographicServiceAction();
            if (CryptographicServiceActionName.SIGN.equals(action)) {
                tmpAcls.add(next);
                // there can be only one
                break;
            }
        }
        if (target.getDataSetName() != null) {
            NamedDataServiceActionName action = next.getAction().getNamedDataServiceAction();
            if (NamedDataServiceActionName.DATA_SET_SELECT.equals(action)) {
                tmpAcls.add(next);
                continue;
            }
            if (NamedDataServiceActionName.DSI_READ.equals(action)) {
                tmpAcls.add(next);
                continue;
            }
        }
    }
    ArrayList<DIDStructureType> result = new ArrayList<>();
    for (AccessRuleType acl : tmpAcls) {
        // get the most suitable DID in the tree
        SecurityConditionType cond = normalize(acl.getSecurityCondition());
        cond = getBestSecurityCondition(cond);
        // flatten condition to list of unsatisfied dids
        List<DIDAuthenticationStateType> authStates = flattenCondition(cond);
        List<DIDStructureType> missingDIDs = filterSatisfiedDIDs(authStates);
        result.addAll(missingDIDs);
    }
    // remove duplicates
    TreeSet<String> newDids = new TreeSet<>();
    Iterator<DIDStructureType> it = result.iterator();
    while (it.hasNext()) {
        // this code bluntly assumes, that did names are unique per cardinfo file
        DIDStructureType next = it.next();
        if (newDids.contains(next.getDIDName())) {
            it.remove();
        } else {
            newDids.add(next.getDIDName());
        }
    }
    return result;
}
Also used : NamedDataServiceActionName(iso.std.iso_iec._24727.tech.schema.NamedDataServiceActionName) ArrayList(java.util.ArrayList) DIDAuthenticationStateType(iso.std.iso_iec._24727.tech.schema.DIDAuthenticationStateType) TreeSet(java.util.TreeSet) CryptographicServiceActionName(iso.std.iso_iec._24727.tech.schema.CryptographicServiceActionName) AccessRuleType(iso.std.iso_iec._24727.tech.schema.AccessRuleType) DIDStructureType(iso.std.iso_iec._24727.tech.schema.DIDStructureType) SecurityConditionType(iso.std.iso_iec._24727.tech.schema.SecurityConditionType)

Aggregations

SignResponse (iso.std.iso_iec._24727.tech.schema.SignResponse)9 DIDStructureType (iso.std.iso_iec._24727.tech.schema.DIDStructureType)4 Sign (iso.std.iso_iec._24727.tech.schema.Sign)4 CardApplicationConnect (iso.std.iso_iec._24727.tech.schema.CardApplicationConnect)3 CardApplicationConnectResponse (iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse)3 CardApplicationPath (iso.std.iso_iec._24727.tech.schema.CardApplicationPath)3 CardApplicationPathResponse (iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse)3 CardApplicationPathType (iso.std.iso_iec._24727.tech.schema.CardApplicationPathType)3 ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)3 CryptoMarkerType (iso.std.iso_iec._24727.tech.schema.CryptoMarkerType)3 ECardException (org.openecard.common.ECardException)3 IncorrectParameterException (org.openecard.common.sal.exception.IncorrectParameterException)3 Test (org.testng.annotations.Test)3 AccessRuleType (iso.std.iso_iec._24727.tech.schema.AccessRuleType)2 CardAppPathResultSet (iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse.CardAppPathResultSet)2 DIDAuthenticate (iso.std.iso_iec._24727.tech.schema.DIDAuthenticate)2 DIDAuthenticateResponse (iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse)2 DIDGet (iso.std.iso_iec._24727.tech.schema.DIDGet)2 DIDGetResponse (iso.std.iso_iec._24727.tech.schema.DIDGetResponse)2 DIDList (iso.std.iso_iec._24727.tech.schema.DIDList)2