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