7 #include "include/hidsdi.h"
8 #include "include/hidpi.h"
13 #define OUR_VID 0x9ac4
14 #define OUR_PID 0x4b8f
15 #define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
20 static void ShowError(void)
23 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, GetLastError(), 0,
24 buf
, sizeof(buf
), NULL
);
25 printf("ERROR: %s", buf
);
28 static BOOL
UsbConnect(void)
30 typedef void (__stdcall
*GetGuidProc
)(GUID
*);
31 typedef BOOLEAN (__stdcall
*GetAttrProc
)(HANDLE
, HIDD_ATTRIBUTES
*);
32 typedef BOOLEAN (__stdcall
*GetPreparsedProc
)(HANDLE
,
33 PHIDP_PREPARSED_DATA
*);
34 typedef NTSTATUS (__stdcall
*GetCapsProc
)(PHIDP_PREPARSED_DATA
, PHIDP_CAPS
);
37 GetPreparsedProc getPreparsed
;
40 HMODULE h
= LoadLibrary("hid.dll");
41 getGuid
= (GetGuidProc
)GetProcAddress(h
, "HidD_GetHidGuid");
42 getAttr
= (GetAttrProc
)GetProcAddress(h
, "HidD_GetAttributes");
43 getPreparsed
= (GetPreparsedProc
)GetProcAddress(h
, "HidD_GetPreparsedData");
44 getCaps
= (GetCapsProc
)GetProcAddress(h
, "HidP_GetCaps");
50 devInfo
= SetupDiGetClassDevs(&hidGuid
, NULL
, NULL
,
51 DIGCF_PRESENT
| DIGCF_INTERFACEDEVICE
);
53 SP_DEVICE_INTERFACE_DATA devInfoData
;
54 devInfoData
.cbSize
= sizeof(devInfoData
);
58 if(!SetupDiEnumDeviceInterfaces(devInfo
, 0, &hidGuid
, i
, &devInfoData
))
60 if(GetLastError() != ERROR_NO_MORE_ITEMS
) {
61 // printf("SetupDiEnumDeviceInterfaces failed\n");
63 // printf("done list\n");
64 SetupDiDestroyDeviceInfoList(devInfo
);
68 // printf("item %d:\n", i);
71 if(!SetupDiGetDeviceInterfaceDetail(devInfo
, &devInfoData
,
72 NULL
, 0, &sizeReqd
, NULL
))
74 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER
) {
75 // printf("SetupDiGetDeviceInterfaceDetail (0) failed\n");
80 SP_DEVICE_INTERFACE_DETAIL_DATA
*devInfoDetailData
=
81 (SP_DEVICE_INTERFACE_DETAIL_DATA
*)malloc(sizeReqd
);
82 devInfoDetailData
->cbSize
= sizeof(*devInfoDetailData
);
84 if(!SetupDiGetDeviceInterfaceDetail(devInfo
, &devInfoData
,
85 devInfoDetailData
, 87, NULL
, NULL
))
87 // printf("SetupDiGetDeviceInterfaceDetail (1) failed\n");
91 char *path
= devInfoDetailData
->DevicePath
;
93 UsbHandle
= CreateFile(path
, /*GENERIC_READ |*/ GENERIC_WRITE
,
94 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
95 FILE_FLAG_OVERLAPPED
, NULL
);
97 if(UsbHandle
== INVALID_HANDLE_VALUE
) {
99 // printf("CreateFile failed: for '%s'\n", path);
103 HIDD_ATTRIBUTES attr
;
104 attr
.Size
= sizeof(attr
);
105 if(!getAttr(UsbHandle
, &attr
)) {
107 // printf("HidD_GetAttributes failed\n");
111 // printf("VID: %04x PID %04x\n", attr.VendorID, attr.ProductID);
113 if(attr
.VendorID
!= OUR_VID
|| attr
.ProductID
!= OUR_PID
) {
114 CloseHandle(UsbHandle
);
115 // printf(" nope, not us\n");
119 // printf ("got it!\n");
120 CloseHandle(UsbHandle
);
122 UsbHandle
= CreateFile(path
, GENERIC_READ
| GENERIC_WRITE
,
123 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
124 FILE_FLAG_OVERLAPPED
, NULL
);
126 if(UsbHandle
== INVALID_HANDLE_VALUE
) {
128 // printf("Error, couldn't open our own handle as desired.\n");
132 PHIDP_PREPARSED_DATA pp
;
133 getPreparsed(UsbHandle
, &pp
);
136 if(getCaps(pp
, &caps
) != HIDP_STATUS_SUCCESS
) {
137 // printf("getcaps failed\n");
141 // printf("input/out report %d/%d\n", caps.InputReportByteLength,
142 // caps.OutputReportByteLength);
150 BOOL
ReceiveCommandPoll(UsbCommand
*c
)
152 static BOOL ReadInProgress
= FALSE
;
153 static OVERLAPPED Ov
;
155 static DWORD HaveRead
;
157 if(!ReadInProgress
) {
158 memset(&Ov
, 0, sizeof(Ov
));
159 ReadFile(UsbHandle
, Buf
, 65, &HaveRead
, &Ov
);
160 if(GetLastError() != ERROR_IO_PENDING
) {
164 ReadInProgress
= TRUE
;
167 if(HasOverlappedIoCompleted(&Ov
)) {
168 ReadInProgress
= FALSE
;
170 if(!GetOverlappedResult(UsbHandle
, &Ov
, &HaveRead
, FALSE
)) {
175 memcpy(c
, Buf
+1, 64);
183 void ReceiveCommand(UsbCommand
*c
)
185 while(!ReceiveCommandPoll(c
)) {
190 void SendCommand(UsbCommand
*c
, BOOL wantAck
)
194 memcpy(buf
+1, c
, 64);
199 memset(&ov
, 0, sizeof(ov
));
200 WriteFile(UsbHandle
, buf
, 65, &written
, &ov
);
201 if(GetLastError() != ERROR_IO_PENDING
) {
206 while(!HasOverlappedIoCompleted(&ov
)) {
210 if(!GetOverlappedResult(UsbHandle
, &ov
, &written
, FALSE
)) {
217 ReceiveCommand(&ack
);
218 if(ack
.cmd
!= CMD_ACK
) {
225 static DWORD ExpectedAddr
;
226 static BYTE QueuedToSend
[256];
227 static BOOL AllWritten
;
228 #define PHYSICAL_FLASH_START 0x100000
236 struct partition partitions
[] = {
237 {0x100000, 0x102000, 1, "bootrom"},
238 {0x102000, 0x110000, 0, "fpga"},
239 {0x110000, 0x140000, 0, "os"},
242 /* If translate is set, subtract PHYSICAL_FLASH_START to translate for old
245 static void FlushPrevious(int translate
)
248 memset(&c
, 0, sizeof(c
));
250 // printf("expected = %08x flush, ", ExpectedAddr);
253 for(i
= 0; i
< 240; i
+= 48) {
254 c
.cmd
= CMD_SETUP_WRITE
;
255 memcpy(c
.d
.asBytes
, QueuedToSend
+i
, 48);
257 SendCommand(&c
, TRUE
);
260 c
.cmd
= CMD_FINISH_WRITE
;
261 c
.ext1
= (ExpectedAddr
-1) & (~255);
263 c
.ext1
-= PHYSICAL_FLASH_START
;
265 printf("Flashing address: %08x\r", c
.ext1
);
266 memcpy(c
.d
.asBytes
, QueuedToSend
+240, 16);
267 SendCommand(&c
, TRUE
);
272 /* Where must be between start_addr (inclusive) and end_addr (exclusive).
274 static void GotByte(int where
, BYTE which
, int start_addr
, int end_addr
, int translate
)
278 if(where
< start_addr
|| where
>= end_addr
) {
279 printf("bad: got byte at %08x, outside of range %08x-%08x\n", where
, start_addr
, end_addr
);
283 if(where
!= ExpectedAddr
) {
284 printf("bad: got at %08x, expected at %08x\n", where
, ExpectedAddr
);
287 QueuedToSend
[where
& 255] = which
;
290 if((where
& 255) == 255) {
291 // we have completed a full page
292 FlushPrevious(translate
);
296 static int HexVal(int c
)
299 if(c
>= '0' && c
<= '9') {
301 } else if(c
>= 'a' && c
<= 'f') {
302 return (c
- 'a') + 10;
304 printf("bad hex digit '%c'\n", c
);
309 static BYTE
HexByte(char *s
)
311 return (HexVal(s
[0]) << 4) | HexVal(s
[1]);
314 static void LoadFlashFromSRecords(const char *file
, int start_addr
, int end_addr
, int translate
)
316 ExpectedAddr
= start_addr
;
318 FILE *f
= fopen(file
, "r");
320 printf("couldn't open file\n");
325 while(fgets(line
, sizeof(line
), f
)) {
326 if(memcmp(line
, "S3", 2)==0) {
328 int len
= HexByte(s
) - 5;
332 memcpy(addrStr
, s
, 8);
335 sscanf(addrStr
, "%x", &addr
);
338 /* Accept files that are located at PHYSICAL_FLASH_START, and files that are located at 0 */
339 if(addr
< PHYSICAL_FLASH_START
)
340 addr
+= PHYSICAL_FLASH_START
;
343 for(i
= 0; i
< len
; i
++) {
344 while((addr
+i
) > ExpectedAddr
) {
345 GotByte(ExpectedAddr
, 0xff, start_addr
, end_addr
, translate
);
347 GotByte(addr
+i
, HexByte(s
), start_addr
, end_addr
, translate
);
353 if(!AllWritten
) FlushPrevious(translate
);
359 static int PrepareFlash(struct partition
*p
, const char *filename
, unsigned int state
)
362 if(state
& DEVICE_INFO_FLAG_UNDERSTANDS_START_FLASH
) {
364 c
.cmd
= CMD_START_FLASH
;
368 /* Only send magic when flashing bootrom */
370 c
.ext3
= START_FLASH_MAGIC
;
374 SendCommand(&c
, TRUE
);
377 fprintf(stderr
, "Warning: Your bootloader does not understand the new START_FLASH command\n");
378 fprintf(stderr
, " It is recommended that you update your bootloader\n\n");
382 LoadFlashFromSRecords(filename
, p
->start
, p
->end
, translate
);
386 static unsigned int GetProxmarkState(void)
388 unsigned int state
= 0;
391 c
.cmd
= CMD_DEVICE_INFO
;
392 SendCommand(&c
, FALSE
);
395 ReceiveCommand(&resp
);
397 * 1. The old bootrom code will ignore CMD_DEVICE_INFO, but respond with an ACK
398 * 2. The old os code will respond with CMD_DEBUG_PRINT_STRING and "unknown command"
399 * 3. The new bootrom and os codes will respond with CMD_DEVICE_INFO and flags
404 state
= DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
;
406 case CMD_DEBUG_PRINT_STRING
:
407 state
= DEVICE_INFO_FLAG_CURRENT_MODE_OS
;
409 case CMD_DEVICE_INFO
:
413 fprintf(stderr
, "Couldn't get proxmark state, bad response type: 0x%04X\n", resp
.cmd
);
419 if(state
& DEVICE_INFO_FLAG_BOOTROM_PRESENT
) printf("New bootrom present\n");
420 if(state
& DEVICE_INFO_FLAG_OSIMAGE_PRESENT
) printf("New osimage present\n");
421 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
) printf("Currently in bootrom\n");
422 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_OS
) printf("Currently in OS\n");
428 static unsigned int EnterFlashState(void)
430 unsigned int state
= GetProxmarkState();
432 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
) {
433 /* Already in flash state, we're done. */
437 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_OS
) {
438 fprintf(stderr
,"Entering flash-mode...\n");
440 bzero(&c
, sizeof(c
));
442 if( (state
& DEVICE_INFO_FLAG_BOOTROM_PRESENT
) && (state
& DEVICE_INFO_FLAG_OSIMAGE_PRESENT
) ) {
443 /* New style handover: Send CMD_START_FLASH, which will reset the board and
444 * enter the bootrom on the next boot.
446 c
.cmd
= CMD_START_FLASH
;
447 SendCommand(&c
, FALSE
);
448 fprintf(stderr
,"(You don't have to do anything. Press and release the button only if you want to abort)\n");
449 fprintf(stderr
,"Waiting for Proxmark to reappear on USB... ");
451 /* Old style handover: Ask the user to press the button, then reset the board */
452 c
.cmd
= CMD_HARDWARE_RESET
;
453 SendCommand(&c
, FALSE
);
454 fprintf(stderr
,"(Press and hold down button NOW if your bootloader requires it)\n");
455 fprintf(stderr
,"Waiting for Proxmark to reappear on USB... ");
461 while(!UsbConnect()) { Sleep(1000); }
462 fprintf(stderr
,"Found.\n");
464 return GetProxmarkState();
470 static void usage(char **argv
)
473 printf("Usage: %s gui\n", argv
[0]);
474 printf(" %s offline\n", argv
[0]);
475 printf(" %s areas file.s19\n", argv
[0]);
476 printf(" Known areas are:");
477 for(i
=0; i
<(sizeof(partitions
)/sizeof(partitions
[0])); i
++) {
478 fprintf(stderr
, " %s", partitions
[i
].name
);
484 /* On first call, have *offset = -1, *length = 0; */
485 static int find_next_area(char *str
, int *offset
, int *length
)
487 if(*str
== '\0') return 0;
488 if((*offset
>= 0) && str
[*offset
+ *length
] == '\0') return 0;
489 *offset
+= 1 + *length
;
491 char *next_comma
= strchr(str
+ *offset
, ',');
492 if(next_comma
== NULL
) {
493 *length
= strlen(str
) - *offset
;
495 *length
= next_comma
-(str
+*offset
);
500 int main(int argc
, char **argv
)
509 // Only do this if NOT in offline mode
510 if (strcmp(argv
[1], "offline"))
517 printf("...no device connected, polling for it now\n");
520 printf("Could not connect to USB device; exiting.\n");
528 if(strcmp(argv
[1], "gui")==0) {
530 } else if(strcmp(argv
[1], "offline")==0) {
535 /* Count area arguments */
536 int areas
= 0, offset
=-1, length
=0;
537 while(find_next_area(argv
[1], &offset
, &length
)) areas
++;
539 if(areas
!= argc
- 2) {
544 unsigned int state
= EnterFlashState();
546 if( !(state
& DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
) ) {
547 fprintf(stderr
, "Proxmark would not enter flash state, abort\n");
552 int current_area
= 0;
553 while(find_next_area(argv
[1], &offset
, &length
)) {
555 struct partition
*p
= NULL
;
556 for(i
=0; i
<sizeof(partitions
)/sizeof(partitions
[0]); i
++) {
557 if(strncmp(partitions
[i
].name
, argv
[1] + offset
, length
) == 0) {
558 /* Check if the name matches the bootrom partition, and if so, require "bootrom" to
559 * be written in full. The other names may be abbreviated.
561 if(!partitions
[i
].precious
|| (strlen(partitions
[i
].name
) == length
)) {
569 fprintf(stderr
, "Warning: area name '");
570 fwrite(argv
[1]+offset
, length
, 1, stderr
);
571 fprintf(stderr
, "' unknown, ignored\n");
573 fprintf(stderr
, "Flashing %s from %s\n", p
->name
, argv
[2+current_area
]);
574 PrepareFlash(p
, argv
[2+current_area
], state
);