use of org.openecard.common.sal.state.CardStateEntry 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;
}
use of org.openecard.common.sal.state.CardStateEntry in project open-ecard by ecsec.
the class MiddlewareSAL method didAuthenticate.
@Override
public DIDAuthenticateResponse didAuthenticate(DIDAuthenticate request) {
DIDAuthenticateResponse response = WSHelper.makeResponse(DIDAuthenticateResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
connectionHandle = cardStateEntry.handleCopy();
byte[] application = cardStateEntry.getImplicitlySelectedApplicationIdentifier();
byte[] slotHandle = connectionHandle.getSlotHandle();
DIDAuthenticationDataType didAuthenticationData = request.getAuthenticationProtocolData();
Assert.assertIncorrectParameter(didAuthenticationData, "The parameter AuthenticationProtocolData is empty.");
String didName = SALUtils.getDIDName(request);
DIDStructureType didStruct = cardStateEntry.getDIDStructure(didName, application);
if (didStruct == null) {
String msg = String.format("DID %s does not exist.", didName);
throw new NamedEntityNotFoundException(msg);
}
PINCompareMarkerType pinCompareMarker = new PINCompareMarkerType(didStruct.getDIDMarker());
String protocolURI = didAuthenticationData.getProtocol();
if (!"urn:oid:1.3.162.15480.3.0.9".equals(protocolURI)) {
String msg = String.format("Protocol %s is not supported by this SAL.", protocolURI);
throw new UnknownProtocolException(msg);
}
PINCompareDIDAuthenticateInputType pinCompareInput = new PINCompareDIDAuthenticateInputType(didAuthenticationData);
PINCompareDIDAuthenticateOutputType pinCompareOutput = pinCompareInput.getOutputType();
// extract pin value from auth data
char[] pinValue = pinCompareInput.getPIN();
pinCompareInput.setPIN(null);
MwSession session = managedSessions.get(slotHandle);
boolean protectedAuthPath = connectionHandle.getSlotInfo().isProtectedAuthPath();
boolean pinAuthenticated;
boolean pinBlocked = false;
if (!(pinValue == null || pinValue.length == 0) && !protectedAuthPath) {
// we don't need a GUI if the PIN is known
try {
session.login(UserType.User, pinValue);
} finally {
Arrays.fill(pinValue, ' ');
}
pinAuthenticated = true;
// TODO: display error GUI if the PIN entry failed
} else {
// omit GUI when Middleware has its own PIN dialog for class 2 readers
if (protectedAuthPath && builtinPinDialog) {
session.loginExternal(UserType.User);
pinAuthenticated = true;
} else {
PinEntryDialog dialog = new PinEntryDialog(gui, protectedAuthPath, pinCompareMarker, session);
dialog.show();
pinAuthenticated = dialog.isPinAuthenticated();
pinBlocked = dialog.isPinBlocked();
}
}
if (pinAuthenticated) {
cardStateEntry.addAuthenticated(didName, application);
} else if (pinBlocked) {
String msg = "PIN is blocked.";
Result r = WSHelper.makeResultError(ECardConstants.Minor.IFD.PASSWORD_BLOCKED, msg);
response.setResult(r);
} else {
String msg = "Failed to enter PIN.";
Result r = WSHelper.makeResultError(ECardConstants.Minor.SAL.CANCELLATION_BY_USER, msg);
response.setResult(r);
}
// create did authenticate response
response.setAuthenticationProtocolData(pinCompareOutput.getAuthDataType());
} catch (PinBlockedException ex) {
// TODO: set retry counter
String minor = ECardConstants.Minor.IFD.PASSWORD_BLOCKED;
Result r = WSHelper.makeResultError(minor, ex.getMessage());
response.setResult(r);
} catch (PinIncorrectException ex) {
// TODO: set retry counter
String minor = ECardConstants.Minor.SAL.SECURITY_CONDITION_NOT_SATISFIED;
Result r = WSHelper.makeResultError(minor, ex.getMessage());
response.setResult(r);
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
use of org.openecard.common.sal.state.CardStateEntry in project open-ecard by ecsec.
the class DecipherStep method perform.
@Override
public DecipherResponse perform(Decipher request, Map<String, Object> internalData) {
DecipherResponse response = WSHelper.makeResponse(DecipherResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
String didName = SALUtils.getDIDName(request);
byte[] applicationID = connectionHandle.getCardApplication();
CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(internalData, connectionHandle);
Assert.securityConditionDID(cardStateEntry, applicationID, didName, CryptographicServiceActionName.DECIPHER);
DIDStructureType didStructure = SALUtils.getDIDStructure(request, didName, cardStateEntry, connectionHandle);
CryptoMarkerType cryptoMarker = new CryptoMarkerType(didStructure.getDIDMarker());
byte[] keyReference = cryptoMarker.getCryptoKeyInfo().getKeyRef().getKeyRef();
byte[] algorithmIdentifier = cryptoMarker.getAlgorithmInfo().getCardAlgRef();
byte[] slotHandle = connectionHandle.getSlotHandle();
// See eGK specification, part 1, version 2.2.0, section 15.9.6.
if (didStructure.getDIDScope().equals(DIDScopeType.LOCAL)) {
keyReference[0] = (byte) (0x80 | keyReference[0]);
}
TLV tagKeyReference = new TLV();
tagKeyReference.setTagNumWithClass(0x84);
tagKeyReference.setValue(keyReference);
TLV tagAlgorithmIdentifier = new TLV();
tagAlgorithmIdentifier.setTagNumWithClass(0x80);
tagAlgorithmIdentifier.setValue(algorithmIdentifier);
byte[] mseData = ByteUtils.concatenate(tagKeyReference.toBER(), tagAlgorithmIdentifier.toBER());
CardCommandAPDU apdu = new ManageSecurityEnvironment((byte) 0x41, ManageSecurityEnvironment.CT, mseData);
apdu.transmit(dispatcher, slotHandle);
byte[] ciphertext = request.getCipherText();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BigInteger bitKeySize = cryptoMarker.getCryptoKeyInfo().getKeySize();
int blocksize = bitKeySize.divide(new BigInteger("8")).intValue();
// check if the ciphertext length is divisible by the blocksize without rest
if ((ciphertext.length % blocksize) != 0) {
return WSHelper.makeResponse(DecipherResponse.class, WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, "The length of the ciphertext should be a multiple of the blocksize."));
}
// decrypt the ciphertext block for block
for (int offset = 0; offset < ciphertext.length; offset += blocksize) {
byte[] ciphertextblock = ByteUtils.copy(ciphertext, offset, blocksize);
apdu = new PSODecipher(ByteUtils.concatenate(PADDING_INDICATOR_BYTE, ciphertextblock), (byte) blocksize);
CardResponseAPDU responseAPDU = apdu.transmit(dispatcher, slotHandle);
baos.write(responseAPDU.getData());
}
response.setPlainText(baos.toByteArray());
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
logger.error(e.getMessage(), e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
use of org.openecard.common.sal.state.CardStateEntry in project open-ecard by ecsec.
the class HashStep method perform.
@Override
public HashResponse perform(Hash request, Map<String, Object> internalData) {
HashResponse response = WSHelper.makeResponse(HashResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
String didName = SALUtils.getDIDName(request);
CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(internalData, connectionHandle);
DIDStructureType didStructure = SALUtils.getDIDStructure(request, didName, cardStateEntry, connectionHandle);
CryptoMarkerType cryptoMarker = new CryptoMarkerType(didStructure.getDIDMarker());
HashGenerationInfoType hashInfo = cryptoMarker.getHashGenerationInfo();
if (hashInfo != null) {
if (hashInfo == HashGenerationInfoType.NOT_ON_CARD) {
String algId = cryptoMarker.getAlgorithmInfo().getAlgorithmIdentifier().getAlgorithm();
SignatureAlgorithms alg = SignatureAlgorithms.fromAlgId(algId);
HashAlgorithms hashAlg = alg.getHashAlg();
if (hashAlg == null) {
String msg = String.format("Algorithm %s does not specify a Hash algorithm.", algId);
LOG.error(msg);
String minor = ECardConstants.Minor.App.INCORRECT_PARM;
response.setResult(WSHelper.makeResultError(minor, msg));
} else {
// calculate hash
MessageDigest md = MessageDigest.getInstance(hashAlg.getJcaAlg());
md.update(request.getMessage());
byte[] digest = md.digest();
response.setHash(digest);
}
} else {
// TODO: implement hashing on card
String msg = String.format("Unsupported Hash generation type (%s) requested.", hashInfo);
LOG.error(msg);
String minor = ECardConstants.Minor.SAL.INAPPROPRIATE_PROTOCOL_FOR_ACTION;
response.setResult(WSHelper.makeResultError(minor, msg));
}
} else {
// no hash alg specified, this is an error
String msg = String.format("No Hash generation type specified in CIF.");
LOG.error(msg);
String minor = ECardConstants.Minor.SAL.INAPPROPRIATE_PROTOCOL_FOR_ACTION;
response.setResult(WSHelper.makeResultError(minor, msg));
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (UnsupportedAlgorithmException | NoSuchAlgorithmException ex) {
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
use of org.openecard.common.sal.state.CardStateEntry 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;
}
}
Aggregations