-
Notifications
You must be signed in to change notification settings - Fork 48
/
read_pcap.py
565 lines (456 loc) · 19.9 KB
/
read_pcap.py
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
#!/usr/bin/env python
import sys
import binascii
import pyshark # pip install pyshark
from bitstring import BitArray, BitStream, pack # pip install bitstring
import crc16 # pip install crc16
import Crypto.Cipher.AES # pip install PyCrypto
import argparse
INCOMING_ENDPOINT = 0x83 # This is the incoming endpoint we want data from
OUTGOING_ENDPOINT = 0x04 # This is the outgoing endpoint we want data from
USB_PACKET_SIZE = 60
class MedtronicSession:
radioChannel = None
stickSerial = None
pumpSerial = None
hexKey = None
def __init__( self, hexKey ):
self.hexKey = hexKey
@property
def KEY( self ):
return binascii.unhexlify( self.hexKey )
@property
def IV( self ):
return binascii.unhexlify( "{0:02x}{1}".format( self.radioChannel, self.hexKey[2:] ) )
class BayerBinaryMessage( object ):
IN = 0x0
OUT = 0x1
@property
def header( self ):
self.stream.bytepos = 0x0
return self.stream.readlist( '2*bytes:1' )
@property
def pumpId( self ):
self.stream.bytepos = 0x2
return self.stream.read( 'bytes:6' )
@property
def unknownBytes1( self ):
self.stream.bytepos = 0x8
return self.stream.read( 'int:80' ) # This is 80 bits of data, 10 bytes
@property
def messageType( self ):
self.stream.bytepos = 0x12
return self.stream.read( 'uint:8' )
@property
def sequenceNumber( self ):
self.stream.bytepos = 0x13
return self.stream.read( 'uintle:32' ) # Assuming for now it's a regular int
@property
def unknownBytes2( self ):
self.stream.bytepos = 0x17
return self.stream.read( 'int:40' ) # This is 40 bits of data, 5 bytes
@property
def messageSize( self ):
self.stream.bytepos = 0x1c
return self.stream.read( 'uintle:32' ) # Assuming for now it's a regular int
@property
def messageChecksum( self ):
self.stream.bytepos = 0x20
return self.stream.read( 'uintle:8' )
@property
def payload( self ):
# get size here, because properties advance the stream pointer, and we want it to
# stay set when we read the payload
payloadSize = self.messageSize
self.stream.bytepos = 0x21
return self.stream.read( 'bytes:%d' % ( payloadSize ) )
@classmethod
def MessageFactory( cls, stream, messageDirection, pumpSession ):
stream.bytepos = 0x0
if( stream.readlist( '2*bytes:1' ) != [ 'Q', '\x03' ] ):
return None
stream.bytepos = 0x12
messageType = stream.read( 'uint:8' )
print "MESSAGE TYPE: %s, Direction: %s" % ( hex(messageType), messageDirection )
if( messageType == 0x10 and messageDirection == BayerBinaryMessage.OUT ):
return OpenConnectionRequest( stream )
elif( messageType == 0x10 and messageDirection == BayerBinaryMessage.IN ):
return MedtronicMessage( stream, pumpSession )
elif( messageType == 0x14 and messageDirection == BayerBinaryMessage.IN ):
return ReadInfoResponse( stream )
elif( messageType == 0x16 and messageDirection == BayerBinaryMessage.OUT ):
return BayerBinaryMessage( stream )
elif( messageType == 0x86 and messageDirection == BayerBinaryMessage.IN ):
return BayerBinaryMessage( stream )
elif( messageType == 0x12 ):
stream.bytepos = 0x21
medtronicSendType = stream.read( 'uint:8' )
if( medtronicSendType == 0x03 ):
return NegotiateChannel( stream, pumpSession )
elif( medtronicSendType == 0x05 ):
return SendMessageRequest( stream, pumpSession )
elif( messageType == 0x81 ):
return SendMessageResponse( stream )
elif( messageType == 0x80 ):
return ReceiveMessage( stream, pumpSession )
elif( ( stream.length / 8 ) > 33 ):
return MedtronicMessage( stream, pumpSession )
else:
return BayerBinaryMessage( stream )
def __init__( self, stream ):
self.stream = stream
if( self.header != [ 'Q', '\x03' ] ):
return
# If our Unknown Bytes are ever anything other than padded nulls, we want to know about it!
self.checkNullBytes( 'unknownBytes1' )
self.checkNullBytes( 'unknownBytes2' )
expectedMessageSize = 0x21 + self.messageSize
if( ( self.stream.length / 8 ) != expectedMessageSize ):
print "Message size mismatch. Expecting message to be '%d' bytes, this stream has '%d' bytes" % ( expectedMessageSize, ( self.stream.length / 8 ) )
raise Exception
# Validate the checksum
calcCrc = self.makeMessageCrc() # only calculate it once for the compare and the print
if( calcCrc != self.messageChecksum ):
print "Message checksum doesn't match. Expected '%#x', calculated '%#x'" % ( self.messageChecksum, calcCrc )
raise Exception
def checkNullBytes( self, field ):
if( getattr( self, field ) != 0 ):
print '*** SOMETHING NEW! %s is more than it seems' % ( field )
raise Exception
def makeMessageCrc( self ):
# unpack is the same as readlist, but starts from the beginning of the stream
bytes = self.stream.unpack( '%s*uint:8' % ( self.stream.length / 8 ) )
# The 33rd byte is the checksum itself, and shouldn't be included in the message checksum
del bytes[32]
return sum(bytes) & 0xff
def __str__( self ):
if( self.header == [ 'Q', '\x03' ] ):
# Binary Bayer message
return '%s, %s, %s, %#x, %d, %#x, %d, %#x' % ( self.header, self.pumpId, self.unknownBytes1, self.messageType, self.sequenceNumber, self.unknownBytes2, self.messageSize, self.messageChecksum )
else:
return '%s' % ( self.header )
class OpenConnectionRequest( BayerBinaryMessage ):
def __str__( self ):
self.stream.bytepos = 0x21
return "%s\nOpen HMAC: %s" % ( BayerBinaryMessage.__str__(self), self.stream.read( 'bytes:32' ).encode('hex') )
class ReadInfoResponse( BayerBinaryMessage ):
@property
def delimiter1( self ):
self.stream.bytepos = 0x21
return self.stream.read( 'uint:24' )
@property
def stickIdentifier( self ):
self.stream.bytepos = 0x24
return self.stream.read( 'uint:16' )
@property
def stickSerial( self ):
self.stream.bytepos = 0x26
return self.stream.read( 'uint:24' )
@property
def delimiter2( self ):
self.stream.bytepos = 0x29
return self.stream.read( 'uint:24' )
@property
def pumpIdentifier( self ):
self.stream.bytepos = 0x2c
return self.stream.read( 'uint:16' )
@property
def pumpSerial( self ):
self.stream.bytepos = 0x2e
return self.stream.read( 'uint:24' )
@property
def unknownBytes( self ):
self.stream.bytepos = 0x31
return self.stream.read( 'bytes:3' ).encode( 'hex' )
def __init__( self, stream ):
BayerBinaryMessage.__init__( self, stream )
# Response looks like this:
# 0023f7 0682 <stickID in Big Endian> 0023f7 45ee <pumpID in Big Endian> <Unknown bytes>
assert self.stickIdentifier == MedtronicMessage.STICK_IDENTIFIER
assert self.pumpIdentifier == MedtronicMessage.PUMP_IDENTIFIER
assert self.delimiter1 == MedtronicMessage.DELIMITER
assert self.delimiter2 == MedtronicMessage.DELIMITER
def __str__( self ):
return "%s\nStick serial: '%d', Pump serial: '%d', Unknown Bytes: '%s'" % ( BayerBinaryMessage.__str__(self), self.stickSerial, self.pumpSerial, self.unknownBytes )
class MedtronicMessage( BayerBinaryMessage ):
STICK_IDENTIFIER = 0x0682
PUMP_IDENTIFIER = 0x45ee
DELIMITER = 0x0023f7
@property
def medtronicMessage( self ):
return self.payload[0:-2]
@property
def ccitt( self ):
self.stream.bytepos = ( self.stream.length / 8 ) - 2
return self.stream.read( 'uintle:16' )
@property
def medtronicHeader( self ):
self.stream.bytepos = 0x21
return self.stream.read( 'bytes:1' )
@property
def medtronicMessageSize( self ):
self.stream.bytepos = 0x22
return self.stream.read( 'uint:8' )
def makeMessageCcitt( self ):
crc = crc16.crc16xmodem( self.medtronicMessage, 0xffff )
return crc & 0xffff
def pad( self, x, n = 16 ):
p = n - ( len( x ) % n )
return x + chr(p) * p
# Encrpytion equivalent to Java's AES/CFB/NoPadding mode
def encrypt( self, clear ):
cipher = Crypto.Cipher.AES.new(
key=pumpSession.KEY,
mode=Crypto.Cipher.AES.MODE_CFB,
IV=pumpSession.IV,
segment_size=128
)
encrypted = cipher.encrypt(self.pad(clear))[0:len(clear)]
return encrypted
# Decryption equivalent to Java's AES/CFB/NoPadding mode
def decrypt( self, encrypted ):
cipher = Crypto.Cipher.AES.new(
key=pumpSession.KEY,
mode=Crypto.Cipher.AES.MODE_CFB,
IV=pumpSession.IV,
segment_size=128
)
decrypted = cipher.decrypt(self.pad(encrypted))[0:len(encrypted)]
return decrypted
def __init__( self, stream, pumpSession ):
BayerBinaryMessage.__init__( self, stream )
calcCcitt = self.makeMessageCcitt()
if( calcCcitt != self.ccitt ):
print "CRC-CCITT doesn't match. Expected '%#x', calculated '%#x'" % ( self.ccitt, calcCcitt )
raise Exception
return
# The medtronicMessage size includes its header and the size byte
assert self.medtronicMessageSize == len( self.payload ) - 2
def __str__( self ):
return "%s\nMedtronic Payload: '%s'" % ( BayerBinaryMessage.__str__(self), self.medtronicMessage.encode('hex') )
class NegotiateChannel( MedtronicMessage ):
@property
def sequenceNumber( self ):
self.stream.bytepos = 0x23
return self.stream.read( 'uint:8' )
@property
def radioChannel( self ):
self.stream.bytepos = 0x24
return self.stream.read( 'uint:8' )
@property
def unknownBytes( self ):
self.stream.bytepos = 0x25
return self.stream.read( 'bytes:8' )
@property
def stickSerial( self ):
self.stream.bytepos = 0x2d
return self.stream.read( 'uintle:24' )
@property
def stickIdentifier( self ):
self.stream.bytepos = 0x30
return self.stream.read( 'uintle:16' )
@property
def delimiter1( self ):
self.stream.bytepos = 0x32
return self.stream.read( 'uintle:24' )
@property
def pumpSerial( self ):
self.stream.bytepos = 0x35
return self.stream.read( 'uintle:24' )
@property
def pumpIdentifier( self ):
self.stream.bytepos = 0x38
return self.stream.read( 'uintle:16' )
@property
def delimiter2( self ):
self.stream.bytepos = 0x3a
return self.stream.read( 'uintle:24' )
def __init__( self, stream, pumpSession ):
MedtronicMessage.__init__( self, stream, pumpSession )
assert self.stickIdentifier == MedtronicMessage.STICK_IDENTIFIER
assert self.pumpIdentifier == MedtronicMessage.PUMP_IDENTIFIER
assert self.delimiter1 == MedtronicMessage.DELIMITER
assert self.delimiter2 == MedtronicMessage.DELIMITER
assert self.stickSerial == pumpSession.stickSerial
assert self.pumpSerial == pumpSession.pumpSerial
def __str__( self ):
return "%s\nseqNo: %d, channel: %d, unknownBytes: '%s', Stick serial: %d, Pump serial: %d" % ( MedtronicMessage.__str__(self), self.sequenceNumber, self.radioChannel, self.unknownBytes.encode('hex'), self.stickSerial, self.pumpSerial )
class SendMessageRequest( MedtronicMessage ):
@property
def pumpSerial( self ):
self.stream.bytepos = 0x23
return self.stream.read( 'uintle:24' )
@property
def pumpIdentifier( self ):
self.stream.bytepos = 0x26
return self.stream.read( 'uintle:16' )
@property
def delimiter( self ):
self.stream.bytepos = 0x28
return self.stream.read( 'uintle:24' )
@property
def sequenceNumber( self ):
self.stream.bytepos = 0x2b
return self.stream.read( 'uint:8' )
@property
def unknownByte( self ):
self.stream.bytepos = 0x2c
return self.stream.read( 'bytes:1' )
@property
def payloadSize( self ):
self.stream.bytepos = 0x2d
return self.stream.read( 'uintle:8' )
@property
def requestBody( self ):
# get size here, because properties advance the stream pointer, and we want it to
# stay set when we read the payload
payloadSize = self.payloadSize
self.stream.bytepos = 0x2e
return self.stream.read( 'bytes:%d' % ( payloadSize ) )
def __init__( self, stream, pumpSession ):
MedtronicMessage.__init__( self, stream, pumpSession )
assert self.pumpIdentifier == MedtronicMessage.PUMP_IDENTIFIER
assert self.delimiter == MedtronicMessage.DELIMITER
assert ( 0x2e + self.payloadSize ) == ( ( self.stream.length / 8 ) - 2 ) # minus 2 bytes for the CCITT
assert self.pumpSerial == pumpSession.pumpSerial
def __str__( self ):
return "%s\nseqNo: %d, unknownByte: '%s', Pump serial: %d\nDecrypted Payload: '%s'" % ( MedtronicMessage.__str__(self), self.sequenceNumber, self.unknownByte.encode('hex'), self.pumpSerial , self.decrypt( self.requestBody ).encode('hex'))
class SendMessageResponse( MedtronicMessage ):
@property
def commandResponseCode( self ):
self.stream.bytepos = 0x23
return self.stream.read( 'uintle:16' )
@property
def unknownBytes( self ):
self.stream.bytepos = 0x25
return self.stream.read( 'bytes:7' )
@property
def sequenceNumber( self ):
self.stream.bytepos = 0x2c
return self.stream.read( 'uint:8' )
@property
def unknownByte( self ):
self.stream.bytepos = 0x2d
return self.stream.read( 'bytes:1' )
def __init__( self, stream ):
MedtronicMessage.__init__( self, stream, pumpSession )
if( self.medtronicMessageSize > 4 ):
assert self.commandResponseCode == 1024
else:
assert self.commandResponseCode == 0
def __str__( self ):
if( self.medtronicMessageSize > 4 ):
return "%s\nseqNo: %d, unknownBytes: %s, unknownByte: %s" % ( MedtronicMessage.__str__(self), self.sequenceNumber, self.unknownBytes.encode('hex'), self.unknownByte.encode('hex'))
else:
return "No extra data"
class ReceiveMessage( MedtronicMessage ):
@property
def commandResponseCode( self ):
self.stream.bytepos = 0x23
return self.stream.read( 'uintle:16' )
@property
def pumpSerial( self ):
self.stream.bytepos = 0x25
return self.stream.read( 'uintle:24' )
@property
def pumpIdentifier( self ):
self.stream.bytepos = 0x28
return self.stream.read( 'uintle:16' )
@property
def delimiter1( self ):
self.stream.bytepos = 0x2a
return self.stream.read( 'uintle:24' )
@property
def stickSerial( self ):
self.stream.bytepos = 0x2d
return self.stream.read( 'uintle:24' )
@property
def stickIdentifier( self ):
self.stream.bytepos = 0x30
return self.stream.read( 'uintle:16' )
@property
def delimiter2( self ):
self.stream.bytepos = 0x32
return self.stream.read( 'uintle:24' )
@property
def sequenceNumber( self ):
self.stream.bytepos = 0x35
return self.stream.read( 'uintle:24' )
@property
def payloadSize( self ):
self.stream.bytepos = 0x38
return self.stream.read( 'uintle:8' )
@property
def requestBody( self ):
# get size here, because properties advance the stream pointer, and we want it to
# stay set when we read the payload
payloadSize = self.payloadSize
self.stream.bytepos = 0x39
return self.stream.read( 'bytes:%d' % ( payloadSize ) )
def __init__( self, stream, pumpSession ):
MedtronicMessage.__init__( self, stream, pumpSession )
# Sometimes response is 1024 (for the channel init) of 0000 (for a failed negotiation). This has different things
assert self.commandResponseCode == 0 or self.commandResponseCode == 1536 or self.commandResponseCode == 1024
if( self.commandResponseCode == 1536 ):
assert self.pumpIdentifier == MedtronicMessage.PUMP_IDENTIFIER
assert self.pumpSerial == pumpSession.pumpSerial
assert self.stickIdentifier == MedtronicMessage.STICK_IDENTIFIER
assert self.stickSerial == pumpSession.stickSerial
assert self.delimiter1 == MedtronicMessage.DELIMITER
assert self.delimiter2 == MedtronicMessage.DELIMITER
def __str__( self ):
if( self.commandResponseCode == 1536 and self.pumpIdentifier == MedtronicMessage.PUMP_IDENTIFIER):
return "%s\nseqNo: %d, Stick serial: %d, Pump serial: %d\nDecrypted Payload: '%s'" % ( MedtronicMessage.__str__(self), self.sequenceNumber, self.stickSerial, self.pumpSerial , self.decrypt( self.requestBody ).encode('hex'))
else:
return "Haven't decoded this one yet"
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument( 'capture_file' )
parser.add_argument( 'encyption_key' )
args = parser.parse_args()
cap = pyshark.FileCapture( args.capture_file )
messageBuffer = BitStream()
i = 1
j = 0
pumpSession = MedtronicSession( args.encyption_key )
for packet in cap:
j+=1
# Make sure the data is coming from one of the USB endpoints we care about.
# Skip anything else
usbEndpoint = int( packet.usb.endpoint_number, 16 )
if( usbEndpoint != INCOMING_ENDPOINT and
usbEndpoint != OUTGOING_ENDPOINT ):
continue
usbBuffer = BitStream('0x%s' % ( packet.data.usb_capdata.replace( ':', '' ) ) )
usbHeader = usbBuffer.readlist( 'bytes:3, uint:8' )
# Validate the header
if( usbEndpoint == OUTGOING_ENDPOINT and usbHeader[0].encode( 'hex' ) != '000000' ):
print 'Unexpected USB Header. Expected "0x000000", got "0x%s".' % ( usbHeader[0].encode( 'hex' ) )
raise Exception
if( usbEndpoint == INCOMING_ENDPOINT and usbHeader[0] != 'ABC' ):
print 'Unexpected USB Header. Expected "0x414243", got "0x%s".' % ( usbHeader[0].encode( 'hex' ) )
raise Exception
messageBuffer.append( usbBuffer.read( usbHeader[1] * 8 ) )
# Clear the messageBuffer if we have a full message
# TODO - we need to be able to figure out if all 60 bytes are conusumed, but it's the end of the message
if( usbHeader[1] < USB_PACKET_SIZE ):
print >> sys.stderr, j
print >> sys.stderr, 'Message %s' % ( 'OUT' if usbEndpoint == OUTGOING_ENDPOINT else 'IN' )
print >> sys.stderr, 'Hex: %s' % ( messageBuffer.hex )
# TODO - make a bayerMessage to also handle standard command sequences and ASTM messages
if( messageBuffer.bytes[0:2] != 'Q\x03' ):
print >> sys.stderr, 'String: %s\n' % ( messageBuffer.bytes )
else:
msg = BayerBinaryMessage.MessageFactory( messageBuffer,
BayerBinaryMessage.OUT if usbEndpoint == OUTGOING_ENDPOINT else BayerBinaryMessage.IN, pumpSession )
if( msg is not None ):
if( isinstance( msg, ReadInfoResponse ) ):
pumpSession.pumpSerial = msg.pumpSerial
pumpSession.stickSerial = msg.stickSerial
elif( isinstance( msg, NegotiateChannel ) ):
pumpSession.radioChannel = msg.radioChannel
print msg
print
messageBuffer.clear()
i+=1
print "Processed %d messages" % ( i )