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