Repository navigation
Expand file tree
/
Copy pathEMVTerminal.java
More file actions
451 lines (395 loc) · 18.5 KB
/
Copy pathEMVTerminal.java
File metadata and controls
451 lines (395 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
* Copyright 2010 sasc
*
* 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 sasc.emv;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import sasc.iso7816.Tag;
import sasc.iso7816.TagAndLength;
import sasc.iso7816.TagImpl;
import sasc.iso7816.TagValueType;
import sasc.util.ISO4217_Numeric;
import sasc.util.Log;
import sasc.util.Util;
/**
* Representation of a Point of Sale (POS)
*
* There is only 1 Terminal
*
* @author sasc
*/
public class EMVTerminal {
private final static Properties defaultTerminalProperties = new Properties();
private final static Properties runtimeTerminalProperties = new Properties();
private final static TerminalVerificationResults terminalVerificationResults = new TerminalVerificationResults();
private static CallbackHandler pinCallbackHandler;
private static boolean doVerifyPinIfRequired = false;
private static boolean isOnline = true;
static {
try {
//Default properties
defaultTerminalProperties.load(EMVTerminal.class.getResourceAsStream("/terminal.properties"));
for (String key : defaultTerminalProperties.stringPropertyNames()) {
//Sanitize
String sanitizedKey = Util.byteArrayToHexString(Util.fromHexString(key)).toLowerCase();
String sanitizedValue = Util.byteArrayToHexString(Util.fromHexString(defaultTerminalProperties.getProperty(key))).toLowerCase();
defaultTerminalProperties.setProperty(sanitizedKey, sanitizedValue);
}
//Runtime/overridden properties
String runtimeTerminalPropertiesFile = System.getProperty("terminal.properties");
if (runtimeTerminalPropertiesFile != null) {
runtimeTerminalProperties.load(new FileInputStream(runtimeTerminalPropertiesFile));
for(String key : runtimeTerminalProperties.stringPropertyNames()) {
//Sanitize
String sanitizedKey = Util.byteArrayToHexString(Util.fromHexString(key)).toLowerCase();
String sanitizedValue = Util.byteArrayToHexString(Util.fromHexString(runtimeTerminalProperties.getProperty(key))).toLowerCase();
if(defaultTerminalProperties.contains(sanitizedKey) && sanitizedValue.length() != defaultTerminalProperties.getProperty(key).length()) {
//Attempt to set different length for a default value
throw new RuntimeException("Attempted to set a value with unsupported length for key: "+sanitizedKey + " (value: "+sanitizedValue+")");
}
runtimeTerminalProperties.setProperty(sanitizedKey, sanitizedValue);
}
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
//PDOL (Processing options Data Object List)
//DDOL (*Default* Dynamic Data Authentication Data Object List)
// (Default to be used for constructing the INTERNAL AUTHENTICATE command if the DDOL in the card is not present)
//TDOL (*Default* Transaction Certificate Data Object List)
// (Default to be used for generating the TC Hash Value if the TDOL in the card is not present)
//PDOL example (Visa Electron, contactless)
// 9f 38 18 -- Processing Options Data Object List (PDOL)
// 9f 66 04 -- Terminal Transaction Qualifiers
// 9f 02 06 -- Amount, Authorised (Numeric)
// 9f 03 06 -- Amount, Other (Numeric)
// 9f 1a 02 -- Terminal Country Code
// 95 05 -- Terminal Verification Results (TVR)
// 5f 2a 02 -- Transaction Currency Code
// 9a 03 -- Transaction Date
// 9c 01 -- Transaction Type
// 9f 37 04 -- Unpredictable Number
private static byte[] getTerminalResidentData(TagAndLength tal, EMVApplication app) {
//Check if the value is specified in the runtime properties file
String propertyValueStr = runtimeTerminalProperties.getProperty(Util.byteArrayToHexString(tal.getTag().getTagBytes()).toLowerCase());
if(propertyValueStr != null) {
byte[] propertyValue = Util.fromHexString(propertyValueStr);
if (propertyValue.length == tal.getLength()) {
return propertyValue;
}
}
if (tal.getTag().equals(EMVTags.TERMINAL_COUNTRY_CODE) && tal.getLength() == 2) {
return findCountryCode(app);
} else if (tal.getTag().equals(EMVTags.TRANSACTION_CURRENCY_CODE) && tal.getLength() == 2) {
return findCurrencyCode(app);
}
//Now check for default values
propertyValueStr = defaultTerminalProperties.getProperty(Util.byteArrayToHexString(tal.getTag().getTagBytes()).toLowerCase());
if(propertyValueStr != null) {
byte[] propertyValue = Util.fromHexString(propertyValueStr);
if (propertyValue.length == tal.getLength()) {
return propertyValue;
}
}
if (tal.getTag().equals(EMVTags.UNPREDICTABLE_NUMBER)) {
return Util.generateRandomBytes(tal.getLength());
} else if (tal.getTag().equals(EMVTags.TERMINAL_TRANSACTION_QUALIFIERS) && tal.getLength() == 4) {
//This seems only to be used in contactless mode. Construct accordingly
TerminalTransactionQualifiers ttq = new TerminalTransactionQualifiers();
ttq.setContactlessEMVmodeSupported(true);
ttq.setReaderIsOfflineOnly(true);
return ttq.getBytes();
} else if (tal.getTag().equals(EMVTags.TERMINAL_VERIFICATION_RESULTS) && tal.getLength() == 5) {
//All bits set to '0'
return terminalVerificationResults.toByteArray();
} else if (tal.getTag().equals(EMVTags.TRANSACTION_DATE) && tal.getLength() == 3) {
return Util.getCurrentDateAsNumericEncodedByteArray();
} else if (tal.getTag().equals(EMVTags.TRANSACTION_TYPE) && tal.getLength() == 1) {
//transactionTypes = { 0: "Payment", 1: "Withdrawal", }
//http://www.codeproject.com/Articles/100084/Introduction-to-ISO-8583
return new byte[]{0x00};
} else {
Log.debug("Terminal Resident Data not found for " + tal);
}
byte[] defaultResponse = new byte[tal.getLength()];
Arrays.fill(defaultResponse, (byte) 0x00);
return defaultResponse;
}
public static TerminalVerificationResults getTerminalVerificationResults() {
return terminalVerificationResults;
}
public static void resetTVR(){
terminalVerificationResults.reset();
}
public static void setProperty(String tagHex, String valueHex) {
setProperty(new TagImpl(tagHex, TagValueType.BINARY, "", ""), Util.fromHexString(valueHex));
}
public static void setProperty(Tag tag, byte[] value){
runtimeTerminalProperties.setProperty(Util.byteArrayToHexString(tag.getTagBytes()).toLowerCase(Locale.US), Util.byteArrayToHexString(value));
}
public static boolean isCDASupported(EMVApplication app) {
return false;
}
public static boolean isDDASupported(EMVApplication app) {
return true;
}
public static boolean isSDASupported(EMVApplication app) {
return true;
}
public static boolean isATM() {
return false;
}
public static Date getCurrentDate() {
return new Date();
}
public static int getSupportedApplicationVersionNumber(EMVApplication app) {
//TODO
//For now, just return the version number maintained in the card
return app.getApplicationVersionNumber();
}
public static boolean isCVMRecognized(EMVApplication app, CVRule rule) {
switch(rule.getRule()) {
case RESERVED_FOR_USE_BY_THE_INDIVIDUAL_PAYMENT_SYSTEMS:
//app.getAID().getRIDBytes();
//TODO check if RID specific rule is supported
//if(supported) {
// return true;
//}
case RESERVED_FOR_USE_BY_THE_ISSUER:
if(app.getIssuerIdentificationNumber() != null){
//TODO check if issuer specific rule is supported
//if(supported){
// return true;
//}
}
case NOT_AVAILABLE_FOR_USE:
case RFU:
return false;
}
return true;
}
public static boolean isCVMSupported(CVRule rule) {
switch(rule.getRule()) {
//TODO support enciphered PIN
case ENCIPHERED_PIN_VERIFIED_BY_ICC:
case ENCIPHERED_PIN_VERIFIED_BY_ICC_AND_SIGNATURE_ON_PAPER:
return false;
case PLAINTEXT_PIN_VERIFIED_BY_ICC_AND_SIGNATURE_ON_PAPER:
case PLAINTEXT_PIN_VERIFIED_BY_ICC:
return hasPinInputCapability();
case SIGNATURE_ON_PAPER:
return false;
case ENCIPHERED_PIN_VERIFIED_ONLINE:
return isOnline();
case FAIL_PROCESSING:
case NO_CVM_REQUIRED:
return true;
}
return false;
}
public static boolean isOnline() {
return isOnline;
}
public static void setIsOnline(boolean value){
isOnline = value;
}
public static boolean isCVMConditionSatisfied(CVRule rule) {
if(rule.getConditionAlways()) {
return true;
}
if(rule.getConditionCode() <= 0x05){
//TODO
return true;
}else if(rule.getConditionCode() < 0x0A) {
//TODO
//Check for presence Application Currency Code or Amount, Authorised in app records?
return true;
} else { //RFU and proprietary
return false;
}
}
public static boolean verifyEncipheredPinOnline() {
if(!isOnline()) {
return false;
}
//TODO
return true;
}
public static boolean hasSignatureOnPaper() {
return true;
}
public static void setDoVerifyPinIfRequired(boolean value) {
doVerifyPinIfRequired = value;
}
public static boolean getDoVerifyPinIfRequired() {
return doVerifyPinIfRequired;
}
/**
*
* @return true if a Pin CallbackHandler has be set
*/
public static boolean hasPinInputCapability() {
return doVerifyPinIfRequired && pinCallbackHandler != null;
}
public static void setPinCallbackHandler(CallbackHandler callbackHandler) {
pinCallbackHandler = callbackHandler;
}
public static PasswordCallback getPinInput() {
CallbackHandler callBackHandler = pinCallbackHandler;
if(callBackHandler == null){
return null;
}
PasswordCallback passwordCallback = new PasswordCallback("Type PIN", false);
try{
callBackHandler.handle(new Callback[]{passwordCallback});
}catch(IOException ex){
Log.info(Util.getStackTrace(ex));
}catch(UnsupportedCallbackException ex){
Log.info(Util.getStackTrace(ex));
}
return passwordCallback;
}
public static boolean getPerformTerminalRiskManagement() {
return false;
}
public static byte[] constructDOLResponse(DOL dol, EMVApplication app) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
for (TagAndLength tagAndLength : dol.getTagAndLengthList()) {
byte[] data = getTerminalResidentData(tagAndLength, app);
stream.write(data, 0, data.length);
}
return stream.toByteArray();
}
//The ICC may contain the DDOL, but there shall be a default DDOL in the terminal,
//specified by the payment system, for use in case the DDOL is not present in the ICC.
public static byte[] getDefaultDDOLResponse(EMVApplication app) {
//It is mandatory that the DDOL contains the Unpredictable Number generated by the terminal (tag '9F37', 4 bytes binary).
byte[] unpredictableNumber = Util.generateRandomBytes(4);
//TODO add other DDOL data specified by the payment system
//if(app.getAID().equals(SOMEAID))
return unpredictableNumber;
}
//Ex Banco BRADESCO (f0 00 00 00 03 00 01) failes GPO with wrong COUNTRY_CODE !
private static byte[] findCountryCode(EMVApplication app) {
if(app != null){
if(app.getIssuerCountryCode() != -1){
byte[] countryCode = Util.intToBinaryEncodedDecimalByteArray(app.getIssuerCountryCode());
return Util.resizeArray(countryCode, 2);
}
}
Log.debug("No Issuer Country Code found in app. Using default Terminal Country Code");
String countryCode = defaultTerminalProperties.getProperty(Util.byteArrayToHexString(EMVTags.TERMINAL_COUNTRY_CODE.getTagBytes()));
if(countryCode != null){
return Util.fromHexString(countryCode);
}
return new byte[]{0x08, 0x26};
}
private static byte[] findCurrencyCode(EMVApplication app){
if(app != null){
if(app.getApplicationCurrencyCode() != -1){
byte[] currencyCode = Util.intToBinaryEncodedDecimalByteArray(app.getApplicationCurrencyCode());
return Util.resizeArray(currencyCode, 2);
}
Locale preferredLocale = null;
if(app.getLanguagePreference() != null){
preferredLocale = app.getLanguagePreference().getPreferredLocale();
}
if(preferredLocale == null
&& app.getCard() != null
&& app.getCard().getPSE() != null
&& app.getCard().getPSE().getLanguagePreference() != null){
preferredLocale = app.getCard().getPSE().getLanguagePreference().getPreferredLocale();
}
if(preferredLocale != null){
if(preferredLocale.getLanguage().equals(Locale.getDefault().getLanguage())) {
//Guesstimate; we presume default locale is the preferred
preferredLocale = Locale.getDefault();
}
List<Integer> numericCodes = ISO4217_Numeric.getNumericCodeForLocale(preferredLocale);
if (numericCodes != null && numericCodes.size() > 0) {
//Just use the first found. It might not be correct, eg Brazil (BRZ) vs Portugal (EUR)
return Util.resizeArray(Util.intToBinaryEncodedDecimalByteArray(numericCodes.get(0)), 2);
}
}
}
String currencyCode = defaultTerminalProperties.getProperty(Util.byteArrayToHexString(EMVTags.TRANSACTION_CURRENCY_CODE.getTagBytes()));
if(currencyCode != null){
return Util.fromHexString(currencyCode);
}
return new byte[]{0x08, 0x26};
}
public static void main(String[] args) {
for(String key : defaultTerminalProperties.stringPropertyNames()){
System.out.println(key+"="+defaultTerminalProperties.getProperty(key));
}
{
TagAndLength tagAndLength = new TagAndLength(EMVTags.AMOUNT_AUTHORISED_NUMERIC, 6);
DOL dol = new DOL(DOL.Type.PDOL, tagAndLength.getBytes());
System.out.println(Util.prettyPrintHexNoWrap(constructDOLResponse(dol, null)));
}
{
TagAndLength tagAndLength = new TagAndLength(EMVTags.TERMINAL_COUNTRY_CODE, 2);
DOL dol = new DOL(DOL.Type.PDOL, tagAndLength.getBytes());
System.out.println(Util.prettyPrintHexNoWrap(constructDOLResponse(dol, null)));
}
{
//Test country code 076 (Brazil)
TagAndLength tagAndLength = new TagAndLength(EMVTags.TERMINAL_COUNTRY_CODE, 2);
DOL dol = new DOL(DOL.Type.PDOL, tagAndLength.getBytes());
EMVApplication app = new EMVApplication();
app.setIssuerCountryCode(76); //Brazil
byte[] dolResponse = constructDOLResponse(dol, app);
System.out.println(Util.prettyPrintHexNoWrap(dolResponse));
if (!Arrays.equals(new byte[]{0x00, (byte) 0x76}, dolResponse)) {
throw new AssertionError("Country code was wrong");
}
}
{
//Test currency code 986 (Brazilian Real)
TagAndLength tagAndLength = new TagAndLength(EMVTags.TRANSACTION_CURRENCY_CODE, 2);
DOL dol = new DOL(DOL.Type.PDOL, tagAndLength.getBytes());
EMVApplication app = new EMVApplication();
app.setApplicationCurrencyCode(986);
byte[] dolResponse = constructDOLResponse(dol, app);
System.out.println(Util.prettyPrintHexNoWrap(dolResponse));
if (!Arrays.equals(new byte[]{0x09, (byte) 0x86}, dolResponse)) {
throw new AssertionError("Currency code was wrong");
}
}
{
//Test currency code 986 (Brazilian Real) from Locale
TagAndLength tagAndLength = new TagAndLength(EMVTags.TRANSACTION_CURRENCY_CODE, 2);
DOL dol = new DOL(DOL.Type.PDOL, tagAndLength.getBytes());
EMVApplication app = new EMVApplication();
app.setLanguagePreference(new LanguagePreference(Util.fromHexString("70 74 65 6e 65 73 69 74"))); // (=ptenesit)
byte[] dolResponse = constructDOLResponse(dol, app);
System.out.println(Util.prettyPrintHexNoWrap(dolResponse));
// if(!Arrays.equals(new byte[]{0x09, (byte)0x86}, dolResponse)){
// throw new AssertionError("Currency code was wrong");
// }
}
}
}