7 #include "include/hidusage.h"
8 #include "include/hidpi.h"
9 #include "include/hidsdi.h"
14 #define OUR_VID 0x9ac4
15 #define OUR_PID 0x4b8f
16 #define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
20 extern unsigned int current_command
;
22 static void ShowError(void)
25 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, GetLastError(), 0,
26 buf
, sizeof(buf
), NULL
);
27 printf("ERROR: %s", buf
);
30 static BOOL
UsbConnect(void)
32 typedef void (__stdcall
*GetGuidProc
)(GUID
*);
33 typedef BOOLEAN (__stdcall
*GetAttrProc
)(HANDLE
, HIDD_ATTRIBUTES
*);
34 typedef BOOLEAN (__stdcall
*GetPreparsedProc
)(HANDLE
,
35 PHIDP_PREPARSED_DATA
*);
36 typedef NTSTATUS (__stdcall
*GetCapsProc
)(PHIDP_PREPARSED_DATA
, PHIDP_CAPS
);
39 GetPreparsedProc getPreparsed
;
42 HMODULE h
= LoadLibrary("hid.dll");
43 getGuid
= (GetGuidProc
)GetProcAddress(h
, "HidD_GetHidGuid");
44 getAttr
= (GetAttrProc
)GetProcAddress(h
, "HidD_GetAttributes");
45 getPreparsed
= (GetPreparsedProc
)GetProcAddress(h
, "HidD_GetPreparsedData");
46 getCaps
= (GetCapsProc
)GetProcAddress(h
, "HidP_GetCaps");
52 devInfo
= SetupDiGetClassDevs(&hidGuid
, NULL
, NULL
,
53 DIGCF_PRESENT
| DIGCF_INTERFACEDEVICE
);
55 SP_DEVICE_INTERFACE_DATA devInfoData
;
56 devInfoData
.cbSize
= sizeof(devInfoData
);
60 if(!SetupDiEnumDeviceInterfaces(devInfo
, 0, &hidGuid
, i
, &devInfoData
))
62 if(GetLastError() != ERROR_NO_MORE_ITEMS
) {
63 // printf("SetupDiEnumDeviceInterfaces failed\n");
65 // printf("done list\n");
66 SetupDiDestroyDeviceInfoList(devInfo
);
70 // printf("item %d:\n", i);
73 if(!SetupDiGetDeviceInterfaceDetail(devInfo
, &devInfoData
,
74 NULL
, 0, &sizeReqd
, NULL
))
76 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER
) {
77 // printf("SetupDiGetDeviceInterfaceDetail (0) failed\n");
82 SP_DEVICE_INTERFACE_DETAIL_DATA
*devInfoDetailData
=
83 (SP_DEVICE_INTERFACE_DETAIL_DATA
*)malloc(sizeReqd
);
84 devInfoDetailData
->cbSize
= sizeof(*devInfoDetailData
);
86 if(!SetupDiGetDeviceInterfaceDetail(devInfo
, &devInfoData
,
87 devInfoDetailData
, 87, NULL
, NULL
))
89 // printf("SetupDiGetDeviceInterfaceDetail (1) failed\n");
93 char *path
= devInfoDetailData
->DevicePath
;
95 UsbHandle
= CreateFile(path
, /*GENERIC_READ |*/ GENERIC_WRITE
,
96 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
97 FILE_FLAG_OVERLAPPED
, NULL
);
99 if(UsbHandle
== INVALID_HANDLE_VALUE
) {
101 // printf("CreateFile failed: for '%s'\n", path);
105 HIDD_ATTRIBUTES attr
;
106 attr
.Size
= sizeof(attr
);
107 if(!getAttr(UsbHandle
, &attr
)) {
109 // printf("HidD_GetAttributes failed\n");
113 // printf("VID: %04x PID %04x\n", attr.VendorID, attr.ProductID);
115 if(attr
.VendorID
!= OUR_VID
|| attr
.ProductID
!= OUR_PID
) {
116 CloseHandle(UsbHandle
);
117 // printf(" nope, not us\n");
121 // printf ("got it!\n");
122 CloseHandle(UsbHandle
);
124 UsbHandle
= CreateFile(path
, GENERIC_READ
| GENERIC_WRITE
,
125 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
126 FILE_FLAG_OVERLAPPED
, NULL
);
128 if(UsbHandle
== INVALID_HANDLE_VALUE
) {
130 // printf("Error, couldn't open our own handle as desired.\n");
134 PHIDP_PREPARSED_DATA pp
;
135 getPreparsed(UsbHandle
, &pp
);
138 if(getCaps(pp
, &caps
) != HIDP_STATUS_SUCCESS
) {
139 // printf("getcaps failed\n");
143 // printf("input/out report %d/%d\n", caps.InputReportByteLength,
144 // caps.OutputReportByteLength);
152 bool ReceiveCommandPoll(UsbCommand
*c
)
154 static BOOL ReadInProgress
= FALSE
;
155 static OVERLAPPED Ov
;
157 static DWORD HaveRead
;
159 if(!ReadInProgress
) {
160 memset(&Ov
, 0, sizeof(Ov
));
161 ReadFile(UsbHandle
, Buf
, 65, &HaveRead
, &Ov
);
162 if(GetLastError() != ERROR_IO_PENDING
) {
166 ReadInProgress
= TRUE
;
169 if(HasOverlappedIoCompleted(&Ov
)) {
170 ReadInProgress
= FALSE
;
172 if(!GetOverlappedResult(UsbHandle
, &Ov
, &HaveRead
, FALSE
)) {
177 memcpy(c
, Buf
+1, 64);
185 void ReceiveCommand(UsbCommand
*c
)
187 while(!ReceiveCommandPoll(c
)) {
192 void SendCommand(UsbCommand
*c
)
196 memcpy(buf
+1, c
, 64);
201 memset(&ov
, 0, sizeof(ov
));
202 WriteFile(UsbHandle
, buf
, 65, &written
, &ov
);
203 if(GetLastError() != ERROR_IO_PENDING
) {
208 while(!HasOverlappedIoCompleted(&ov
)) {
212 if(!GetOverlappedResult(UsbHandle
, &ov
, &written
, FALSE
)) {
216 current_command
= c
->cmd
;
219 void WaitForAck(void) {
221 ReceiveCommand(&ack
);
222 if(ack
.cmd
!= CMD_ACK
) {
228 static DWORD ExpectedAddr
;
229 static BYTE QueuedToSend
[256];
230 static BOOL AllWritten
;
231 #define PHYSICAL_FLASH_START 0x100000
239 struct partition partitions
[] = {
240 {0x100000, 0x102000, 1, "bootrom"},
241 {0x102000, 0x110000, 0, "fpga"},
242 {0x110000, 0x140000, 0, "os"},
245 /* If translate is set, subtract PHYSICAL_FLASH_START to translate for old
248 static void FlushPrevious(int translate
)
251 memset(&c
, 0, sizeof(c
));
253 // printf("expected = %08x flush, ", ExpectedAddr);
256 for(i
= 0; i
< 240; i
+= 48) {
257 c
.cmd
= CMD_SETUP_WRITE
;
258 memcpy(c
.d
.asBytes
, QueuedToSend
+i
, 48);
264 c
.cmd
= CMD_FINISH_WRITE
;
265 c
.arg
[0] = (ExpectedAddr
-1) & (~255);
267 c
.arg
[0] -= PHYSICAL_FLASH_START
;
269 printf("Flashing address: %08x\r", c
.arg
[0]);
270 memcpy(c
.d
.asBytes
, QueuedToSend
+240, 16);
277 /* Where must be between start_addr (inclusive) and end_addr (exclusive).
279 static void GotByte(int where
, BYTE which
, int start_addr
, int end_addr
, int translate
)
283 if(where
< start_addr
|| where
>= end_addr
) {
284 printf("bad: got byte at %08x, outside of range %08x-%08x\n", where
, start_addr
, end_addr
);
288 if(where
!= ExpectedAddr
) {
289 printf("bad: got at %08x, expected at %08x\n", where
, ExpectedAddr
);
292 QueuedToSend
[where
& 255] = which
;
295 if((where
& 255) == 255) {
296 // we have completed a full page
297 FlushPrevious(translate
);
301 static int HexVal(int c
)
304 if(c
>= '0' && c
<= '9') {
306 } else if(c
>= 'a' && c
<= 'f') {
307 return (c
- 'a') + 10;
309 printf("bad hex digit '%c'\n", c
);
314 static BYTE
HexByte(char *s
)
316 return (HexVal(s
[0]) << 4) | HexVal(s
[1]);
319 static void LoadFlashFromSRecords(const char *file
, int start_addr
, int end_addr
, int translate
)
321 ExpectedAddr
= start_addr
;
323 FILE *f
= fopen(file
, "r");
325 printf("couldn't open file\n");
330 while(fgets(line
, sizeof(line
), f
)) {
331 if(memcmp(line
, "S3", 2)==0) {
333 int len
= HexByte(s
) - 5;
337 memcpy(addrStr
, s
, 8);
340 sscanf(addrStr
, "%x", &addr
);
343 /* Accept files that are located at PHYSICAL_FLASH_START, and files that are located at 0 */
344 if(addr
< PHYSICAL_FLASH_START
)
345 addr
+= PHYSICAL_FLASH_START
;
348 for(i
= 0; i
< len
; i
++) {
349 while((addr
+i
) > ExpectedAddr
) {
350 GotByte(ExpectedAddr
, 0xff, start_addr
, end_addr
, translate
);
352 GotByte(addr
+i
, HexByte(s
), start_addr
, end_addr
, translate
);
358 if(!AllWritten
) FlushPrevious(translate
);
364 static int PrepareFlash(struct partition
*p
, const char *filename
, unsigned int state
)
367 if(state
& DEVICE_INFO_FLAG_UNDERSTANDS_START_FLASH
) {
369 c
.cmd
= CMD_START_FLASH
;
373 /* Only send magic when flashing bootrom */
375 c
.arg
[2] = START_FLASH_MAGIC
;
383 fprintf(stderr
, "Warning: Your bootloader does not understand the new START_FLASH command\n");
384 fprintf(stderr
, " It is recommended that you update your bootloader\n\n");
388 LoadFlashFromSRecords(filename
, p
->start
, p
->end
, translate
);
392 static unsigned int GetProxmarkState(void)
394 unsigned int state
= 0;
397 c
.cmd
= CMD_DEVICE_INFO
;
401 ReceiveCommand(&resp
);
403 * 1. The old bootrom code will ignore CMD_DEVICE_INFO, but respond with an ACK
404 * 2. The old os code will respond with CMD_DEBUG_PRINT_STRING and "unknown command"
405 * 3. The new bootrom and os codes will respond with CMD_DEVICE_INFO and flags
410 state
= DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
;
412 case CMD_DEBUG_PRINT_STRING
:
413 state
= DEVICE_INFO_FLAG_CURRENT_MODE_OS
;
415 case CMD_DEVICE_INFO
:
419 fprintf(stderr
, "Couldn't get proxmark state, bad response type: 0x%04X\n", resp
.cmd
);
425 if(state
& DEVICE_INFO_FLAG_BOOTROM_PRESENT
) printf("New bootrom present\n");
426 if(state
& DEVICE_INFO_FLAG_OSIMAGE_PRESENT
) printf("New osimage present\n");
427 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
) printf("Currently in bootrom\n");
428 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_OS
) printf("Currently in OS\n");
434 static unsigned int EnterFlashState(void)
436 unsigned int state
= GetProxmarkState();
438 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
) {
439 /* Already in flash state, we're done. */
443 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_OS
) {
444 fprintf(stderr
,"Entering flash-mode...\n");
446 bzero(&c
, sizeof(c
));
448 if( (state
& DEVICE_INFO_FLAG_BOOTROM_PRESENT
) && (state
& DEVICE_INFO_FLAG_OSIMAGE_PRESENT
) ) {
449 /* New style handover: Send CMD_START_FLASH, which will reset the board and
450 * enter the bootrom on the next boot.
452 c
.cmd
= CMD_START_FLASH
;
454 fprintf(stderr
,"(You don't have to do anything. Press and release the button only if you want to abort)\n");
455 fprintf(stderr
,"Waiting for Proxmark to reappear on USB... ");
457 /* Old style handover: Ask the user to press the button, then reset the board */
458 c
.cmd
= CMD_HARDWARE_RESET
;
460 fprintf(stderr
,"(Press and hold down button NOW if your bootloader requires it)\n");
461 fprintf(stderr
,"Waiting for Proxmark to reappear on USB... ");
467 while(!UsbConnect()) { Sleep(1000); }
468 fprintf(stderr
,"Found.\n");
470 return GetProxmarkState();
476 static void usage(char **argv
)
479 printf("Usage: %s gui\n", argv
[0]);
480 printf(" %s offline\n", argv
[0]);
481 printf(" %s areas file.s19\n", argv
[0]);
482 printf(" Known areas are:");
483 for(i
=0; i
<(sizeof(partitions
)/sizeof(partitions
[0])); i
++) {
484 fprintf(stderr
, " %s", partitions
[i
].name
);
490 /* On first call, have *offset = -1, *length = 0; */
491 static int find_next_area(char *str
, int *offset
, int *length
)
493 if(*str
== '\0') return 0;
494 if((*offset
>= 0) && str
[*offset
+ *length
] == '\0') return 0;
495 *offset
+= 1 + *length
;
497 char *next_comma
= strchr(str
+ *offset
, ',');
498 if(next_comma
== NULL
) {
499 *length
= strlen(str
) - *offset
;
501 *length
= next_comma
-(str
+*offset
);
506 int main(int argc
, char **argv
)
515 // Only do this if NOT in offline mode
516 if (strcmp(argv
[1], "offline"))
523 printf("...no device connected, polling for it now\n");
526 printf("Could not connect to USB device; exiting.\n");
534 if(strcmp(argv
[1], "gui")==0) {
536 } else if(strcmp(argv
[1], "offline")==0) {
541 /* Count area arguments */
542 int areas
= 0, offset
=-1, length
=0;
543 while(find_next_area(argv
[1], &offset
, &length
)) areas
++;
545 if(areas
!= argc
- 2) {
550 unsigned int state
= EnterFlashState();
552 if( !(state
& DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
) ) {
553 fprintf(stderr
, "Proxmark would not enter flash state, abort\n");
558 int current_area
= 0;
559 while(find_next_area(argv
[1], &offset
, &length
)) {
561 struct partition
*p
= NULL
;
562 for(i
=0; i
<sizeof(partitions
)/sizeof(partitions
[0]); i
++) {
563 if(strncmp(partitions
[i
].name
, argv
[1] + offset
, length
) == 0) {
564 /* Check if the name matches the bootrom partition, and if so, require "bootrom" to
565 * be written in full. The other names may be abbreviated.
567 if(!partitions
[i
].precious
|| (strlen(partitions
[i
].name
) == length
)) {
575 fprintf(stderr
, "Warning: area name '");
576 fwrite(argv
[1]+offset
, length
, 1, stderr
);
577 fprintf(stderr
, "' unknown, ignored\n");
579 fprintf(stderr
, "Flashing %s from %s\n", p
->name
, argv
[2+current_area
]);
580 PrepareFlash(p
, argv
[2+current_area
], state
);