-
Notifications
You must be signed in to change notification settings - Fork 11
/
EMV-CAP
executable file
·655 lines (608 loc) · 24.5 KB
/
EMV-CAP
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
#!/usr/bin/env python
# coding: latin-1
# Copyright 2011, 2012
# Philippe Teuwen <phil@teuwen.org>
# Jean-Pierre Szikora <jean-pierre.szikora@uclouvain.be>
# Cette création est mise à disposition selon
# le Contrat Attribution-NoDerivs 2.0 Belgium
# disponible en ligne http://creativecommons.org/licenses/by-nd/2.0/be/
# ou par courrier postal à Creative Commons, 171 Second Street,
# Suite 300, San Francisco, California 94105, USA.
# L'utilisation de ce logiciel pour des opérations financières réelles
# peut entrainer un certain risque. En effet l'intérêt d'utiliser une
# calculette est d'isoler votre carte bancaire des vilains malwares.
# L'utiliser sur un lecteur non sécurisé, c'est risquer qu'un keylogger
# intercepte votre PIN, qu'un malware accède aux informations de votre carte,
# voire qu'il intercepte votre transaction pour la modifier ou qu'il procède
# lui-même à ses propres transactions.
# LIMITATION DE RESPONSABILITE
# DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, LE DONNEUR DE LICENCE NE
# SERA EN AUCUN CAS RESPONSABLE A VOTRE EGARD, POUR QUELQUE PREJUDICE QUE
# CE SOIT, DIRECT OU INDIRECT, MATERIEL OU MORAL, RESULTANT DE LÕEXECUTION
# DE LA PRESENTE LICENCE OU DE LÕUTILISATION DE LÕOEUVRE, MEME SI LE DONNEUR
# DE LICENCE A ETE INFORME DE LA POSSIBILITE DE TELS PREJUDICES.
# Using this software for real financial operations can lead to some risks.
# Indeed advantage of using a standalone reader is is to isolate your banking
# card from big bad malwares.
# Using it in a non-secured reader is taking risk that a keylogger intercepts
# your PIN, a malware accesses to your card informations, or even intercepts
# your transaction to modify it or operates its own transactions.
# Limitation of Liability.
#
# IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
# WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO CONVEYS THE PROGRAM,
# BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
# INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY
# TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA
# BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES
# OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN
# IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGES.
# Version:
# cf setup.py
#
# History:
# cf git log
# All refs to "book" are from "Implementing Electronic Card Payment Systems"
# by Cristian Radu
import sys
import argparse
from EMVCAPfoo import *
from EMVCAPcore import *
# Hack for bogus reader
# Do not change it yourself, the code will detect it automatically
hack_ACR38U = False
def AreYouSure():
# print """
#***************************************************************************
#Using this software for real financial operations can lead to some risks.
#Indeed advantage of using a standalone reader is is to isolate your banking
#card from big bad malwares.
#Using it in a non-secured reader is taking risk that a keylogger intercepts
#your PIN, a malware accesses to your card informations, or even intercepts
#your transaction to modify it or operates its own transactions.
#***************************************************************************
#Are you sure you want to continue?
#"""
# resp = raw_input('If so, type \'YES\', or anything else to quit:')
# if resp != 'YES':
# print 'Bye!'
# sys.exit()
print('Processing...')
def MyListReaders():
print('Available readers:')
try:
readers = smartcard.System.readers()
if len(readers) == 0:
print('Warning: no reader found!')
else:
for i in range(len(readers)):
print(i, ' :', readers[i])
except smartcard.pcsc.PCSCExceptions.EstablishContextException:
print('Warning: cannot connect to PC/SC daemon!')
print('foo: provides fake reader and card', end=' ')
print('for demo/debug purposes')
return
def MyConnect(reader_match=None, debug=False):
if reader_match is not None and len(reader_match) >= 3 and \
reader_match[:3] == "foo":
return MyConnectFoo(reader_match, debug)
reader = None
try:
readers = smartcard.System.readers()
if len(readers) == 0:
print('error: no reader found!')
return None
except smartcard.pcsc.PCSCExceptions.EstablishContextException:
print('Cannot connect to PC/SC daemon!')
return None
if reader_match is not None:
try:
reader_index = int(reader_match)
reader = readers[reader_index]
except:
for r in readers:
if reader_match in repr(r):
reader = r
break
if reader is None:
print('error: no reader found according to option -r', end=' ')
print(reader_match)
return None
if reader is None:
reader = readers[0]
try:
connection = reader.createConnection()
except:
print('Fail connecting to', reader)
return None
if repr(reader).find('ACR38U') != -1:
# Hack for bogus reader
global hack_ACR38U
hack_ACR38U = True
try:
connection.connect()
except (smartcard.Exceptions.CardConnectionException, smartcard.Exceptions.NoCardException):
print('No card found!')
del(connection)
return None
atr = connection.getATR()
if (args.warmreset == 'yes') or \
(args.warmreset == 'auto' and atr[0] == 0x3F):
# inverse convention
# seen on French cards with another ATR behind soft-reset
# let's try...
if args.debug:
print("ATR: " + \
''.join(["%02X" % i for i in connection.getATR()]))
print("Trying a warm reset to get another ATR...")
result, activeProtocol = smartcard.scard.SCardReconnect(
connection.component.hcard,
smartcard.scard.SCARD_SHARE_EXCLUSIVE,
smartcard.scard.SCARD_PROTOCOL_ANY,
smartcard.scard.SCARD_RESET_CARD)
if result != smartcard.scard.SCARD_S_SUCCESS:
print('Warm reset failed!')
del(connection)
return None
return connection
def myTransmit(connection, CAPDU, debug=False, maskpin=True,
force_nodata=False):
# In T=0 mode, add P3=00 if there is no P3
if connection.getProtocol() == connection.T0_protocol:
if (len(CAPDU) / 2) <= 4:
CAPDU += "00"
# In T=1 mode, add Le=00 when we expect data
# We try to guess if the command expects data (default) or not
# but you can use arg force_nodata to tell cmd doesn't expect data in resp
elif connection.getProtocol() == connection.T1_protocol:
if force_nodata:
pass
# PinVerify, no data expected
elif CAPDU[2:4] == "20":
pass
else:
CAPDU += "00"
if debug:
if maskpin and CAPDU[:4] == "0020":
print("CAPDU: " + CAPDU[:12] +\
"*** (masked as it contains PIN info)")
else:
print("CAPDU: " + CAPDU)
(RAPDU, sw1, sw2) = connection.transmit(hex2lint(CAPDU))
if debug:
print("RAPDU(%02X %02X): %s" % (sw1, sw2, lint2hex(RAPDU)))
if (sw1 != 0x61) and (sw1 != 0x6c):
return (RAPDU, sw1, sw2)
if sw1 == 0x61: # More bytes available
if hack_ACR38U and (((sw2 + 6) % 64) == 0):
sw2-=1
CAPDU = '00C00000' + ("%02X" % sw2)
if sw1 == 0x6c: # Wrong length
CAPDU = CAPDU[:4 * 2] + ("%02X" % sw2)
if debug:
print("CAPDU: " + CAPDU)
(RAPDU, sw1, sw2) = connection.transmit(hex2lint(CAPDU))
if debug:
print("RAPDU(%02X %02X): %s" % (sw1, sw2, lint2hex(RAPDU)))
if (sw1 != 0x61) and (sw1 != 0x6c):
return (RAPDU, sw1, sw2)
if sw1 == 0x61: # More bytes available
CAPDU = '00C00000' + ("%02X" % sw2)
if debug:
print("CAPDU: " + CAPDU)
(RAPDUtmp, sw1, sw2) = connection.transmit(hex2lint(CAPDU))
if debug:
print("RAPDU(%02X %02X): %s" % (sw1, sw2, lint2hex(RAPDUtmp)))
return (RAPDU + RAPDUtmp, sw1, sw2)
parser = argparse.ArgumentParser(description='EMV-CAP calculator',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''\
Examples:
%(prog)s --listreaders
%(prog)s --listapps
%(prog)s --listapps --debug --reader foo
%(prog)s -m1 123456
%(prog)s -m2
%(prog)s -m2 1000 3101234567
''')
group1 = parser.add_argument_group('Standalone options')
group1.add_argument('-l', '--listreaders', dest='listreaders',
action='store_true', default=False,
help='print list of available readers and exit')
group1.add_argument('-L', '--listapps', dest='listapps',
action='store_true', default=False,
help='print list of available applications on the card ' +\
'and exit')
group1.add_argument('--tlv', dest='parsetlv',
action='store',
type=str,
help='parse a hex string into TLV elements')
group2 = parser.add_argument_group('Global options')
group2.add_argument('-r', '--reader', dest='reader_match',
metavar='{<index>, <reader_substring>}',
help='select one specific reader with reader index, ' +\
'name string or sub-string otherwise first reader ' +\
'found will be used. ')
group2.add_argument('-d', '--debug', dest='debug',
action='store_true', default=False,
help='print exchanged APDU for debugging')
group2.add_argument('-v', '--verbose', dest='verbose',
action='store_true', default=False,
help='print APDU parsing')
group3 = parser.add_argument_group('Modes and data')
group3.add_argument('-m', '--mode', dest='mode',
action='store',
type=int,
choices=[1, 2],
help='M1/M2 mode selection (mandatory, unless -l or -L ' +\
'is used)')
# We've to use type str for mdata instead of int to not mangle
# most left zeroes if any
group3.add_argument('mdata', metavar='N', type=str, nargs='*', \
help='number(s) as M1/M2 data: max one 8-digit number ' +\
'for M1 and max 10 10-digit numbers for M2')
group3.add_argument('--warmreset', dest='warmreset',
action='store',
type=str,
choices=['auto', 'yes', 'no'],
default='auto',
help='Warm reset: yes / no / auto (default) ' +\
'If \'auto\' it will perform a warm reset if ' +\
'the ATR starts with 3F (indirect convention)')
args = parser.parse_args()
if args.listapps:
args.verbose = True
if args.mode is None and args.listreaders is False and \
args.listapps is False and args.parsetlv is None:
print('error: argument -m/--mode is required')
parser.print_usage()
sys.exit()
if args.mode == 1 and len(args.mdata) > 1:
print('error: max one number in mode1 please')
parser.print_usage()
sys.exit()
# Check that mdata strings are actual numbers
for i in args.mdata:
assert i.isdigit()
if args.parsetlv:
print(TLVparser(
bytes.fromhex(args.parsetlv.replace(":", ""))))
sys.exit()
import smartcard
if args.listreaders:
MyListReaders()
sys.exit()
connection = MyConnect(args.reader_match, args.debug)
if connection is None:
sys.exit()
# ----------------------------------------------------------------------------
# ATR
if args.debug:
print("ATR: " + ''.join(["%02X" % i for i in connection.getATR()]))
# ----------------------------------------------------------------------------
# Select Application:
current_app = None
if args.verbose:
print('Trying PSE: accessing 1PAY.SYS.DDF01 file...')
file = '1PAY.SYS.DDF01'
CAPDU = '00A40400%02X' % len(file) + file.encode('ascii').hex()
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
if len(RAPDU) != 0:
parsedRAPDU = TLVparser(RAPDU)
if args.debug:
print(parsedRAPDU)
assert 0x6F in parsedRAPDU
fci_template = parsedRAPDU[parsedRAPDU.index(0x6F)]
assert 0xA5 in fci_template
fci_p_template = fci_template.get(0xA5)
assert 0x88 in fci_p_template
sfi = int(fci_p_template.get(0x88).V, 16)
record = 1
p2 = (sfi << 3) + 0b100 # means P1 to be interpreted as a record
p1 = 0x01
if args.verbose:
print('Read record %02X of SFI %02X...' % (record, sfi))
CAPDU = '00B2%02X%02X' % (p1, p2)
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
parsedRAPDU = TLVparser(RAPDU)
if args.debug:
print(parsedRAPDU)
assert 0x70 in parsedRAPDU
aef_data_template = parsedRAPDU[parsedRAPDU.index(0x70)]
if 0x61 in aef_data_template:
aidList = [app['AID'] for app in ApplicationsList]
for application_template in aef_data_template.get(0x61, multi=True):
assert 0x4F in application_template
aid = application_template.get(0x4F).V
if 0x50 in application_template:
label = application_template.get(0x50).prettyV
if args.verbose:
print("Application detected: %s (%s)" % (label, aid))
if aid in aidList:
if args.verbose:
print("Application already in pre-defined list,", end=' ')
print("skipping...")
else:
if args.verbose:
print("Application not yet in pre-defined list,", end=' ')
print("adding it...")
ApplicationsList.append({'name': label, 'description': label, \
'AID': aid})
if args.verbose:
print('Trying list of pre-defined applications:')
for app in ApplicationsList:
CAPDU = '00A40400' + ("%02X" % (int)(len(app['AID']) / 2)) + app['AID']
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
if len(RAPDU) != 0:
if current_app is None:
current_app = app
elif current_app['onVasco810?'] is False and app['onVasco810?'] is True:
current_app = app
if args.verbose:
print("Application detected: " + app['description'])
if args.debug:
print(lint2hex(RAPDU))
print(TLVparser(RAPDU))
if args.listapps:
# We're done
sys.exit()
import getpass
if current_app is None or current_app['onVasco810?'] is False:
print('No suitable app found, exiting')
sys.exit()
app_is_cap_dpa = False
if current_app['mode'] == 'CAP' or current_app['mode'] == 'DPA':
app_is_cap_dpa = True
if app_is_cap_dpa is False:
print('Could not find an EMV-CAP or Visa DPA application!')
if args.verbose or app_is_cap_dpa is False:
print('Will use the following application:', end=' ')
print(current_app['name'], end=' ')
print('(type ' + current_app['mode'] + ')')
if not hasattr(connection, 'foo'):
AreYouSure()
# Do a select again as we might have selected also other apps while scanning:
CAPDU = '00A40400' + ("%02X" % (len(current_app['AID']) / 2)) +\
current_app['AID']
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
parsedRAPDU = TLVparser(RAPDU)
assert 0x6F in parsedRAPDU
fci_template = parsedRAPDU[parsedRAPDU.index(0x6F)]
assert 0x84 in fci_template
tlv_aid = fci_template.get(0x84)
tlv_pdol = None
psn_to_be_used = False
cardholder_nationality = False
df07 = False
if 0xA5 in fci_template:
fci_proprietary_template = fci_template.get(0xA5)
if 0x9F38 in fci_proprietary_template:
tlv_pdol = fci_proprietary_template.get(0x9F38)
if 0xBF0C in fci_proprietary_template:
fci_issuer_discretionary_data = fci_proprietary_template.get(0xBF0C)
if 0x9F55 in fci_issuer_discretionary_data:
issuer_authentication_flag = \
fci_issuer_discretionary_data.get(0x9F55)
psn_to_be_used = \
(bytes.fromhex(issuer_authentication_flag.V) & 0x40) != 0
if 0x5F2C in fci_issuer_discretionary_data:
cardholder_nationality = \
fci_issuer_discretionary_data.get(0x5F2C)
if 0xDF07 in fci_issuer_discretionary_data:
df07 = \
fci_issuer_discretionary_data.get(0xDF07)
# ----------------------------------------------------------------------------
# Initiate transaction / Get Processing Options:
if args.verbose:
print('Get Processing Options...')
# From book, ch 6.2.1
pdol_data = dol_filling(tlv_pdol, current_app['mode'], debug=args.debug)
if pdol_data is None:
sys.exit()
CAPDU = '80A80000%02X83%02X%s' % \
((len(pdol_data) / 2) + 2, (len(pdol_data) / 2), pdol_data)
if args.debug:
print(TLVparser(hex2lint(CAPDU[5 * 2:])))
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
parsedRAPDU = TLVparser(RAPDU)
if args.debug:
print(parsedRAPDU)
files = []
if 0x80 in parsedRAPDU:
# Answer is not TLV encoded, we only get values according to a template
if args.verbose:
print('Warning: answer to Get Processing Options is not TLV,', end=' ')
print('attempting to reconstruct it...')
parsedRAPDU = reconstruct(parsedRAPDU, template_processingoptions)
if args.debug:
print(parsedRAPDU)
assert 0x77 in parsedRAPDU
rsp_msg_template2 = parsedRAPDU[parsedRAPDU.index(0x77)]
if 0x94 in rsp_msg_template2:
application_file_locator = rsp_msg_template2.get(0x94)
raw_afl = bytes.fromhex(application_file_locator.V)
for i in range(application_file_locator.L / 4):
files.append([ord(x) for x in raw_afl[i * 4:i * 4 + 4]])
# ----------------------------------------------------------------------------
# Read files
hex_ipb = False
for f in files:
# From book, ch 4.3.2.1
sfi = f[0] >> 3
p2 = (sfi << 3) + 0b100 # means P1 to be interpreted as a record
for record in range(f[1], f[2] + 1):
p1 = record
if args.verbose:
print('Read record %02X of SFI %02X...' % (record, sfi))
CAPDU = '00B2%02X%02X' % (p1, p2)
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
# For simulation we skip some files
if hasattr(connection, 'foo') and len(RAPDU) == 0:
continue
parsedRAPDU = TLVparser(RAPDU)
if args.debug:
print(parsedRAPDU)
assert 0x70 in parsedRAPDU
aef_data_template = parsedRAPDU[parsedRAPDU.index(0x70)]
if 0x5F34 in aef_data_template:
hex_psn = aef_data_template.get(0x5F34).V
if 0x9F55 in aef_data_template:
issuer_authentication_flag = \
aef_data_template.get(0x9F55)
psn_to_be_used = \
(bytes.fromhex(issuer_authentication_flag.V)[0] & 0x40)\
!= 0
if 0x9F56 in aef_data_template:
hex_ipb = aef_data_template.get(0x9F56).V
if args.verbose:
print('Issuer Proprietary Bitmap: ' + hex_ipb)
if 0x8C in aef_data_template:
tlv_cdol1 = aef_data_template.get(0x8C)
if 0x8D in aef_data_template:
tlv_cdol2 = aef_data_template.get(0x8D)
if psn_to_be_used:
assert hex_psn
# Belgian cards will nead specific tuning:
if isinstance(cardholder_nationality, TLV) and \
cardholder_nationality.V == "0056" and \
isinstance(df07, TLV) and \
bytes.fromhex(df07.V)[:6] == "BKS056":
country = "BE"
else:
country = "any"
if hex_ipb is False:
print('IPB not found')
if country == "BE":
print('Using default Belgian IPB function')
hex_ipb = "IPB_BE"
elif current_app['mode'] == 'VISA':
print('Using default VISA IPB')
hex_ipb = "0000FFFFFF0000000000000000000020B938"
else:
print('Sorry, at the moment we don\'t know how to handle', end=' ')
print('absence of IPB')
sys.exit()
elif current_app['mode'] == 'BANCONTACT' and country == "BE":
print('Forcing default Belgian IPB function even if IPB found!')
hex_ipb = "IPB_BE"
assert tlv_cdol1
assert tlv_cdol2
# ------------------------------------------------------------------------
# Get PIN Try Counter
# From book, ch 6.6.4
CAPDU = '80CA9F17'
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
parsedRAPDU = TLVparser(RAPDU)
if args.debug:
print(parsedRAPDU)
assert 0x9F17 in parsedRAPDU
ntry = int(parsedRAPDU[parsedRAPDU.index(0x9F17)].V, 16)
if ntry < 3 or args.verbose:
print('Still %i PIN tries available!' % ntry)
# ------------------------------------------------------------------------
# Verify PIN
# From book, ch 6.6.4
if hasattr(connection, 'foo'):
print('Simulation mode, PIN entry skipped')
pin = '1234'
else:
pin = getpass.getpass('Enter PIN (enter to abort) :')
while len(pin) < 4 or len(pin) > 12 or not pin.isdigit():
if len(pin) == 0:
sys.exit()
pin = getpass.getpass('Error! I expect a proper PIN: ')
CAPDU = '00200080082%i' % len(pin) + pin + 'F' * (14 - len(pin))
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
if sw1 != 0x90 or sw2 != 00:
print('Error wrong PIN!!!')
sys.exit()
del(pin)
# ----------------------------------------------------------------------------
# Generate Application Cryptogram ARQC
if args.verbose:
print('Generate Application Cryptogram ARQC...')
# TODO handle CAP Sign, with amount into transaction_value and
# account into unpredictable_number
transaction_value = 0
unpredictable_number = 0
if args.mode == 1 and len(args.mdata) == 1:
unpredictable_number = int(args.mdata[0])
# TODO for ABN-AMRO NL there is apparently a scrambling of UN,
# cf [schouwenaar] annex B
cdol1_data = dol_filling(tlv_cdol1, current_app['mode'], country, \
transaction_value, unpredictable_number, debug=args.debug)
if cdol1_data is None:
sys.exit()
CAPDU = '80AE8000%02X%s' % (len(cdol1_data) / 2, cdol1_data)
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
parsedRAPDU = TLVparser(RAPDU)
if args.debug:
print(parsedRAPDU)
if 0x80 in parsedRAPDU:
# Answer is not TLV encoded, we only get values according to a template
if args.verbose:
print('Warning: answer to GenerateAC is not TLV,', end=' ')
print('attempting to reconstruct it...')
parsedRAPDU = reconstruct(parsedRAPDU, template_generatearqc)
if args.debug:
print(parsedRAPDU)
assert 0x77 in parsedRAPDU
resp = parsedRAPDU[parsedRAPDU.index(0x77)]
assert 0x9F10 in resp
hex_iad = resp.get(0x9F10).V
assert 0x9F26 in resp
hex_ac = resp.get(0x9F26).V
assert 0x9F27 in resp
hex_cid = resp.get(0x9F27).V
assert 0x9F36 in resp
hex_atc = resp.get(0x9F36).V
if args.verbose:
print('Got CID=%s ATC=%s AC=%s IAD=%s' % \
(hex_cid, hex_atc, hex_ac, hex_iad))
# ----------------------------------------------------------------------------
# Generate Application Cryptogram AAC
if args.verbose:
print('Generate Application Cryptogram AAC...')
cdol2_data = dol_filling(tlv_cdol2, current_app['mode'], country, \
transaction_value, unpredictable_number, debug=args.debug)
if cdol2_data is None:
sys.exit()
CAPDU = '80AE0000%02X%s' % (len(cdol2_data) / 2, cdol2_data)
(RAPDU, sw1, sw2) = myTransmit(connection, CAPDU, args.debug)
parsedRAPDU = TLVparser(RAPDU)
if args.debug:
print(parsedRAPDU)
if 0x80 in parsedRAPDU:
# Answer is not TLV encoded, we only get values according to a template
if args.verbose:
print('Warning: answer to GenerateAC is not TLV,', end=' ')
print('attempting to reconstruct it...')
parsedRAPDU = reconstruct(parsedRAPDU, template_generatearqc)
if args.debug:
print(parsedRAPDU)
# ----------------------------------------------------------------------------
# From here no more interaction with the card needed
# ----------------------------------------------------------------------------
# Mixing TDS with cryptogram if Mode2 with TDS
if args.mode == 2 and len(args.mdata) > 0:
if args.verbose:
print('Mixing TDS with cryptogram...')
hex_ac = mix_tds(hex_ac, args.mdata, args.debug)
# ----------------------------------------------------------------------------
# Display OTP
if args.verbose:
print('Computing OTP...')
if hex_ipb == "IPB_BE":
otp = generate_otp_be(hex_atc, hex_ac, debug=args.debug)
elif psn_to_be_used:
otp = generate_otp(hex_cid, hex_atc, hex_ac, hex_iad, hex_ipb, \
hex_psn, debug=args.debug)
else:
otp = generate_otp(hex_cid, hex_atc, hex_ac, hex_iad, hex_ipb, \
debug=args.debug)
print('Response: %i' % otp)
if len("%i" % otp) < 8:
print('WARNING: some banks want to see exactly 8 digits')
print('so you may have to use the following response instead:')
print('Response: %08i' % otp)