summaryrefslogtreecommitdiff
path: root/usb-i2c-sl018/tuer-rfid.c
blob: 7beccb0c8c669d5a36d67a375007f12d18fd3fab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
 *  spreadspace avr utils
 *
 *
 *  Copyright (C) 2013 Christian Pointner <equinox@spreadspace.org>
 *                     Othmar Gsenger <otti@wirdorange.org>
 *
 *  This file is part of spreadspace avr utils.
 *
 *  spreadspace avr utils is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  any later version.
 *
 *  spreadspace avr utils is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with spreadspace avr utils. If not, see <http://www.gnu.org/licenses/>.
 */

#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
#include <avr/power.h>

#include <stdio.h>
#include <string.h>

#include "util.h"
#include "led.h"

#include "heartbeat.h"
#include "stepper.h"
#include "ledmatrix.h"
#include "sl018.h"

#include "LUFA/Drivers/Peripheral/TWI.h"
#include "LUFA/Drivers/Peripheral/Serial.h"
#include "LUFA/Drivers/Misc/RingBuffer.h"

#include <avr/eeprom.h>
#define EEPROM_SIZE 1024
typedef uint8_t keyslot_t[8];
keyslot_t EEMEM keystore[EEPROM_SIZE/sizeof(keyslot_t)];

FILE usb_stream;
FILE serial_stream;
FILE * stdio = &serial_stream;

/*
             LUFA Library
     Copyright (C) Dean Camera, 2012.

  dean [at] fourwalledcubicle [dot] com
           www.lufa-lib.org
*/


#include <LUFA/Drivers/USB/USB.h>
#include "lufa-descriptor-usbserial.h"

USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface =
  {
    .Config =
      {
        .ControlInterfaceNumber         = 0,

        .DataINEndpointNumber           = CDC_TX_EPNUM,
        .DataINEndpointSize             = CDC_TXRX_EPSIZE,
        .DataINEndpointDoubleBank       = false,

        .DataOUTEndpointNumber          = CDC_RX_EPNUM,
        .DataOUTEndpointSize            = CDC_TXRX_EPSIZE,
        .DataOUTEndpointDoubleBank      = false,

        .NotificationEndpointNumber     = CDC_NOTIFICATION_EPNUM,
        .NotificationEndpointSize       = CDC_NOTIFICATION_EPSIZE,
        .NotificationEndpointDoubleBank = false,
      },
  };

void EVENT_USB_Device_ConfigurationChanged(void)
{
  CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface);
}

void EVENT_USB_Device_ControlRequest(void)
{
  CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface);
}

void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)	
{
  if(CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
    stdio = &usb_stream;
  else
    stdio = &serial_stream;
}

void EVENT_USB_Device_Disconnect(void)
{
  stdio = &serial_stream;
}
/* end LUFA CDC-ACM specific definitions*/



int16_t stdio_bytes_received(void)
{
  if(stdio == &usb_stream)
    return CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface);
  else
    return (int16_t)Serial_IsCharReceived();
}


void flash_keystore_from_stdio(void)
{
  keyslot_t ks;
  uint8_t byte_pos=0;
  fprintf(stdio,"Flashing keys:\n\r");
  fflush(stdio);
  for(uint8_t ks_pos=0;ks_pos<EEPROM_SIZE/sizeof(ks);) {
    CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
    USB_USBTask();

    int16_t bytes_received = stdio_bytes_received();
    while(bytes_received > 0) {
      ks[byte_pos++]=fgetc(stdio);
      bytes_received--;
      if (byte_pos == sizeof(ks)) {
        byte_pos=0;
        eeprom_update_block(&ks,&keystore[ks_pos],sizeof(ks));
        ks_pos++;
        fputc('.', stdio);
        fflush(stdio);
        led_toggle();
      }
    }
  }
  fprintf(stdio,"\n");
  fputc(0, stdio);
  led_off();
}

void dump_keystore_to_stdio(void)
{
  keyslot_t ks;
  for(uint8_t ks_pos=0;ks_pos<EEPROM_SIZE/sizeof(ks);ks_pos++) {
    eeprom_read_block(&ks,&keystore[ks_pos],sizeof(ks));
    for (uint8_t i=0; i< sizeof(ks); i++)
      fprintf(stdio,"%02X",ks[i]);
    fprintf(stdio,"\n\r");
  }
}

