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)
21 static void ShowError(void)
24 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, GetLastError(), 0,
25 buf
, sizeof(buf
), NULL
);
26 printf("ERROR: %s", buf
);
29 static BOOL
UsbConnect(void)
31 typedef void (__stdcall
*GetGuidProc
)(GUID
*);
32 typedef BOOLEAN (__stdcall
*GetAttrProc
)(HANDLE
, HIDD_ATTRIBUTES
*);
33 typedef BOOLEAN (__stdcall
*GetPreparsedProc
)(HANDLE
,
34 PHIDP_PREPARSED_DATA
*);
35 typedef NTSTATUS (__stdcall
*GetCapsProc
)(PHIDP_PREPARSED_DATA
, PHIDP_CAPS
);
38 GetPreparsedProc getPreparsed
;
41 HMODULE h
= LoadLibrary("hid.dll");
42 getGuid
= (GetGuidProc
)GetProcAddress(h
, "HidD_GetHidGuid");
43 getAttr
= (GetAttrProc
)GetProcAddress(h
, "HidD_GetAttributes");
44 getPreparsed
= (GetPreparsedProc
)GetProcAddress(h
, "HidD_GetPreparsedData");
45 getCaps
= (GetCapsProc
)GetProcAddress(h
, "HidP_GetCaps");
51 devInfo
= SetupDiGetClassDevs(&hidGuid
, NULL
, NULL
,
52 DIGCF_PRESENT
| DIGCF_INTERFACEDEVICE
);
54 SP_DEVICE_INTERFACE_DATA devInfoData
;
55 devInfoData
.cbSize
= sizeof(devInfoData
);
59 if(!SetupDiEnumDeviceInterfaces(devInfo
, 0, &hidGuid
, i
, &devInfoData
))
61 if(GetLastError() != ERROR_NO_MORE_ITEMS
) {
62 // printf("SetupDiEnumDeviceInterfaces failed\n");
64 // printf("done list\n");
65 SetupDiDestroyDeviceInfoList(devInfo
);
69 // printf("item %d:\n", i);
72 if(!SetupDiGetDeviceInterfaceDetail(devInfo
, &devInfoData
,
73 NULL
, 0, &sizeReqd
, NULL
))
75 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER
) {
76 // printf("SetupDiGetDeviceInterfaceDetail (0) failed\n");
81 SP_DEVICE_INTERFACE_DETAIL_DATA
*devInfoDetailData
=
82 (SP_DEVICE_INTERFACE_DETAIL_DATA
*)malloc(sizeReqd
);
83 devInfoDetailData
->cbSize
= sizeof(*devInfoDetailData
);
85 if(!SetupDiGetDeviceInterfaceDetail(devInfo
, &devInfoData
,
86 devInfoDetailData
, 87, NULL
, NULL
))
88 // printf("SetupDiGetDeviceInterfaceDetail (1) failed\n");
92 char *path
= devInfoDetailData
->DevicePath
;
94 UsbHandle
= CreateFile(path
, /*GENERIC_READ |*/ GENERIC_WRITE
,
95 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
96 FILE_FLAG_OVERLAPPED
, NULL
);
98 if(UsbHandle
== INVALID_HANDLE_VALUE
) {
100 // printf("CreateFile failed: for '%s'\n", path);
104 HIDD_ATTRIBUTES attr
;
105 attr
.Size
= sizeof(attr
);
106 if(!getAttr(UsbHandle
, &attr
)) {
108 // printf("HidD_GetAttributes failed\n");
112 // printf("VID: %04x PID %04x\n", attr.VendorID, attr.ProductID);
114 if(attr
.VendorID
!= OUR_VID
|| attr
.ProductID
!= OUR_PID
) {
115 CloseHandle(UsbHandle
);
116 // printf(" nope, not us\n");
120 // printf ("got it!\n");
121 CloseHandle(UsbHandle
);
123 UsbHandle
= CreateFile(path
, GENERIC_READ
| GENERIC_WRITE
,
124 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
,
125 FILE_FLAG_OVERLAPPED
, NULL
);
127 if(UsbHandle
== INVALID_HANDLE_VALUE
) {
129 // printf("Error, couldn't open our own handle as desired.\n");
133 PHIDP_PREPARSED_DATA pp
;
134 getPreparsed(UsbHandle
, &pp
);
137 if(getCaps(pp
, &caps
) != HIDP_STATUS_SUCCESS
) {
138 // printf("getcaps failed\n");
142 // printf("input/out report %d/%d\n", caps.InputReportByteLength,
143 // caps.OutputReportByteLength);
151 bool ReceiveCommandPoll(UsbCommand
*c
)
153 static BOOL ReadInProgress
= FALSE
;
154 static OVERLAPPED Ov
;
156 static DWORD HaveRead
;
158 if(!ReadInProgress
) {
159 memset(&Ov
, 0, sizeof(Ov
));
160 ReadFile(UsbHandle
, Buf
, 65, &HaveRead
, &Ov
);
161 if(GetLastError() != ERROR_IO_PENDING
) {
165 ReadInProgress
= TRUE
;
168 if(HasOverlappedIoCompleted(&Ov
)) {
169 ReadInProgress
= FALSE
;
171 if(!GetOverlappedResult(UsbHandle
, &Ov
, &HaveRead
, FALSE
)) {
176 memcpy(c
, Buf
+1, 64);
184 void ReceiveCommand(UsbCommand
*c
)
186 while(!ReceiveCommandPoll(c
)) {
191 void SendCommand(UsbCommand
*c
, bool wantAck
)
195 memcpy(buf
+1, c
, 64);
200 memset(&ov
, 0, sizeof(ov
));
201 WriteFile(UsbHandle
, buf
, 65, &written
, &ov
);
202 if(GetLastError() != ERROR_IO_PENDING
) {
207 while(!HasOverlappedIoCompleted(&ov
)) {
211 if(!GetOverlappedResult(UsbHandle
, &ov
, &written
, FALSE
)) {
218 ReceiveCommand(&ack
);
219 if(ack
.cmd
!= CMD_ACK
) {
226 static DWORD ExpectedAddr
;
227 static BYTE QueuedToSend
[256];
228 static BOOL AllWritten
;
229 #define PHYSICAL_FLASH_START 0x100000
237 struct partition partitions
[] = {
238 {0x100000, 0x102000, 1, "bootrom"},
239 {0x102000, 0x110000, 0, "fpga"},
240 {0x110000, 0x140000, 0, "os"},
243 /* If translate is set, subtract PHYSICAL_FLASH_START to translate for old
246 static void FlushPrevious(int translate
)
249 memset(&c
, 0, sizeof(c
));
251 // printf("expected = %08x flush, ", ExpectedAddr);
254 for(i
= 0; i
< 240; i
+= 48) {
255 c
.cmd
= CMD_SETUP_WRITE
;
256 memcpy(c
.d
.asBytes
, QueuedToSend
+i
, 48);
258 SendCommand(&c
, TRUE
);
261 c
.cmd
= CMD_FINISH_WRITE
;
262 c
.arg
[0] = (ExpectedAddr
-1) & (~255);
264 c
.arg
[0] -= PHYSICAL_FLASH_START
;
266 printf("Flashing address: %08x\r", c
.arg
[0]);
267 memcpy(c
.d
.asBytes
, QueuedToSend
+240, 16);
268 SendCommand(&c
, TRUE
);
273 /* Where must be between start_addr (inclusive) and end_addr (exclusive).
275 static void GotByte(int where
, BYTE which
, int start_addr
, int end_addr
, int translate
)
279 if(where
< start_addr
|| where
>= end_addr
) {
280 printf("bad: got byte at %08x, outside of range %08x-%08x\n", where
, start_addr
, end_addr
);
284 if(where
!= ExpectedAddr
) {
285 printf("bad: got at %08x, expected at %08x\n", where
, ExpectedAddr
);
288 QueuedToSend
[where
& 255] = which
;
291 if((where
& 255) == 255) {
292 // we have completed a full page
293 FlushPrevious(translate
);
297 static int HexVal(int c
)
300 if(c
>= '0' && c
<= '9') {
302 } else if(c
>= 'a' && c
<= 'f') {
303 return (c
- 'a') + 10;
305 printf("bad hex digit '%c'\n", c
);
310 static BYTE
HexByte(char *s
)
312 return (HexVal(s
[0]) << 4) | HexVal(s
[1]);
315 static void LoadFlashFromSRecords(const char *file
, int start_addr
, int end_addr
, int translate
)
317 ExpectedAddr
= start_addr
;
319 FILE *f
= fopen(file
, "r");
321 printf("couldn't open file\n");
326 while(fgets(line
, sizeof(line
), f
)) {
327 if(memcmp(line
, "S3", 2)==0) {
329 int len
= HexByte(s
) - 5;
333 memcpy(addrStr
, s
, 8);
336 sscanf(addrStr
, "%x", &addr
);
339 /* Accept files that are located at PHYSICAL_FLASH_START, and files that are located at 0 */
340 if(addr
< PHYSICAL_FLASH_START
)
341 addr
+= PHYSICAL_FLASH_START
;
344 for(i
= 0; i
< len
; i
++) {
345 while((addr
+i
) > ExpectedAddr
) {
346 GotByte(ExpectedAddr
, 0xff, start_addr
, end_addr
, translate
);
348 GotByte(addr
+i
, HexByte(s
), start_addr
, end_addr
, translate
);
354 if(!AllWritten
) FlushPrevious(translate
);
360 static int PrepareFlash(struct partition
*p
, const char *filename
, unsigned int state
)
363 if(state
& DEVICE_INFO_FLAG_UNDERSTANDS_START_FLASH
) {
365 c
.cmd
= CMD_START_FLASH
;
369 /* Only send magic when flashing bootrom */
371 c
.arg
[2] = START_FLASH_MAGIC
;
375 SendCommand(&c
, TRUE
);
378 fprintf(stderr
, "Warning: Your bootloader does not understand the new START_FLASH command\n");
379 fprintf(stderr
, " It is recommended that you update your bootloader\n\n");
383 LoadFlashFromSRecords(filename
, p
->start
, p
->end
, translate
);
387 static unsigned int GetProxmarkState(void)
389 unsigned int state
= 0;
392 c
.cmd
= CMD_DEVICE_INFO
;
393 SendCommand(&c
, FALSE
);
396 ReceiveCommand(&resp
);
398 * 1. The old bootrom code will ignore CMD_DEVICE_INFO, but respond with an ACK
399 * 2. The old os code will respond with CMD_DEBUG_PRINT_STRING and "unknown command"
400 * 3. The new bootrom and os codes will respond with CMD_DEVICE_INFO and flags
405 state
= DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
;
407 case CMD_DEBUG_PRINT_STRING
:
408 state
= DEVICE_INFO_FLAG_CURRENT_MODE_OS
;
410 case CMD_DEVICE_INFO
:
414 fprintf(stderr
, "Couldn't get proxmark state, bad response type: 0x%04X\n", resp
.cmd
);
420 if(state
& DEVICE_INFO_FLAG_BOOTROM_PRESENT
) printf("New bootrom present\n");
421 if(state
& DEVICE_INFO_FLAG_OSIMAGE_PRESENT
) printf("New osimage present\n");
422 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
) printf("Currently in bootrom\n");
423 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_OS
) printf("Currently in OS\n");
429 static unsigned int EnterFlashState(void)
431 unsigned int state
= GetProxmarkState();
433 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
) {
434 /* Already in flash state, we're done. */
438 if(state
& DEVICE_INFO_FLAG_CURRENT_MODE_OS
) {
439 fprintf(stderr
,"Entering flash-mode...\n");
441 bzero(&c
, sizeof(c
));
443 if( (state
& DEVICE_INFO_FLAG_BOOTROM_PRESENT
) && (state
& DEVICE_INFO_FLAG_OSIMAGE_PRESENT
) ) {
444 /* New style handover: Send CMD_START_FLASH, which will reset the board and
445 * enter the bootrom on the next boot.
447 c
.cmd
= CMD_START_FLASH
;
448 SendCommand(&c
, FALSE
);
449 fprintf(stderr
,"(You don't have to do anything. Press and release the button only if you want to abort)\n");
450 fprintf(stderr
,"Waiting for Proxmark to reappear on USB... ");
452 /* Old style handover: Ask the user to press the button, then reset the board */
453 c
.cmd
= CMD_HARDWARE_RESET
;
454 SendCommand(&c
, FALSE
);
455 fprintf(stderr
,"(Press and hold down button NOW if your bootloader requires it)\n");
456 fprintf(stderr
,"Waiting for Proxmark to reappear on USB... ");
462 while(!UsbConnect()) { Sleep(1000); }
463 fprintf(stderr
,"Found.\n");
465 return GetProxmarkState();
471 static void usage(char **argv
)
474 printf("Usage: %s gui\n", argv
[0]);
475 printf(" %s offline\n", argv
[0]);
476 printf(" %s areas file.s19\n", argv
[0]);
477 printf(" Known areas are:");
478 for(i
=0; i
<(sizeof(partitions
)/sizeof(partitions
[0])); i
++) {
479 fprintf(stderr
, " %s", partitions
[i
].name
);
485 /* On first call, have *offset = -1, *length = 0; */
486 static int find_next_area(char *str
, int *offset
, int *length
)
488 if(*str
== '\0') return 0;
489 if((*offset
>= 0) && str
[*offset
+ *length
] == '\0') return 0;
490 *offset
+= 1 + *length
;
492 char *next_comma
= strchr(str
+ *offset
, ',');
493 if(next_comma
== NULL
) {
494 *length
= strlen(str
) - *offset
;
496 *length
= next_comma
-(str
+*offset
);
501 int main(int argc
, char **argv
)
510 // Only do this if NOT in offline mode
511 if (strcmp(argv
[1], "offline"))
518 printf("...no device connected, polling for it now\n");
521 printf("Could not connect to USB device; exiting.\n");
529 if(strcmp(argv
[1], "gui")==0) {
531 } else if(strcmp(argv
[1], "offline")==0) {
536 /* Count area arguments */
537 int areas
= 0, offset
=-1, length
=0;
538 while(find_next_area(argv
[1], &offset
, &length
)) areas
++;
540 if(areas
!= argc
- 2) {
545 unsigned int state
= EnterFlashState();
547 if( !(state
& DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM
) ) {
548 fprintf(stderr
, "Proxmark would not enter flash state, abort\n");
553 int current_area
= 0;
554 while(find_next_area(argv
[1], &offset
, &length
)) {
556 struct partition
*p
= NULL
;
557 for(i
=0; i
<sizeof(partitions
)/sizeof(partitions
[0]); i
++) {
558 if(strncmp(partitions
[i
].name
, argv
[1] + offset
, length
) == 0) {
559 /* Check if the name matches the bootrom partition, and if so, require "bootrom" to
560 * be written in full. The other names may be abbreviated.
562 if(!partitions
[i
].precious
|| (strlen(partitions
[i
].name
) == length
)) {
570 fprintf(stderr
, "Warning: area name '");
571 fwrite(argv
[1]+offset
, length
, 1, stderr
);
572 fprintf(stderr
, "' unknown, ignored\n");
574 fprintf(stderr
, "Flashing %s from %s\n", p
->name
, argv
[2+current_area
]);
575 PrepareFlash(p
, argv
[2+current_area
], state
);