-
Notifications
You must be signed in to change notification settings - Fork 13
/
apdu
executable file
·312 lines (252 loc) · 9.35 KB
/
apdu
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
#!/usr/bin/env python
# APDU shell
#
# Copyright (c) 2014 Goran Rakic <grakic@devbase.net>
import sys, os, stat
import getopt
from time import sleep
from threading import Thread, Event
from subprocess import Popen, PIPE
from fcntl import fcntl, F_GETFL, F_SETFL
from smartcard.System import readers
from smartcard.CardRequest import CardRequest
from smartcard.util import *
VERSION = "1.0"
HELLO = "APDU shell v%s" % VERSION
def error(e, lineno = None):
out = " Error"
if lineno is not None:
out += " on line %d" % lineno
out += ": " + str(e)
return out
class Connection(object):
__connection = None
class Monitoring(Thread):
def __init__(self, observer, reader):
Thread.__init__(self)
self.reader = reader
self.observer = observer
self.stopEvent = Event()
self.stopEvent.clear()
self.initializedEvent = Event()
self.initializedEvent.clear()
self.setDaemon(True)
self.card = None
def run(self):
self.cardrequest = CardRequest(timeout=0.5, readers=[reader])
while not self.stopEvent.isSet():
try:
card = self.cardrequest.waitforcardevent()
if card != self.card:
if not card:
self.observer.removed()
else:
self.observer.inserted(card[0])
self.card = card
self.initializedEvent.set()
except Exception as e:
print >> sys.stderr, "Connection error:", e
def __init__(self, reader):
self.monitoring = Connection.Monitoring(self, reader)
self.monitoring.start()
while not self.monitoring.initializedEvent.isSet():
sleep(0.1)
def inserted(self, card):
self.__connection = card.createConnection()
self.__connection.connect()
# print "Card connected: %s" % toHexString(card.atr)
def removed(self):
self.__connection = None
# print "Card removed"
def send(self, apdu, output=None, show_sent=True):
if not self.__connection:
raise Exception("Card not connected")
# print input
if show_sent:
print ">> %s" % toHexString(apdu)
data, sw1, sw2 = self.__connection.transmit(apdu)
# print output and data
print "<< %02X %02X%s" % (sw1, sw2, ", %d bytes" % len(data) if data else "")
if data:
if output:
# save data
with open(output, "w+") as f:
f.write(HexListToBinString(data))
print " Output saved to %s" % output
else:
# pack 8 bits into bytes, write 4 bytes per line
bytes = [toHexString(data[i:i+8]) for i in range(0, len(data), 8)]
print "\n".join([" "+" ".join(bytes[i:i+4]) for i in range(0, len(bytes), 4)])
# return response
return data + [sw1, sw2]
def close(self):
self.monitoring.stopEvent.set()
self.connection = None
def hexByteToInt(byte):
try:
return int(byte, 16)
except ValueError as e:
if "invalid literal" in str(e):
raise ValueError("Input error at %s" % str(e)[-4:])
else:
raise
def parse(line):
apdu = []
line, _, output = line.partition('>')
line = line.split(' ')
for part in line:
if len(part) % 2 == 0:
apdu.extend([hexByteToInt(part[2*i:2*i+2]) for i in range(len(part)/2)])
elif len(part) == 1:
apdu.append(hexByteToInt(part))
else:
raise ValueError("Input error at: '%s'" % part)
output = output.strip()
return apdu, output or None
def repl_cmd_run(connection, command, lineno, interactive):
p = Popen(command, stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = True, bufsize=0)
command_lineno = 0
while True:
command_lineno += 1
raw_line = p.stdout.readline()
if not raw_line and p.returncode is not None:
if p.returncode == 0:
print " Command completed successfully"
return
else:
raise Exception("Command exited with status %d" % p.returncode)
line, _, comment = raw_line.partition("#")
line, comment = line.strip(), comment.strip()
if comment:
print "##", comment
if line:
try:
apdu, output = parse(line)
response = connection.send(apdu, output, True)
except Exception as e:
error = "While executing output line %d: '%s'" % (command_lineno, raw_line)
if not interactive:
error += " from command %s on line %d" % (command, lineno)
error += ":\n %s" % e
raise Exception(error)
p.stdin.write(toHexString(response) + "\n")
p.stdin.flush()
p.poll()
def select_reader(name=None, index=None):
readers_all = readers()
if index is None:
for reader in readers_all:
if name in str(reader):
return reader
raise Exception("Unknown reader %s" % name)
else:
if index < len(readers_all):
return readers_all[index]
else:
raise Exception("Unknown reader number #%d" % index)
def list_readers():
print "Listing readers:"
for i, reader in enumerate(readers()):
reader = str(reader)
print " #%d" % i, reader[:60], "..." if len(reader)>60 else ""
print
print "Use -r <num index> or -r <part of the name> to select non-default reader."
def usage():
print """
%s
Usage: %s [options]
-l, --list
List all PC/SC readers
-r <reader>, --reader <reader>
Select a reader where <reader> is either numeric index starting
at 0 or a part of the reader name. Default: reader with index 0
-h, --help
Display this help message
""" % (HELLO, sys.argv[0])
if __name__ == "__main__":
reader = None
# Parse options
try:
opts, args = getopt.getopt(sys.argv[1:], "hr:l", ["help", "reader=", "list"])
except getopt.GetoptError as e:
print >> sys.stderr, str(e)
usage()
sys.exit(2)
for o, a in opts:
if o in ("-r", "--reader"):
reader = a
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-l", "--list"):
list_readers()
sys.exit()
# Check TTY interactivity
mode = os.fstat(0).st_mode
interactive = not (stat.S_ISFIFO(mode) or stat.S_ISREG(mode))
# Welcome message
if interactive:
import readline
print """
%s
Type APDU as hex string. Append '> <file>' to save data output to a file. Comments starts with a '#'.
RUN <command> runs an external command, executing APDUs from command output and passing full response
to input. Use SAVE <file> to save command history, CLEAR to clear it.
""" % HELLO
# Connect reader
try:
if not reader:
reader = select_reader(index=0)
elif reader.isdigit():
reader = select_reader(index=int(reader))
else:
reader = select_reader(reader)
connection = Connection(reader)
except Exception as e:
print >> sys.stderr, str(e)
sys.exit(1)
# Launch "REPL"
history = []
lineno = 0
try:
while True:
lineno += 1
save_history = True
line, _, comment = raw_input(">> " if interactive else "").partition("#")
line, comment = line.strip(), comment.strip()
if comment and not interactive:
print "##", comment
if line:
try:
# save command
if line.lower().startswith("save"):
filename = line[4:].strip()
with open(filename, "w+") as f:
f.writelines([l+("# "+c if c else "")+"\n" for l,c in history])
print " History saved to %s" % filename, interactive
save_history = False
# clear command
elif line.lower().startswith("clear"):
history = []
echo_message("History cleared", interactive)
save_history = False
# run external process
elif line.lower().startswith("run"):
command = line[3:].strip()
repl_cmd_run(connection, command, lineno, interactive)
# send apdu
else:
apdu, output = parse(line)
connection.send(apdu, output, not interactive)
except Exception as e:
print >> sys.stderr, error(e, lineno if not interactive else None)
save_history = False
# save history
if save_history:
history.append((line, comment))
sys.stdout.flush()
except (KeyboardInterrupt, EOFError):
if interactive:
print
connection.close()
sys.exit()