]> git.cryptolib.org Git - labortage2013badge.git/blob - firmware/main.c
b1afcdced995686b1c2f6475d09aa023b1bd03dc
[labortage2013badge.git] / firmware / main.c
1 /* Name: main.c
2  * Project: labortage-2013-badge
3  * Author: bg (bg@das-labor.org)
4  * Creation Date: 2013-10-16
5  * Tabsize: 4
6  * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH, (c) Daniel Otte
7  * License: GNU GPL v3
8  * This Revision: $Id: main.c 692 2008-11-07 15:07:40Z cs $
9  */
10
11 /*
12 This example should run on most AVRs with only little changes. No special
13 hardware resources except INT0 are used. You may have to change usbconfig.h for
14 different I/O pins for USB. Please note that USB D+ must be the INT0 pin, or
15 at least be connected to INT0 as well.
16 */
17
18 #define BUTTON_PIN 5
19 #define DEBOUNCE_DELAY 50
20 #define SIMPLE_COUNTER 1
21 #define NO_CHECK 1
22 #define ALLOW_SECRET_READ 0
23
24 #include <stdint.h>
25 #include <string.h>
26 #include <stdbool.h>
27
28 #include <avr/io.h>
29 #include <avr/wdt.h>
30 #include <avr/eeprom.h>
31 #include <avr/interrupt.h>  /* for sei() */
32 #include <util/delay.h>     /* for _delay_ms() */
33
34 #include <avr/pgmspace.h>   /* required by usbdrv.h */
35 #include "usbdrv.h"
36 #include "requests.h"       /* The custom request numbers we use */
37 #include "hotp.h"
38 #include "special_functions.h"
39 #if !SIMPLE_COUNTER
40 #include "percnt2.h"
41 #endif
42 #include "usb_keyboard_codes.h"
43
44 /* ------------------------------------------------------------------------- */
45 /* ----------------------------- USB interface ----------------------------- */
46 /* ------------------------------------------------------------------------- */
47
48 #define STATE_WAIT 0
49 #define STATE_SEND_KEY 1
50 #define STATE_RELEASE_KEY 2
51 #define STATE_NEXT 3
52
53 PROGMEM const char usbHidReportDescriptor[USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH] = {
54     0x05, 0x01,                    /* USAGE_PAGE (Generic Desktop) */
55     0x09, 0x06,                    /* USAGE (Keyboard) */
56     0xa1, 0x01,                    /* COLLECTION (Application) */
57     0x75, 0x01,                    /*   REPORT_SIZE (1) */
58     0x95, 0x08,                    /*   REPORT_COUNT (8) */
59     0x05, 0x07,                    /*   USAGE_PAGE (Keyboard)(Key Codes) */
60     0x19, 0xe0,                    /*   USAGE_MINIMUM (Keyboard LeftControl)(224) */
61     0x29, 0xe7,                    /*   USAGE_MAXIMUM (Keyboard Right GUI)(231) */
62     0x15, 0x00,                    /*   LOGICAL_MINIMUM (0) */
63     0x25, 0x01,                    /*   LOGICAL_MAXIMUM (1) */
64     0x81, 0x02,                    /*   INPUT (Data,Var,Abs) ; Modifier byte */
65     0x95, 0x01,                    /*   REPORT_COUNT (1) */
66     0x75, 0x08,                    /*   REPORT_SIZE (8) */
67     0x81, 0x03,                    /*   INPUT (Cnst,Var,Abs) ; Reserved byte */
68     0x95, 0x05,                    /*   REPORT_COUNT (5) */
69     0x75, 0x01,                    /*   REPORT_SIZE (1) */
70     0x05, 0x08,                    /*   USAGE_PAGE (LEDs) */
71     0x19, 0x01,                    /*   USAGE_MINIMUM (Num Lock) */
72     0x29, 0x05,                    /*   USAGE_MAXIMUM (Kana) */
73     0x91, 0x02,                    /*   OUTPUT (Data,Var,Abs) ; LED report */
74     0x95, 0x01,                    /*   REPORT_COUNT (1) */
75     0x75, 0x03,                    /*   REPORT_SIZE (3) */
76     0x91, 0x03,                    /*   OUTPUT (Cnst,Var,Abs) ; LED report padding */
77     0x95, 0x06,                    /*   REPORT_COUNT (6) */
78     0x75, 0x08,                    /*   REPORT_SIZE (8) */
79     0x15, 0x00,                    /*   LOGICAL_MINIMUM (0) */
80     0x25, 0x65,                    /*   LOGICAL_MAXIMUM (101) */
81     0x05, 0x07,                    /*   USAGE_PAGE (Keyboard)(Key Codes) */
82     0x19, 0x00,                    /*   USAGE_MINIMUM (Reserved (no event indicated))(0) */
83     0x29, 0x65,                    /*   USAGE_MAXIMUM (Keyboard Application)(101) */
84     0x81, 0x00,                    /*   INPUT (Data,Ary,Abs) */
85     0xc0                           /* END_COLLECTION */
86 };
87
88 static uint16_t secret_length_ee EEMEM = 0;
89 static uint8_t  secret_ee[32] EEMEM;
90 static uint8_t  reset_counter_ee EEMEM = 0;
91 static uint8_t  digits_ee EEMEM = 8;
92
93 #if SIMPLE_COUNTER
94 static uint32_t counter_ee EEMEM = 0;
95 #endif
96
97 static uint8_t dbg_buffer[8];
98 static uint8_t secret[32];
99 static uint16_t secret_length_b;
100 static char token[10];
101
102 #define UNI_BUFFER_SIZE 16
103
104 static union __attribute__((packed)) {
105         uint8_t  w8[UNI_BUFFER_SIZE];
106         uint16_t w16[UNI_BUFFER_SIZE/2];
107         uint32_t w32[UNI_BUFFER_SIZE/4];
108         void*    ptr[UNI_BUFFER_SIZE/sizeof(void*)];
109 } uni_buffer;
110
111 static uint8_t current_command;
112
113 typedef struct __attribute__((packed)) {
114     uint8_t modifier;
115     uint8_t reserved;
116     uint8_t keycode[6];
117 } keyboard_report_t;
118
119 static keyboard_report_t keyboard_report; /* report sent to the host */
120 static uchar idleRate;  /* in 4 ms units */
121 static uchar key_state = STATE_WAIT;
122 volatile static uchar LED_state = 0xff;
123 /* ------------------------------------------------------------------------- */
124
125 static
126 void memory_clean(void) {
127     memset(secret, 0, 32);
128     secret_length_b = 0;
129 }
130
131 static
132 uint8_t secret_set(void){
133 #if !NO_CHECK
134     uint8_t r;
135     union {
136         uint8_t w8[32];
137         uint16_t w16[16];
138     } read_back;
139 #endif
140     const uint8_t length_B = (secret_length_b + 7) / 8;
141
142     eeprom_busy_wait();
143     eeprom_write_block(secret, secret_ee, length_B);
144 #if !NO_CHECK
145     eeprom_busy_wait();
146     eeprom_read_block(read_back.w8, secret_ee, length_B);
147     r = memcmp(secret, read_back.w8, length_B);
148     memory_clean();
149     memset(read_back.w8, 0, 32);
150     if (r) {
151         return 1;
152     }
153 #endif
154     eeprom_busy_wait();
155     eeprom_write_word(&secret_length_ee, secret_length_b);
156 #if !NO_CHECK
157     eeprom_busy_wait();
158     r = eeprom_read_word(&secret_length_ee) == secret_length_b;
159     memory_clean();
160     *read_back.w16 = 0;
161     if (!r) {
162         return 1;
163     }
164 #else
165     memory_clean();
166 #endif
167
168     return 0;
169 }
170
171 static
172 void counter_inc(void){
173 #if SIMPLE_COUNTER
174     uint32_t t;
175     eeprom_busy_wait();
176     t = eeprom_read_dword(&counter_ee);
177     eeprom_busy_wait();
178     eeprom_write_dword(&counter_ee, t + 1);
179 #else
180     percnt_inc(0);
181 #endif
182 }
183
184 static
185 void counter_reset(void) {
186     uint8_t reset_counter;
187     eeprom_busy_wait();
188     reset_counter = eeprom_read_byte(&reset_counter_ee);
189 #if SIMPLE_COUNTER
190     eeprom_busy_wait();
191     eeprom_write_dword(&counter_ee, 0);
192 #else
193     percnt_reset(0);
194 #endif
195     eeprom_busy_wait();
196     eeprom_write_byte(&reset_counter_ee, reset_counter + 1);
197 }
198
199 static
200 void counter_init(void) {
201 #if !SIMPLE_COUNTER
202     eeprom_busy_wait();
203     if (eeprom_read_byte(&reset_counter_ee) == 0) {
204         counter_reset();
205     }
206     percnt_init(0);
207 #endif
208 }
209
210 static
211 void token_generate(void) {
212     uint16_t s_length_b;
213     uint8_t digits;
214     counter_inc();
215     eeprom_busy_wait();
216     eeprom_read_block(secret, secret_ee, 32);
217     eeprom_busy_wait();
218     s_length_b = eeprom_read_word(&secret_length_ee);
219     if (s_length_b > 256) {
220         s_length_b = 256;
221     }
222     eeprom_busy_wait();
223     digits = eeprom_read_byte(&digits_ee);
224 #if SIMPLE_COUNTER
225     eeprom_busy_wait();
226     hotp(token, secret, s_length_b, eeprom_read_dword(&counter_ee) - 1, digits);
227 #else
228     hotp(token, secret, s_length_b, percnt_get(0) - 1, digits);
229 #endif
230     memory_clean();
231 }
232
233
234 static
235 void buildReport(uchar send_key) {
236     keyboard_report.modifier = 0;
237     switch (send_key) {
238     case '1' ... '9':
239         keyboard_report.keycode[0] = KEY_1 + (send_key-'1');
240         break;
241     case '0':
242         keyboard_report.keycode[0] = KEY_0;
243         break;
244     default:
245         keyboard_report.keycode[0] = 0;
246     }
247 }
248
249 static
250 int8_t button_get_debounced(volatile int8_t debounce_count) {
251     uint8_t v;
252     v = PINB & _BV(BUTTON_PIN);
253     while (debounce_count-- && (v == (PINB & _BV(BUTTON_PIN)))) {
254         ;
255     }
256     if (debounce_count != -1) {
257         return -1;
258     }
259     return v ? 0 : 1;
260 }
261
262 usbMsgLen_t usbFunctionSetup(uchar data[8])
263 {
264         usbRequest_t    *rq = (usbRequest_t *)data;
265         if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) {    /* class request type */
266             switch(rq->bRequest) {
267         case USBRQ_HID_GET_REPORT: /* send "no keys pressed" if asked here */
268             /* wValue: ReportType (highbyte), ReportID (lowbyte) */
269             usbMsgPtr = (void *)&keyboard_report; /* we only have this one */
270             keyboard_report.modifier = 0;
271             keyboard_report.keycode[0] = 0;
272             return sizeof(keyboard_report);
273         case USBRQ_HID_SET_REPORT: /* if wLength == 1, should be LED state */
274             if (rq->wLength.word == 1) {
275                 current_command = LED_WRITE;
276                 return USB_NO_MSG;
277             }
278             return 0;
279         case USBRQ_HID_GET_IDLE: /* send idle rate to PC as required by spec */
280             usbMsgPtr = &idleRate;
281             return 1;
282         case USBRQ_HID_SET_IDLE: /* save idle rate as required by spec */
283             idleRate = rq->wValue.bytes[1];
284             return 0;
285         }
286     }
287     if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
288                 current_command = rq->bRequest;
289         usbMsgPtr = uni_buffer.w8;
290         switch(rq->bRequest)
291                 {
292         case CUSTOM_RQ_SET_SECRET:
293             secret_length_b = rq->wValue.word;
294             if (secret_length_b > 256) {
295                 secret_length_b = 256;
296             }
297             uni_buffer.w8[0] = 0;
298             return USB_NO_MSG;
299         case CUSTOM_RQ_INC_COUNTER:
300             counter_inc();
301             return 0;
302         case CUSTOM_RQ_GET_COUNTER:
303 #if SIMPLE_COUNTER
304             eeprom_busy_wait();
305             uni_buffer.w32[0] = eeprom_read_dword(&counter_ee);
306 #else
307             uni_buffer.w32[0] = percnt_get(0);
308 #endif
309             return 4;
310         case CUSTOM_RQ_RESET_COUNTER:
311             counter_reset();
312             return 0;
313         case CUSTOM_RQ_GET_RESET_COUNTER:
314             eeprom_busy_wait();
315             uni_buffer.w8[0] = eeprom_read_byte(&reset_counter_ee);
316             return 1;
317         case CUSTOM_RQ_SET_DIGITS:
318             if (rq->wValue.bytes[0] < 6) {
319                 rq->wValue.bytes[0] = 6;
320             }
321             if (rq->wValue.bytes[0] > 9) {
322                 rq->wValue.bytes[0] = 9;
323             }
324             eeprom_busy_wait();
325             eeprom_write_byte(&digits_ee, rq->wValue.bytes[0]);
326             return 0;
327         case CUSTOM_RQ_GET_DIGITS:
328             eeprom_busy_wait();
329             uni_buffer.w8[0] = eeprom_read_byte(&digits_ee);
330             return 1;
331         case CUSTOM_RQ_GET_TOKEN:
332             token_generate();
333             usbMsgPtr = (usbMsgPtr_t)token;
334             return strlen(token);
335         case CUSTOM_RQ_PRESS_BUTTON:
336             key_state = STATE_SEND_KEY;
337             return 0;
338         case CUSTOM_RQ_CLR_DBG:
339             memset(dbg_buffer, 0, sizeof(dbg_buffer));
340             return 0;
341                 case CUSTOM_RQ_SET_DBG:
342                         return USB_NO_MSG;
343                 case CUSTOM_RQ_GET_DBG:{
344                         usbMsgLen_t len = 8;
345                         if(len > rq->wLength.word){
346                                 len = rq->wLength.word;
347                         }
348                         usbMsgPtr = dbg_buffer;
349                         return len;
350                 }
351                 case CUSTOM_RQ_RESET:
352                         soft_reset((uint8_t)(rq->wValue.word));
353                         break;
354                 case CUSTOM_RQ_READ_BUTTON:
355                         uni_buffer.w8[0] = button_get_debounced(DEBOUNCE_DELAY);
356                         return 1;
357                 case CUSTOM_RQ_GET_SECRET:
358                     uni_buffer.w8[0] = 0;
359                     return USB_NO_MSG;
360                 }
361     }
362
363     return 0;   /* default for not implemented requests: return no data back to host */
364 }
365
366
367 uchar usbFunctionWrite(uchar *data, uchar len)
368 {
369         switch(current_command){
370
371         case LED_WRITE:
372             if (data[0] != LED_state)
373                 LED_state = data[0];
374             return 1; /* Data read, not expecting more */
375         case CUSTOM_RQ_SET_SECRET:
376         {
377             if (uni_buffer.w8[0] < (secret_length_b + 7) / 8) {
378                 memcpy(&secret[uni_buffer.w8[0]], data, len);
379                 uni_buffer.w8[0] += len;
380             }
381             if (uni_buffer.w8[0] >= (secret_length_b + 7) / 8) {
382                 secret_set();
383                 return 1;
384             }
385             return 0;
386         }
387         case CUSTOM_RQ_SET_DBG:
388                 if(len > sizeof(dbg_buffer)){
389                         len = sizeof(dbg_buffer);
390                 }
391                 memcpy(dbg_buffer, data, len);
392                 return 1;
393         default:
394                 return 1;
395         }
396         return 0;
397 }
398
399 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
400
401 uchar usbFunctionRead(uchar *data, uchar len){
402 #if ALLOW_SECRET_READ
403     uchar r;
404     uint8_t s_length_B;
405     switch(current_command){
406     case CUSTOM_RQ_GET_SECRET:
407         eeprom_busy_wait();
408         s_length_B = (eeprom_read_word(&secret_length_ee) + 7) / 8;
409         r = MIN(len, s_length_B - uni_buffer.w8[0]);
410         eeprom_busy_wait();
411         eeprom_read_block(data, secret_ee + uni_buffer.w8[0], r);
412         uni_buffer.w8[0] += r;
413         return r;
414     }
415 #endif
416     return 0;
417 }
418
419 static void calibrateOscillator(void)
420 {
421 uchar       step = 128;
422 uchar       trialValue = 0, optimumValue;
423 int         x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
424  
425     /* do a binary search: */
426     do {
427         OSCCAL = trialValue + step;
428         x = usbMeasureFrameLength();    /* proportional to current real frequency */
429         if(x < targetValue)             /* frequency still too low */
430             trialValue += step;
431         step >>= 1;
432     } while(step > 0);
433     /* We have a precision of +/- 1 for optimum OSCCAL here */
434     /* now do a neighborhood search for optimum value */
435     optimumValue = trialValue;
436     optimumDev = x; /* this is certainly far away from optimum */
437     for (OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
438         x = usbMeasureFrameLength() - targetValue;
439         if (x < 0)
440             x = -x;
441         if (x < optimumDev) {
442             optimumDev = x;
443             optimumValue = OSCCAL;
444         }
445     }
446     OSCCAL = optimumValue;
447 }
448  
449
450 void usbEventResetReady(void)
451 {
452     cli();  /* usbMeasureFrameLength() counts CPU cycles, so disable interrupts. */
453     calibrateOscillator();
454     sei();
455 }
456
457 /* ------------------------------------------------------------------------- */
458
459 int main(void)
460 {
461         size_t idx = 0;
462         int8_t i = 0, last_stable_button_state = 0;
463
464     wdt_enable(WDTO_1S);
465     /* Even if you don't use the watchdog, turn it off here. On newer devices,
466      * the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
467      */
468     /* RESET status: all port bits are inputs without pull-up.
469      * That's the way we need D+ and D-. Therefore we don't need any
470      * additional hardware initialization.
471      */
472
473     counter_init();
474     usbInit();
475     usbDeviceDisconnect();  /* enforce re-enumeration, do this while interrupts are disabled! */
476     while(--i){             /* fake USB disconnect for ~512 ms */
477         wdt_reset();
478         _delay_ms(2);
479     }
480     usbDeviceConnect();
481         
482     sei();
483     DDRB &= ~_BV(BUTTON_PIN); /* make button pin input */
484     PORTB |= _BV(BUTTON_PIN); /* turn on pull-up resistor */
485
486     for(;;){                /* main event loop */
487         wdt_reset();
488         usbPoll();
489
490         i = button_get_debounced(DEBOUNCE_DELAY);
491         if (i != -1) {
492             if (last_stable_button_state == 0 && i == 1) {
493                 token_generate();
494                 key_state = STATE_SEND_KEY;
495             }
496             last_stable_button_state = i;
497         }
498
499         if(usbInterruptIsReady() && key_state != STATE_WAIT){
500             switch(key_state) {
501             case STATE_SEND_KEY:
502                 buildReport(token[idx]);
503                 key_state = STATE_RELEASE_KEY; /* release next */
504                 break;
505             case STATE_RELEASE_KEY:
506                 buildReport(0);
507                 ++idx;
508                 if (token[idx] == '\0') {
509                     idx = 0;
510                     key_state = STATE_WAIT;
511                 } else {
512                     key_state = STATE_SEND_KEY;
513                 }
514                 break;
515             default:
516                 key_state = STATE_WAIT; /* should not happen */
517             }
518                         /* start sending */
519             usbSetInterrupt((void *)&keyboard_report, sizeof(keyboard_report));
520
521         }
522
523     }
524     return 0;
525 }
526
527 /* ------------------------------------------------------------------------- */