]> git.zerfleddert.de Git - proxmark3-svn/blob - client/prox.c
There's no painless way to do this, but it needs to be done --
[proxmark3-svn] / client / prox.c
1 #include <windows.h>
2 #include <setupapi.h>
3 #include <stdio.h>
4 #include <ctype.h>
5 #include <stdlib.h>
6 //extern "C" {
7 #include "include/hidusage.h"
8 #include "include/hidpi.h"
9 #include "include/hidsdi.h"
10 //}
11
12 #include "prox.h"
13
14 #define OUR_VID 0x9ac4
15 #define OUR_PID 0x4b8f
16 #define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
17
18 int offline = 0;
19 HANDLE UsbHandle;
20
21 static void ShowError(void)
22 {
23 char buf[1024];
24 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0,
25 buf, sizeof(buf), NULL);
26 printf("ERROR: %s", buf);
27 }
28
29 static BOOL UsbConnect(void)
30 {
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);
36 GetGuidProc getGuid;
37 GetAttrProc getAttr;
38 GetPreparsedProc getPreparsed;
39 GetCapsProc getCaps;
40
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");
46
47 GUID hidGuid;
48 getGuid(&hidGuid);
49
50 HDEVINFO devInfo;
51 devInfo = SetupDiGetClassDevs(&hidGuid, NULL, NULL,
52 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
53
54 SP_DEVICE_INTERFACE_DATA devInfoData;
55 devInfoData.cbSize = sizeof(devInfoData);
56
57 int i;
58 for(i = 0;; i++) {
59 if(!SetupDiEnumDeviceInterfaces(devInfo, 0, &hidGuid, i, &devInfoData))
60 {
61 if(GetLastError() != ERROR_NO_MORE_ITEMS) {
62 // printf("SetupDiEnumDeviceInterfaces failed\n");
63 }
64 // printf("done list\n");
65 SetupDiDestroyDeviceInfoList(devInfo);
66 return FALSE;
67 }
68
69 // printf("item %d:\n", i);
70
71 DWORD sizeReqd = 0;
72 if(!SetupDiGetDeviceInterfaceDetail(devInfo, &devInfoData,
73 NULL, 0, &sizeReqd, NULL))
74 {
75 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
76 // printf("SetupDiGetDeviceInterfaceDetail (0) failed\n");
77 continue;
78 }
79 }
80
81 SP_DEVICE_INTERFACE_DETAIL_DATA *devInfoDetailData =
82 (SP_DEVICE_INTERFACE_DETAIL_DATA *)malloc(sizeReqd);
83 devInfoDetailData->cbSize = sizeof(*devInfoDetailData);
84
85 if(!SetupDiGetDeviceInterfaceDetail(devInfo, &devInfoData,
86 devInfoDetailData, 87, NULL, NULL))
87 {
88 // printf("SetupDiGetDeviceInterfaceDetail (1) failed\n");
89 continue;
90 }
91
92 char *path = devInfoDetailData->DevicePath;
93
94 UsbHandle = CreateFile(path, /*GENERIC_READ |*/ GENERIC_WRITE,
95 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
96 FILE_FLAG_OVERLAPPED, NULL);
97
98 if(UsbHandle == INVALID_HANDLE_VALUE) {
99 ShowError();
100 // printf("CreateFile failed: for '%s'\n", path);
101 continue;
102 }
103
104 HIDD_ATTRIBUTES attr;
105 attr.Size = sizeof(attr);
106 if(!getAttr(UsbHandle, &attr)) {
107 ShowError();
108 // printf("HidD_GetAttributes failed\n");
109 continue;
110 }
111
112 // printf("VID: %04x PID %04x\n", attr.VendorID, attr.ProductID);
113
114 if(attr.VendorID != OUR_VID || attr.ProductID != OUR_PID) {
115 CloseHandle(UsbHandle);
116 // printf(" nope, not us\n");
117 continue;
118 }
119
120 // printf ("got it!\n");
121 CloseHandle(UsbHandle);
122
123 UsbHandle = CreateFile(path, GENERIC_READ | GENERIC_WRITE,
124 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
125 FILE_FLAG_OVERLAPPED, NULL);
126
127 if(UsbHandle == INVALID_HANDLE_VALUE) {
128 ShowError();
129 // printf("Error, couldn't open our own handle as desired.\n");
130 return FALSE;
131 }
132
133 PHIDP_PREPARSED_DATA pp;
134 getPreparsed(UsbHandle, &pp);
135 HIDP_CAPS caps;
136
137 if(getCaps(pp, &caps) != HIDP_STATUS_SUCCESS) {
138 // printf("getcaps failed\n");
139 return FALSE;
140 }
141
142 // printf("input/out report %d/%d\n", caps.InputReportByteLength,
143 // caps.OutputReportByteLength);
144
145
146 return TRUE;
147 }
148 return FALSE;
149 }
150
151 bool ReceiveCommandPoll(UsbCommand *c)
152 {
153 static BOOL ReadInProgress = FALSE;
154 static OVERLAPPED Ov;
155 static BYTE Buf[65];
156 static DWORD HaveRead;
157
158 if(!ReadInProgress) {
159 memset(&Ov, 0, sizeof(Ov));
160 ReadFile(UsbHandle, Buf, 65, &HaveRead, &Ov);
161 if(GetLastError() != ERROR_IO_PENDING) {
162 ShowError();
163 exit(-1);
164 }
165 ReadInProgress = TRUE;
166 }
167
168 if(HasOverlappedIoCompleted(&Ov)) {
169 ReadInProgress = FALSE;
170
171 if(!GetOverlappedResult(UsbHandle, &Ov, &HaveRead, FALSE)) {
172 ShowError();
173 exit(-1);
174 }
175
176 memcpy(c, Buf+1, 64);
177
178 return TRUE;
179 } else {
180 return FALSE;
181 }
182 }
183
184 void ReceiveCommand(UsbCommand *c)
185 {
186 while(!ReceiveCommandPoll(c)) {
187 Sleep(0);
188 }
189 }
190
191 void SendCommand(UsbCommand *c, bool wantAck)
192 {
193 BYTE buf[65];
194 buf[0] = 0;
195 memcpy(buf+1, c, 64);
196
197 DWORD written;
198 OVERLAPPED ov;
199
200 memset(&ov, 0, sizeof(ov));
201 WriteFile(UsbHandle, buf, 65, &written, &ov);
202 if(GetLastError() != ERROR_IO_PENDING) {
203 ShowError();
204 exit(-1);
205 }
206
207 while(!HasOverlappedIoCompleted(&ov)) {
208 Sleep(0);
209 }
210
211 if(!GetOverlappedResult(UsbHandle, &ov, &written, FALSE)) {
212 ShowError();
213 exit(-1);
214 }
215
216 if(wantAck) {
217 UsbCommand ack;
218 ReceiveCommand(&ack);
219 if(ack.cmd != CMD_ACK) {
220 printf("bad ACK\n");
221 exit(-1);
222 }
223 }
224 }
225
226 static DWORD ExpectedAddr;
227 static BYTE QueuedToSend[256];
228 static BOOL AllWritten;
229 #define PHYSICAL_FLASH_START 0x100000
230
231 struct partition {
232 int start;
233 int end;
234 int precious;
235 const char *name;
236 };
237 struct partition partitions[] = {
238 {0x100000, 0x102000, 1, "bootrom"},
239 {0x102000, 0x110000, 0, "fpga"},
240 {0x110000, 0x140000, 0, "os"},
241 };
242
243 /* If translate is set, subtract PHYSICAL_FLASH_START to translate for old
244 * bootroms.
245 */
246 static void FlushPrevious(int translate)
247 {
248 UsbCommand c;
249 memset(&c, 0, sizeof(c));
250
251 // printf("expected = %08x flush, ", ExpectedAddr);
252
253 int i;
254 for(i = 0; i < 240; i += 48) {
255 c.cmd = CMD_SETUP_WRITE;
256 memcpy(c.d.asBytes, QueuedToSend+i, 48);
257 c.arg[0] = (i/4);
258 SendCommand(&c, TRUE);
259 }
260
261 c.cmd = CMD_FINISH_WRITE;
262 c.arg[0] = (ExpectedAddr-1) & (~255);
263 if(translate) {
264 c.arg[0] -= PHYSICAL_FLASH_START;
265 }
266 printf("Flashing address: %08x\r", c.arg[0]);
267 memcpy(c.d.asBytes, QueuedToSend+240, 16);
268 SendCommand(&c, TRUE);
269
270 AllWritten = TRUE;
271 }
272
273 /* Where must be between start_addr (inclusive) and end_addr (exclusive).
274 */
275 static void GotByte(int where, BYTE which, int start_addr, int end_addr, int translate)
276 {
277 AllWritten = FALSE;
278
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);
281 exit(-1);
282 }
283
284 if(where != ExpectedAddr) {
285 printf("bad: got at %08x, expected at %08x\n", where, ExpectedAddr);
286 exit(-1);
287 }
288 QueuedToSend[where & 255] = which;
289 ExpectedAddr++;
290
291 if((where & 255) == 255) {
292 // we have completed a full page
293 FlushPrevious(translate);
294 }
295 }
296
297 static int HexVal(int c)
298 {
299 c = tolower(c);
300 if(c >= '0' && c <= '9') {
301 return c - '0';
302 } else if(c >= 'a' && c <= 'f') {
303 return (c - 'a') + 10;
304 } else {
305 printf("bad hex digit '%c'\n", c);
306 exit(-1);
307 }
308 }
309
310 static BYTE HexByte(char *s)
311 {
312 return (HexVal(s[0]) << 4) | HexVal(s[1]);
313 }
314
315 static void LoadFlashFromSRecords(const char *file, int start_addr, int end_addr, int translate)
316 {
317 ExpectedAddr = start_addr;
318
319 FILE *f = fopen(file, "r");
320 if(!f) {
321 printf("couldn't open file\n");
322 exit(-1);
323 }
324
325 char line[512];
326 while(fgets(line, sizeof(line), f)) {
327 if(memcmp(line, "S3", 2)==0) {
328 char *s = line + 2;
329 int len = HexByte(s) - 5;
330 s += 2;
331
332 char addrStr[9];
333 memcpy(addrStr, s, 8);
334 addrStr[8] = '\0';
335 DWORD addr;
336 sscanf(addrStr, "%x", &addr);
337 s += 8;
338
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;
342
343 int i;
344 for(i = 0; i < len; i++) {
345 while((addr+i) > ExpectedAddr) {
346 GotByte(ExpectedAddr, 0xff, start_addr, end_addr, translate);
347 }
348 GotByte(addr+i, HexByte(s), start_addr, end_addr, translate);
349 s += 2;
350 }
351 }
352 }
353
354 if(!AllWritten) FlushPrevious(translate);
355
356 fclose(f);
357 printf("\ndone.\n");
358 }
359
360 static int PrepareFlash(struct partition *p, const char *filename, unsigned int state)
361 {
362 int translate = 0;
363 if(state & DEVICE_INFO_FLAG_UNDERSTANDS_START_FLASH) {
364 UsbCommand c;
365 c.cmd = CMD_START_FLASH;
366 c.arg[0] = p->start;
367 c.arg[1] = p->end;
368
369 /* Only send magic when flashing bootrom */
370 if(p->precious) {
371 c.arg[2] = START_FLASH_MAGIC;
372 } else {
373 c.arg[2] = 0;
374 }
375 SendCommand(&c, TRUE);
376 translate = 0;
377 } else {
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");
380 translate = 1;
381 }
382
383 LoadFlashFromSRecords(filename, p->start, p->end, translate);
384 return 1;
385 }
386
387 static unsigned int GetProxmarkState(void)
388 {
389 unsigned int state = 0;
390
391 UsbCommand c;
392 c.cmd = CMD_DEVICE_INFO;
393 SendCommand(&c, FALSE);
394
395 UsbCommand resp;
396 ReceiveCommand(&resp);
397 /* Three cases:
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
401 */
402
403 switch(resp.cmd) {
404 case CMD_ACK:
405 state = DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM;
406 break;
407 case CMD_DEBUG_PRINT_STRING:
408 state = DEVICE_INFO_FLAG_CURRENT_MODE_OS;
409 break;
410 case CMD_DEVICE_INFO:
411 state = resp.arg[0];
412 break;
413 default:
414 fprintf(stderr, "Couldn't get proxmark state, bad response type: 0x%04X\n", resp.cmd);
415 exit(-1);
416 break;
417 }
418
419 #if 0
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");
424 #endif
425
426 return state;
427 }
428
429 static unsigned int EnterFlashState(void)
430 {
431 unsigned int state = GetProxmarkState();
432
433 if(state & DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM) {
434 /* Already in flash state, we're done. */
435 return state;
436 }
437
438 if(state & DEVICE_INFO_FLAG_CURRENT_MODE_OS) {
439 fprintf(stderr,"Entering flash-mode...\n");
440 UsbCommand c;
441 bzero(&c, sizeof(c));
442
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.
446 */
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... ");
451 } else {
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... ");
457 }
458
459
460 Sleep(1000);
461
462 while(!UsbConnect()) { Sleep(1000); }
463 fprintf(stderr,"Found.\n");
464
465 return GetProxmarkState();
466 }
467
468 return 0;
469 }
470
471 static void usage(char **argv)
472 {
473 int i;
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);
480 }
481
482 printf("\n");
483 }
484
485 /* On first call, have *offset = -1, *length = 0; */
486 static int find_next_area(char *str, int *offset, int *length)
487 {
488 if(*str == '\0') return 0;
489 if((*offset >= 0) && str[*offset + *length] == '\0') return 0;
490 *offset += 1 + *length;
491
492 char *next_comma = strchr(str + *offset, ',');
493 if(next_comma == NULL) {
494 *length = strlen(str) - *offset;
495 } else {
496 *length = next_comma-(str+*offset);
497 }
498 return 1;
499 }
500
501 int main(int argc, char **argv)
502 {
503 int i = 0;
504
505 if(argc < 2) {
506 usage(argv);
507 exit(-1);
508 }
509
510 // Only do this if NOT in offline mode
511 if (strcmp(argv[1], "offline"))
512 {
513 for(;;) {
514 if(UsbConnect()) {
515 break;
516 }
517 if(i == 0) {
518 printf("...no device connected, polling for it now\n");
519 }
520 if(i > 50000) {
521 printf("Could not connect to USB device; exiting.\n");
522 return -1;
523 }
524 i++;
525 Sleep(5);
526 }
527 }
528
529 if(strcmp(argv[1], "gui")==0) {
530 ShowGui();
531 } else if(strcmp(argv[1], "offline")==0) {
532 offline = 1;
533 ShowGui();
534 }
535
536 /* Count area arguments */
537 int areas = 0, offset=-1, length=0;
538 while(find_next_area(argv[1], &offset, &length)) areas++;
539
540 if(areas != argc - 2) {
541 usage(argv);
542 exit(-1);
543 }
544
545 unsigned int state = EnterFlashState();
546
547 if( !(state & DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM) ) {
548 fprintf(stderr, "Proxmark would not enter flash state, abort\n");
549 exit(-1);
550 }
551
552 offset=-1; length=0;
553 int current_area = 0;
554 while(find_next_area(argv[1], &offset, &length)) {
555 int i;
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.
561 */
562 if(!partitions[i].precious || (strlen(partitions[i].name) == length)) {
563 p = &partitions[i];
564 }
565 break;
566 }
567 }
568
569 if(p == NULL) {
570 fprintf(stderr, "Warning: area name '");
571 fwrite(argv[1]+offset, length, 1, stderr);
572 fprintf(stderr, "' unknown, ignored\n");
573 } else {
574 fprintf(stderr, "Flashing %s from %s\n", p->name, argv[2+current_area]);
575 PrepareFlash(p, argv[2+current_area], state);
576 }
577 current_area++;
578 }
579
580 return 0;
581 }
Impressum, Datenschutz