I think this will add support for decryption of incoming packets, but I might be...
[goodfet] / client / goodfet.maxusbmass
1 #!/usr/bin/env python
2
3 #USB Mass Storage Emulator
4 #by Travis Goodspeed
5 #with thanks to Brandon Wilson and his Linky project.
6
7 import sys;
8 import binascii;
9 import array;
10 import time;
11
12 from GoodFETMAXUSB import *;
13
14 class GoodFETMAXUSBMass(GoodFETMAXUSBDevice):
15     """This emulates a USB Mass Storage device."""
16     
17     #Too much data to watch everything.
18     usbverbose=False;
19
20     def getSectorData(self,lba):
21         """Overload this to return data from a given 512-byte sector."""
22         print "You forgot to overload getSectorData().  Returning something neighborly.";
23         sector=[
24             0xE9, 0x86, 0x00, 0x0A, 0x47, 0x6F, 0x6F, 0x64, 0x44, 0x69, 0x73, 0x6B, 0x20, 0x30, 0x2E, 0x30,
25             0x31, 0x0A, 0x0D, 0x62, 0x79, 0x20, 0x54, 0x72, 0x61, 0x76, 0x69, 0x73, 0x20, 0x47, 0x6F, 0x6F,
26             0x64, 0x73, 0x70, 0x65, 0x65, 0x64, 0x0A, 0x0A, 0x0D, 0x00, 0x59, 0x6F, 0x75, 0x20, 0x68, 0x61,
27             0x76, 0x65, 0x20, 0x62, 0x65, 0x65, 0x6E, 0x20, 0x65, 0x61, 0x74, 0x65, 0x6E, 0x20, 0x62, 0x79,
28             0x20, 0x61, 0x20, 0x67, 0x72, 0x75, 0x65, 0x2E, 0x20, 0x20, 0x53, 0x6F, 0x72, 0x72, 0x79, 0x2E,
29             0x0A, 0x0D, 0x00, 0x31, 0x29, 0x20, 0x52, 0x65, 0x61, 0x64, 0x69, 0x6E, 0x67, 0x20, 0x6B, 0x65,
30             0x72, 0x6E, 0x65, 0x6C, 0x20, 0x66, 0x72, 0x6F, 0x6D, 0x20, 0x64, 0x69, 0x73, 0x6B, 0x2E, 0x0A,
31             0x0D, 0x00, 0x32, 0x29, 0x20, 0x45, 0x78, 0x65, 0x63, 0x75, 0x74, 0x69, 0x6E, 0x67, 0x20, 0x6B,
32             0x65, 0x72, 0x6E, 0x65, 0x6C, 0x2E, 0x0A, 0x0D, 0x00, 0xBE, 0x03, 0x7C, 0xE8, 0x41, 0x00, 0xE8,
33             0x7B, 0x00, 0x31, 0xC0, 0x30, 0xD2, 0xCD, 0x13, 0x0F, 0x82, 0xE8, 0x00, 0xBE, 0x53, 0x7C, 0xE8,
34             0x2E, 0x00, 0xB8, 0xE0, 0x07, 0x8E, 0xC0, 0x31, 0xDB, 0xB8, 0x10, 0x02, 0xB5, 0x00, 0xB1, 0x02,
35             0xB6, 0x00, 0xB2, 0x00, 0xCD, 0x13, 0x0F, 0x82, 0xCA, 0x00, 0xB8, 0x00, 0x7E, 0x89, 0xC6, 0xE8,
36             0x7C, 0x00, 0xBE, 0x72, 0x7C, 0xE8, 0x08, 0x00, 0xEA, 0x00, 0x00, 0xE0, 0x07, 0xE8, 0xB4, 0x00,
37             0xAC, 0x3C, 0x00, 0x74, 0x06, 0xB4, 0x0E, 0xCD, 0x10, 0xEB, 0xF5, 0xC3, 0x30, 0x78, 0x00, 0x20,
38             0x62, 0x79, 0x74, 0x65, 0x73, 0x20, 0x6F, 0x66, 0x20, 0x6D, 0x65, 0x6D, 0x6F, 0x72, 0x79, 0x20,
39             0x64, 0x65, 0x74, 0x65, 0x63, 0x74, 0x65, 0x64, 0x2E, 0x0A, 0x0D, 0x00, 0x53, 0x65, 0x67, 0x6D,
40             0x65, 0x6E, 0x74, 0x73, 0x3A, 0x20, 0x00, 0x2C, 0x20, 0x00, 0x0A, 0x0D, 0x00, 0xBE, 0xDC, 0x7C,
41             0xE8, 0xBD, 0xFF, 0xE8, 0x63, 0x00, 0xE8, 0x07, 0x00, 0xBE, 0xDF, 0x7C, 0xE8, 0xB1, 0xFF, 0xC3,
42             0x89, 0xC3, 0xC1, 0xE8, 0x0C, 0xE8, 0x39, 0x00, 0x89, 0xD8, 0xC1, 0xE8, 0x08, 0xE8, 0x31, 0x00,
43             0x89, 0xD8, 0xC1, 0xE8, 0x04, 0xE8, 0x29, 0x00, 0x89, 0xD8, 0xE8, 0x24, 0x00, 0xC3, 0x31, 0xC9,
44             0xAD, 0xE8, 0xDC, 0xFF, 0xE8, 0x2C, 0x00, 0x83, 0xC1, 0x02, 0x81, 0xF9, 0x00, 0x02, 0x75, 0xF0,
45             0xC3, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45,
46             0x46, 0x50, 0x56, 0x83, 0xE0, 0x0F, 0x05, 0x51, 0x7D, 0x89, 0xC6, 0xAC, 0xB4, 0x0E, 0xCD, 0x10,
47             0x5E, 0x58, 0xC3, 0xB8, 0x20, 0x0E, 0xCD, 0x10, 0xC3, 0x31, 0xC0, 0xCD, 0x12, 0x72, 0x05, 0x85,
48             0xC0, 0x74, 0x01, 0xC3, 0xBE, 0x2A, 0x7C, 0xE8, 0x46, 0xFF, 0xEB, 0xFE, 0xEA, 0x00, 0x00, 0xFF,
49             0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
50             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
51             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
52             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
53             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
54             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
55             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xAA
56             ];
57         return sector;
58     def putSectorData(self,lba,block):
59         """Overload this to write data to a given 512-byte sector."""
60         print "You forgot to overload putSectorData().  Ignoring sector write.";
61         return;
62     
63     def getSectorCount(self):
64         """Returns the number of viable Logical Block Addresses."""
65         print "You forgot to overload getSectorCount().  Guessing 0x200.";
66         return 0x200;
67     
68     def massinit(self):
69         """Initialize a USB Mass Storage device."""
70         self.usb_disconnect();
71         time.sleep(1);
72         self.usb_connect();
73         self.massrun();
74         
75     def massrun(self):
76         """Main loop of the USB Mass Storage emulator."""
77         print "Starting a Mass Storage device.";
78         while 1:
79             sys.stdout.flush();
80             self.service_irqs();
81     def do_SETUP(self):
82         """Handle USB Enumeration"""
83         
84         #Grab the SETUP packet from the buffer.
85         SUD=self.readbytes(rSUDFIFO,8);
86         
87         #Parse the SETUP packet
88         print "Handling a setup packet of %s" % self.setup2str(SUD);
89         setuptype=(ord(SUD[bmRequestType])&0x60);
90         if setuptype==0x00:
91             self.std_request(SUD);
92         elif setuptype==0x20:
93             self.class_request(SUD);
94         elif setuptype==0x40:
95             self.vendor_request(SUD);
96         else:
97             print "Unknown bmRequestType=0x%02x." % ord(SUD[bmRequestType])
98             self.STALL_EP0(SUD);
99     def class_request(self,SUD):
100         """Handle a class request."""
101         requesttype=ord(SUD[bmRequestType]);
102         request=ord(SUD[bRequest]);
103         if requesttype==0xA1 and request==0xFE:
104             print "Reporting 0 as the maximum LUN.";
105             #This is a Get Max LUN request.
106             #Return 1-byte maximum Logical Unit Number
107             self.wreg(rEP0FIFO,0x00); # Just one LUN.
108             self.wregAS(rEP0BC,1); # ARM and fire!
109             return; #Don't stall.
110         if requesttype==0x21 and request==0xff:
111             print "Received BBB reset."
112             self.wregAS(rEP0BC,0); # ARM and fire!
113             return; #Don't stall.
114         print "Stalling an unknown class request: %s" % self.setup2str(SUD);
115         self.STALL_EP0(SUD);
116     def vendor_request(self,SUD):
117         """Handle a vendor request."""
118         request=ord(SUD[bRequest]);
119         print "Why the hell is there a vendor request?";
120         #self.wreg(rEP0FIFO,0);
121         self.wregAS(rEP0BC,0);
122     def std_request(self,SUD):
123         """Handles a standard setup request."""
124         setuptype=ord(SUD[bRequest]);
125         if setuptype==SR_GET_DESCRIPTOR: self.send_descriptor(SUD);
126         #elif setuptype==SR_SET_FEATURE: self.feature(1);
127         elif setuptype==SR_SET_CONFIGURATION: self.set_configuration(SUD);
128         elif setuptype==SR_GET_STATUS: self.get_status(SUD);
129         elif setuptype==SR_SET_ADDRESS: self.rregAS(rFNADDR);
130         elif setuptype==SR_GET_INTERFACE: self.get_interface(SUD);
131         else:
132             #print "Stalling Unknown standard setup request type %02x" % setuptype;
133             #self.STALL_EP0(SUD);
134             print "Accepting unknown standard setup request type %02x" % setuptype;
135             self.wregAS(rEP0BC,0);
136             
137     def get_interface(self,SUD):
138         """Handles a setup request for SR_GET_INTERFACE."""
139         if ord(SUD[wIndexL]==0):
140             self.wreg(rEP0FIFO,0);
141             self.wregAS(rEP0BC,1);
142         else:
143             self.STALL_EP0(SUD);
144     
145
146
147 #Device Descriptor
148     DD=[ 
149         
150     0x12, #length
151     0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x40,
152     0x81, 0x07, #Sandisk 
153     0x50, 0x51, #SDCZ2 Cruzer Mini Flash Drive (thin)
154     0x00, 0x03,
155     0x01, 0x02, 0x03, #Strings
156     0x01
157     
158     ];
159
160 #Configuration Descriptor
161     CD=[
162
163   0x09, #Length
164   0x02, #Type
165   0x20, #Total Length
166   0x00, 0x01, 0x01, 0x00, 0xE0, 0x00, 0x09, 0x04, 0x00, 0x00,
167   0x02, #Num Endpoints
168   0x08, #Mass Storage Bulk Only
169   0x06, #SCSI
170   0x50, 0x00,
171   
172   #OUT EP1
173   0x07, 0x05, 0x01, 0x02, 0x40, 0x00, 0x00,
174   #IN EP3
175   0x07, 0x05, 0x83, 0x02, 0x40, 0x00, 0x00,
176
177 ];
178     strDesc=[
179 # STRING descriptor 0--Language string
180 "\x04\x03\x09\x04",
181 # [
182 #         0x04,                 # bLength
183 #       0x03,                   # bDescriptorType = string
184 #       0x09,0x04               # wLANGID(L/H) = English-United Sates
185 # ],
186 # STRING descriptor 1--Manufacturer ID
187 "\x10\x03G\x00o\x00o\x00d\x00F\x00E\x00T\x00",
188 # STRING descriptor 2 - Product ID
189 "\x1C\x03M\x00A\x00S\x00S\x00 \x00E\x00m\x00u\x00l\x00a\x00t\x00o\x00r\x00",
190 # STRING descriptor 3 - Serial Number ID
191 "\x14\x03S\x00/\x00N\x00 \x003\x004\x002\x000\x00E\x00"
192 ];
193
194     def get_status(self,SUD):
195         """Get the USB Setup Status."""
196         testbyte=ord(SUD[bmRequestType])
197         
198         #Toward Device
199         if testbyte==0x80:
200             self.wreg(rEP0FIFO,0x03); #Enable RWU and self-powered
201             self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
202             self.wregAS(rEP0BC,2);    #Load byte count, arm transfer, and ack CTL.
203         #Toward Interface
204         elif testbyte==0x81:
205             self.wreg(rEP0FIFO,0x00);
206             self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
207             self.wregAS(rEP0BC,2);
208         #Toward Endpoint
209         elif testbyte==0x82:
210             if(ord(SUD[wIndexL])==0x83):
211                 print "This code almost certainly doesn't work.";
212                 self.wreg(rEP0FIFO,0x01); #Stall EP3
213                 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
214                 self.wregAS(rEP0BC,2);
215             else:
216                 print "Stalling unknown status.";
217                 self.STALL_EP0(SUD);
218         else:
219             print "Stalling unknown status.";
220             self.STALL_EP0(SUD);
221     
222     def do_IN3(self):
223         """Handle IN3 input event."""
224         # Do nothing here, as it'll be taken care of elsewhere.  The
225         # interrupt just means that the buffer is empty, not that we
226         # are expected to fill it.
227         
228     def do_OUT1(self):
229         """Handle an OUT1 output event."""
230         l=self.rreg(rEP1OUTBC);
231         frame=self.readbytes(rEP1OUTFIFO,l);
232         self.handleCBW(frame);
233         
234     lastCBW="";
235     def handleCBW(self,cbw):
236         """Handles an incoming Command Block Wrapper.  See USB Mass
237         Storage Class for details."""
238         
239         if len(cbw)!=31:
240             print "Invalid CBW length of %i bytes.  Aborting." % len(cbw);
241             return;
242         sig=cbw[0:4];
243         if sig!="USBC":
244             print "Invalid CBW signature: %s.  Should be USBC; aborting." % sig;
245             return;
246         self.lastCBW=cbw;
247         
248         dtlen=ord(cbw[8])+(ord(cbw[9])<<8)+(ord(cbw[10])<<16)+(ord(cbw[11])<<24);
249         flags=ord(cbw[12]);
250         dtdir=flags&0x80; # 0x80 for dev->host, 0x00 for host->dev
251         lun=ord(cbw[13])&0x0F; # Should be zero, as we only reported one LUN.
252         cblen=ord(cbw[14])&0x1F;
253         cb=cbw[15:31];
254         self.handleCB(cb,cblen,dtlen,dtdir);
255         
256     def handleCB(self,cb,cblen,dtlen,dtdir):
257         """Handles a command block, then replies with a CSW."""
258         if self.usbverbose:
259             print "Got command block, type 0x%02x requesting 0x%02x bytes" % (
260                 ord(cb[0]), dtlen);
261         verb=ord(cb[0]);
262         status=00; #good, set to 1 for bad.
263         if verb==0x00: # Test Unit Ready
264             # Send nothing, just the success code.
265             status=0;
266         elif verb==0x03: # Request Sense
267             print "Responding to Request Sense.  Needed for Macs.";
268             response=[0x70, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0A,
269                       0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00,
270                       0x00, 0x00,
271                       0,0,0,0,0];
272             #status=1;
273             self.writebytes(rEP3INFIFO,
274                             response);
275             self.wreg(rEP3INBC,len(response));
276         elif verb==0x12: #Inquiry
277             #print "Responding to CB inquiry.";
278             response=[
279                 0x00, # 00 for Direct, 1F for "no floppy"
280                 0x80, # make 0x80 for removable media
281                 0x00, # Version
282                 0x01, # Response Data Format
283                 0x1f, #Additional length.
284                 0x00, 0x00, 0x00,
285                 #Manufacturer
286                 ord('G'),ord('o'),ord('o'),ord('d'),ord('F'),ord('E'),ord('T'),0x20,
287                 #Device name
288                 ord('G'),ord('o'),ord('o'),ord('d'),ord('F'),ord('E'),ord('T'),0x20,
289                 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
290                 ord('0'),ord('.'),ord('0'),ord('1')]
291             #print "Sending %i byte reply to %i byte query." % (
292             #        len(response),dtlen);
293             #while not(self.rreg(rEPIRQ)&bmIN3BAVIRQ):
294             #    #Wait for the packet to complete before sending the next.
295             #    print "Waiting to complete inquiry."
296             #    pass;
297             self.writebytes(rEP3INFIFO,
298                             response);
299             self.wregAS(rEP3INBC,
300                         dtlen);
301                         #len(response));
302             #self.wreg(rEPIRQ,bmIN3BAVIRQ); #Clear the bit
303             #while not(self.rreg(rEPIRQ)&bmIN3BAVIRQ):
304             #    #Wait for the packet to complete before sending the next.
305             #    print "Waiting to complete inquiry."
306             #    pass;
307         elif verb==0x1e: #Prevent/Allow Removal
308             # Give a good status to pretend we understand.
309             status=0x00;
310         elif verb==0x1A: #Mode Sense (6)
311             # I should probably send six bytes here.
312             response=[0x12,0,0,0, 0,0,0,0x1C];
313             self.writebytes(rEP3INFIFO,
314                             response);
315             self.wregAS(rEP3INBC,
316                         len(response));
317         elif verb==0x23: #Read Format Capacity
318             response=[
319                 0x00, 0,0x00,0x08, #Capacity list length.
320                 0,0x00,0x10,0x00,   # Number of sectors, implying 10MB.
321                 0x01,0x00,            #reserved/desciptor code.
322                 0x02,0x00             # 512 bytes/sector.  Why is this twice?
323                 ];
324             self.writebytes(rEP3INFIFO,
325                             response);
326             self.wregAS(rEP3INBC,
327                         len(response));
328         elif verb==0x25: #Read Capacity
329             lastlba=self.getSectorCount();
330             response=[
331                 #0x00, 0, 0x0f, 0xFF, # Last LBA
332                 (lastlba>>24)&0xFF, (lastlba>>16)&0xFF, (lastlba>>8)&0xFF, lastlba&0xFF, # Last LBA
333                 0x00,0x00,0x02,0x00   # Block length of 512 bytes.
334                 ];
335             self.writebytes(rEP3INFIFO,
336                             response);
337             self.wregAS(rEP3INBC,
338                         len(response));
339         elif verb==0x28: #READ SECTOR
340             cbw=self.lastCBW;
341             baselba=(
342                 ord(cbw[20]) |
343                 (ord(cbw[19])<<8) |
344                 (ord(cbw[18])<<16) |
345                 (ord(cbw[17])<<24)
346                 );
347             count=dtlen/512;
348             print "Fetching %i blocks starting at  LBA %i." % (count,baselba);
349             if count>32:
350                 count=0;
351                 status=1; #Fail if we're asked to read more than 32 blocks.
352                 #Now we need to stall EP3.  It's not acceptable to just forget to transmit.
353                 self.wreg(rEPSTALLS,0x10);
354             for i in range(0,count):
355                 data=self.getSectorData(baselba+i);
356                 for j in range(0,8):
357                     #print "Sending block fragment %i,%i" % (i,j);
358                     #Transmit each 64-byte block fragment, then wait for next.
359                     while not(self.rreg(rEPIRQ)&bmIN3BAVIRQ): pass;
360                     response=data[j*64:j*64+64];
361                     self.writebytes(rEP3INFIFO,
362                                     response);
363                     self.wregAS(rEP3INBC,
364                                 64);
365             #sys.exit();
366         elif verb==0x2A: #WRITE SECTOR
367             print "Haven't implemented WRITE SECTOR.";
368             #sys.exit();
369         else:
370             print "ERROR: Unknown SCSI command block verb %02x." % verb;
371             status=1; #Command Failed
372             if dtlen>0:
373                 print "Perhaps I should send %i bytes of dummy data here." % dtlen;
374             sys.exit(1);
375         cbw=self.lastCBW;
376         
377         #Now we need to send the CSW.
378         csw=[
379             #Standard prefix.
380             ord('U'),ord('S'),ord('B'),ord('S'),
381             #CBW key; must be the same as the one we're replying to.
382             ord(cbw[4]),ord(cbw[5]),ord(cbw[6]),ord(cbw[7]),
383             #CSW Data Residue, probably oughtn't be zeroed.
384             0,0,0,0,
385             #Status byte: 00 for good, 01 for bad.
386             status];
387         self.writebytes(rEP3INFIFO,
388                         csw);
389         self.wregAS(rEP3INBC,len(csw));
390         
391         
392         return;
393
394 class GoodFETMAXUSBMassFile(GoodFETMAXUSBMass):
395     """This emulates a USB Mass Storage Device, providing a file as
396     its image.  Writes are not yet supported, and this is very slow.
397     Performance hacks will come after the code stabilizes."""
398     
399     datafile=None;
400     datafilelen=None;
401     def openImage(self,filename):
402         """Opens an image for use.  Call this *before* massinit()."""
403         self.datafile=open(filename,"rb");
404         print "Opened an image with %i blocks." % self.getSectorCount();
405     def putSectorData(self,lba,block):
406         """Writes a 512-byte sector to the lba address."""
407         print "Writes aren't yet supported.";
408         return;
409     
410     def getSectorData(self,lba):
411         """Returns data from a 512-byte sector."""
412         toret="";
413         
414         #Seek to the appropraite block.
415         #print "Seeking to position %i"% (lba*512)
416         self.datafile.seek(lba*512,0);
417         pos=self.datafile.tell();
418         if pos!=lba*512:
419             print "SEEK ERROR: Seeked to %i (lba=%i), but now I'm at %i (lba=%i)" % (
420                 lba*512,lba,
421                 pos,pos/512);
422             #sys.exit();
423         
424         #Dump the data out, assuming no blocking and filling with nonsense.
425         toret=self.datafile.read(512);
426         if len(toret)<512:
427             print "Holy hell, I only have %i bytes of 512." % len(toret);
428         
429         toretbytes=range(0,len(toret));
430         for b in range(0,len(toret)): toretbytes[b]=ord(toret[b]);
431         return toretbytes;
432         
433     def getSectorCount(self):
434         """Returns the number of viable Logical Block Addresses."""
435         
436         # Python must have a better way to read a file length, but for
437         # now we just read the whole damned thing and then throw it
438         # away.  With present performance, we can't read anything
439         # large enough for this to be a problem.
440         if self.datafilelen==None:
441             self.datafile.seek(0);
442             self.datafilelen=len(self.datafile.read());
443         if self.datafilelen%512!=0:
444             print "ERROR: Image does not have an integer number of blocks!"
445             print "%i \% 512 == %i" % (self.datafilelen,
446                                        self.datafilelen%512);
447             sys.exit();
448         return self.datafilelen/512-1;
449 if(len(sys.argv)==1):
450     print "Usage: %s disk.img\n" % sys.argv[0];
451     sys.exit();
452
453
454 #Initialize FET and set baud rate
455 client=GoodFETMAXUSBMassFile();
456 client.serInit()
457
458 client.openImage(sys.argv[1]);
459
460 client.MAXUSBsetup();
461 client.massinit();
462