void handle_stdio(uint8_t cmd)
{  
  switch(cmd) {
    case 'r': 
             reset2bootloader(); 
             break;
    case 'R': 
             if(!sl018_reset(stdio))
               fprintf(stdio, "ok\n\r");
             break;
    case 'f': //get cardreader firmware version
             do {
               unsigned char * firmware_str = sl018_get_firmware_version(stdio);
               if(firmware_str)
                 fprintf(stdio, "%s\n\r",firmware_str);
             } while(0);    
             break;
    case 'e': //flash eeprom
             flash_keystore_from_stdio();
             break;
    case 'd': //dump eeprom - this breaks security!
             dump_keystore_to_stdio();
             break;
    case 'o': 
             if(start_stepper(dir_open))
               fprintf(stdio, "ok\n\r");
             else
               fprintf(stdio, "error: already in progress\n\r");
             break;
    case 'c': 
             if(start_stepper(dir_close))
               fprintf(stdio, "ok\n\r");
             else
               fprintf(stdio, "error: already in progress\n\r");
             break;
    case '0': ledmatrix(off); break;
    case '1': ledmatrix(red); break;
    case '2': ledmatrix(red_moving); break;
    case '3': ledmatrix(red_blink); break;
    case '4': ledmatrix(green); break;
    case '5': ledmatrix(green_moving); break;
    case '6': ledmatrix(green_blink); break;
    case '7': ledmatrix(rg_moving); break;
    case '8': ledmatrix(rg_blink); break;
    default: fprintf(stdio, "error, unknown command %02X '%c'\n\r",cmd, cmd); return;
  }
}



/* this generates a Fletcher8 checksum  */
/* code from: http://stackoverflow.com/questions/13491700/8-bit-fletcher-checksum-of-16-byte-data */
uint8_t generate_csum(uint8_t* data)
{
  uint16_t sum1 = 0xf, sum2 = 0xf, len = sizeof(keyslot_t) - 1;
  do { sum2 += ( sum1 += *data++ ); } while (--len);
  return sum2<<4 | sum1;
}

uint8_t compare_keyslots(const keyslot_t a, const keyslot_t b)
{
  uint8_t tmp=0;
      // constant time compare
  for(uint8_t i=0; i<sizeof(keyslot_t); ++i)
    tmp |= a[i] ^ b[i];
  return tmp;
}

bool check_card(const uint8_t * uid, uint8_t uid_len)
{
  keyslot_t card, ks;
  memset(card, 0, sizeof(card));
  for (uint8_t pos=0; pos<uid_len; pos++)
    card[pos]=uid[uid_len-pos-1];
  card[sizeof(keyslot_t)-1]=generate_csum(card);
  bool valid=0;
  for(uint8_t ks_pos=0;ks_pos<(EEPROM_SIZE/sizeof(ks));ks_pos++) {
    eeprom_read_block(&ks,&keystore[ks_pos],sizeof(ks));
    if(!compare_keyslots(card, ks)) {
      valid=1;
      // break;  // this would break security (not constant time)
    }
  }
  return valid;
}

void handle_card(void)
{
  uid_t uid;
  sl018_read_card_uid(&uid,stdio);
  if (uid.length)
  {
    if(check_card(uid.buffer,uid.length)) {  
      sl018_set_led(1,stdio);
      _delay_ms(255);  
      fprintf(stdio,"Card allowed - opening/closing door\n\r"); // TODO: open/close door!  
      sl018_set_led(0,stdio);
    } else {  
      fprintf(stdio,"Card not found in Database\n\r");  
    } 
  }
}

int main(void)
{
  MCUSR &= ~(1 << WDRF);
  wdt_disable();

  cpu_init();
  led_init();
  USB_Init();
  TWI_Init(TWI_BIT_PRESCALE_1, TWI_BITLENGTH_FROM_FREQ(1, 200000));
  Serial_Init(115200,false);
  Serial_CreateStream(&serial_stream);
  CDC_Device_CreateStream(&VirtualSerial_CDC_Interface,&usb_stream);

  sei();  

  init_heartbeat();
  init_stepper();
  init_ledmatrix();

  sl018_reset(stdio);

  for(;;) {
    CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
    USB_USBTask();

    int16_t bytes_received = stdio_bytes_received();
    if(bytes_received > 0)
      handle_stdio(fgetc(stdio));

    if (sl018_check_for_new_card(stdio))
      handle_card();
    handle_heartbeat();
  }
}