Authentication after a read failure of a MIFARE card - arduino

An arduino and a mfrc522 rfid reader are easy to use to read and write mifare card.
My aim is to use the both key of the card in a sector, some blocks are readable with key A, and some are only readable by key B.
Setting properly the access bits allow this behaviour. So as to try it on the second sector (blocks 4 5 6 7), I set the access bits g0 [0 0 0], g1 [1 0 1], g2 [0 0 0], g3 [1 0 1] by writting the block 7 with {,0xF5,0xA5,0xA0,0x38,} cf. §8.7 of https://www.nxp.com/docs/en/data-sheet/MF1S50YYX_V1.pdf. Now the block 5 is not readable with keyA but with keyB (g1), and keyB is no more readable (g3). So when I authenticate with keyA an attempt to read the block 5 lead to an error. At this time the others authentications fail, and it is not possible to read the others blocks, though the access bits allow it.
I tried to read the second sector with key B for block 5 and keyA for the others code, it is working. But if I try to read with key A then with keyB in case of failure it is not working.
Extract of the code :
// The sector of interest is the second one : blocks 4 5 6 7
Serial.println("\nAuthenticate block 0x05 with key B");
for (i = 4; i < 8; i++) {
// Block 5 is readable with key B
status = readblock(i==5?MF1_AUTHENT1B:MF1_AUTHENT1A, i, i==5?keyB:keyA, serial);
if ( status == MI_ERR) {
Serial.print(" - Unable to read block nb. 0x");
Serial.println(i, HEX);
}
}
Serial.println("\nAuthenticate with key A then key B if failed");
for (i = 4; i < 8; i++) {
// Try to authenticate each block first with the A key.
status = readblock(MF1_AUTHENT1A, i, keyA, serial);
if ( status == MI_ERR) {
Serial.print(" - Try keyB - ");
status = readblock(MF1_AUTHENT1B, i, keyB, serial);
if ( status == MI_ERR) {
Serial.print(" - Unable to read block nb. 0x");
Serial.println(i, HEX);
}
}
}
readblock function (authentication and read)
byte readblock(byte mode, byte block, byte *key, byte *serial)
{
int j;
byte data[MAX_LEN];
byte status = MI_ERR;
// Try to authenticate the block first
status = nfc.authenticate(mode, block, key, serial);
if ( status == MI_OK) {
Serial.print("Authenticated block nb. 0x");
Serial.print(block, HEX);
// Reading block i from the tag into data.
status = nfc.readFromTag(block, data);
if (status == MI_OK) {
// If there was no error when reading; print all the hex
// values in the data.
Serial.print(" : ");
for (j = 0; j < 15; j++) {
Serial.print(data[j], HEX);
Serial.print(", ");
}
Serial.println(data[15], HEX);
} else
Serial.print(" - Read failed");
} else {
Serial.print("Failed authentication block nb. 0x");
Serial.print(block, HEX);
}
return status;
}
The result is
Authenticate block 0x05 with key B
Authenticated block nb. 0x4 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
Authenticated block nb. 0x5 : AB, CD, EF, 1, 23, 45, 67, 89, 98, 76, 54, 1A, 10, FE, DC, BA
Authenticated block nb. 0x6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
Authenticated block nb. 0x7 : 0, 0, 0, 0, 0, 0, F5, A5, A0, 38, 0, 0, 0, 0, 0, 0
Authenticate with key A then key B if failed
Authenticated block nb. 0x4 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
Authenticated block nb. 0x5 - Read failed - Try keyB - Failed authentication block nb. 0x5 - Unable to read block nb. 0x5
Failed authentication block nb. 0x6 - Try keyB - Failed authentication block nb. 0x6 - Unable to read block nb. 0x6
Failed authentication block nb. 0x7 - Try keyB - Failed authentication block nb. 0x7 - Unable to read block nb. 0x7
So I would like to know if it is possible to attempt to read a block with the bad key and then go on reading the block with the othe rkey, and so on.

An explanation can be found in https://www.nxp.com/docs/en/application-note/AN1304.pdf p.24
Each time an Authentication operation, a Read operation or a Write operation fails, the MIFARE Classic or MIFARE Plus remains silent and it does not respond anymore to any commands. In this situation in order to continue the NDEF Detection Procedure the MIFARE Classic or MIFARE Plus needs to be re-activated and selected.
So you have to re-activate and select after failure, by adding these lines to your code for instance :
Serial.println("\nAuthenticate with key A then key B if failed");
for (i = 4; i < 8; i++) {
// Try to authenticate each block first with the A key.
status = readblock(MF1_AUTHENT1A, i, keyA, serial);
if ( status == MI_ERR) {
Serial.print(" - Try keyB - ");
/** RE ACTIVATE AND SELECT ------------------------------- **/
nfc.haltTag();
status = nfc.requestTag(MF1_REQIDL, data);
if (status == MI_OK) {
status = nfc.antiCollision(data);
memcpy(serial, data, 5);
nfc.selectTag(serial);
}
/** ------------------------------------------------------ **/
status = readblock(MF1_AUTHENT1B, i, keyB, serial);
if ( status == MI_ERR) {
Serial.print(" - Unable to read block nb. 0x");
Serial.println(i, HEX);
}
}
}

Related

Convert Byte array to string and than match it with string in arduino

I cannot able to match my serial monitor data to my string.
The way I am sending data to serial is data.getBytes() where data is a string and I have to keep it that way.
So now I have to convert that data to string and than match it to its equivalent string but I couldn't figure that out.
aduino code inside void loop() is:
if(Serial.available()){ // only send data back if data has been sent
byte msg = Serial.read();
byte plain[a.length()]; // String a = "2"
byte inString = a.getBytes(plain, a.length(), 0); // read the incoming data
if(inString == msg){
sevenSeg(0, 1, 1, 0, 1, 1, 1); // 2
delay(500);
}else{
sevenSeg(0, 0, 0, 1, 1, 0, 0); // 1
delay(500);
}
else{
sevenSeg(1, 1, 1, 1, 1, 1, 0); //0
}
All I end up with is displaying 1. Even though I am sending data to the serial monitor. Any help or ideas are greatly appreciated. Thanks.

Passing/printing parameters in Arduino

There is a function RFID that returns *z4 parameter that should be put into TagID.
When I print TagID from loop(), '1' instead of '1B31687DBC7FF' is printed.
How can I get the whole value? I would like to print full string '1B31687DBC7FF' to serial port.
#include "Arduino.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
int inWord = 0;
int outWord[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int index = 0;
unsigned char Data2Calc[]= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
unsigned short CRC2Calc = 0;
unsigned char Bytes2Calc = 9;
char z5 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
const char* TagID;
void setup()
{
pinMode(13, OUTPUT);
lcd.begin(16,2);
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("RFID Reader");
lcd.setCursor(0,1);
lcd.print("Skanuj TAG");
Serial.begin(9600);
Serial1.begin(9600);
lcd.setCursor(0,0);
}
void loop()
{
if (Serial1.available())
{
TagID = RFID();
}
else
{
if (index==11)
{
index=0;
Serial.print(TagID);
Serial.println("");
lcd.setCursor(0,0);
lcd.print("ID:");
lcd.print(TagID);
}
}
}
const char * RFID()
{
char z1 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
char z2 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
char z3 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
unsigned short crc2[] = { 0 };
inWord = Serial1.read();
index++;
if (index == 1)
{
if (inWord == 1)
{
outWord[index] = inWord;
}
else
{
index=index-1;
}
}
else if (index > 1)
{
if (index == 11)
{
outWord[index] = inWord;
for (int i = 1; i <12; i++)
{
Data2Calc[i-1] = outWord[i];
}
CRC16(Data2Calc, &CRC2Calc, Bytes2Calc);
itoa(outWord[10],z1,16);
itoa(outWord[11],z2,16);
strcat(z1, z2);
*crc2 = CRC2Calc;
sprintf(z2, "%x", *crc2); //
if (strcmp(z1,z2) == 0)
{
char z4 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int i=1;i<10;i++)
{
itoa(outWord[i],z3,16);
if (strlen(z3)<2) strcat(z4, "0");
strcat(z4, z3);
//Serial.print(z4);
//Serial.println("");
}
//Serial.print("z4=");
//Serial.print(z4);
//Serial.println("");
strncpy(z5, z4, 18);
}
}
else
{
outWord[index] = inWord;
}
}
return z5;
}
void CRC16(unsigned char * Data, unsigned short * CRC, unsigned char Bytes)
{
int i, byte;
unsigned short C;
*CRC = 0;
for (byte = 1; byte <= Bytes; byte++, Data++)
{
C = ((*CRC >> 8) ^ *Data) << 8;
for (i = 0; i < 8; i++)
{
if (C & 0x8000)
C = (C << 1) ^ 0x1021;
else
C = C << 1;
}
*CRC = C ^ (*CRC << 8);
}
}
Whole output of the functions is attached bellow:
Currently there are no serial ports registered - please use the + button to add a port to the monitor.
Connect to serial port COM4 at 9600
TagID: 1
UPDATE 1
I have attached above full code. Sorry... it is a bit long.
UPDATE 2
OK. I got it somewhat working, but not quite as expected. I got the value printed as expected, but only for the first time I call the function. If I call the function more times, I get some garbage added to the printed value as bellow:
Currently there are no serial ports registered - please use the + button to add a port to the monitor.
Connect to serial port COM4 at 9600
TagID: 1b31596d9cff
TagID: 1b31596d9cff1b31596d9cff
TagID: 1b31596d9cff1Řc–
ś˙cŘ1b31596d9cff
TagID: 1b31596d9cff1Řc–
ś˙cŘ1b311031596d9cff
TagID: 1b31596d9cff1Řc–
ś˙cŘ1b311031596d9cff
Any idea on what the problem might be?
I have updated the latest full source code at the top of the post.
Thanks.
UPDATE 3
OK, I got it finally working. I have changed declaration from 'char z1 []=...' to 'const char z1 []=...'
I am not sure it is written in decent style... but it works :) I attach working source code at the top of the page.
UPDATE 4
No, after a few tests I have to admit that the solution from UPDATE 3 does NOT work. Indeed it reads correctly but only for the first time... then program crashes and... it reads RFID again for the first time... so it looks only it reads OK, but it does not.
Serial output for 5 readings is as follows:
Currently there are no serial ports registered - please use the + button to add a port to the monitor.
Connect to serial port COM4 at 9600
1b31596d9cff
1b31596d9cff1b31596d9cff
1b31596d9cff1Řc–
ś˙cŘ1b31596d9cff
1b31596d9cff1Řc– ś˙cŘ1b311031596d9cff
1b31596d9cff1Řc– ś˙cŘ1b311031596d9cff
Any hints on what is wrong with the code?
UPDATE 5
OK. Finally I got it working... at least from what I can see.
I changed tables size, reworked HEX display way and made a few minor changes.
The entire source code updated at the top.
TagID is a char and your function returns a char. A char is a one byte variable. It will hold at most one character. It shouldn't then surprise you that you only print one character. You haven't provided enough of your code to really figure out what you're actually after. But that explains why you only get one character printed. A char variable can hold one character, not that whole string of stuff.
I'm thinking that you wanted to get a char*, a pointer to a char array. But you're going to have trouble with that too because z4 is a local array and goes out of scope before you get a chance to use it.

netlink_broadcast fail with return value -3

I can't broadcast netlink message to userspace by the following code. However, I can't find anything wrong. My userspace program can recieve broadcast message of other types, for example sock_fd=socket(PF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);, but not my type SYSHOOK_NL_NUM.
I think that bugs hide in my kernel code. Can anyone figure out what's wrong? Thanks.
syshook_nl_sk = netlink_kernel_create(&init_net, SYSHOOK_NL_NUM, 1, NULL, NULL, THIS_MODULE);
skb = alloc_skb(NLMSG_SPACE(nl_send_len), GFP_ATOMIC);
if(!skb) {
error = -ENOMEM;
goto err;
}
nlh = (struct nlmsghdr *)skb->data;
nlh->nlmsg_len = NLMSG_SPACE(nl_send_len);
nlh->nlmsg_pid = 0;
nlh->nlmsg_flags = 0;
nlh = nlmsg_put(skb, 0, 0, 0, NLMSG_SPACE(nl_send_len) - sizeof (struct nlmsghdr), 0);
NETLINK_CB(skb).pid = 0;
NETLINK_CB(skb).dst_group = 1;
error = netlink_broadcast(syshook_nl_sk, skb, 0, 1, GFP_KERNEL);
Userspace code that receive broadcast messages from kernel.
sock_fd=socket(PF_NETLINK, SOCK_RAW, NETLINK_TEST);
// sock_fd=socket(PF_NETLINK, SOCK_RAW, 15);
if(sock_fd < 0) {
printf("create nl failed.\n");
return -1;
}
memset(&src_addr, 0, sizeof(src_addr));
memset(&msg, 0, sizeof(msg));
src_addr.nl_family = AF_NETLINK;
src_addr.nl_pid = 100; /* self pid */
/* interested in group 1<<0 */
src_addr.nl_groups = 1;
// setsockopt(sock_fd, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
bind(sock_fd, (struct sockaddr*)&src_addr, sizeof(src_addr));
memset(&dest_addr, 0, sizeof(dest_addr));
nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
iov.iov_base = (void *)nlh;
iov.iov_len = NLMSG_SPACE(MAX_PAYLOAD);
msg.msg_name = (void *)&dest_addr;
msg.msg_namelen = sizeof(dest_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
char buf[1024] = {0};
printf("begin to recvmsg jiang \n");
int rcvlen;
while (1) {
/* Read message from kernel */
rcvlen = recv(sock_fd, &buf, sizeof(buf), 0);
// rcvlen = recvmsg(sock_fd, &msg, 0);
printf("--%d--%s\n",rcvlen, buf);
}
sudo make it works. Seems the code is OK.

How to wait till all process receive particular data using MPI blocking fucntions?

I am distributing adjacency matrix row by row to the processes using MPI_Send and MPI_Recv functions. I used MPI_Barrier but the program is getting stuck! How do I wait till all the processes get their part of a matrix?
/* Distribute the adjacency matrix */
if( my_rank == 0) {
int row_start_l, row_end_l, dest_l;
for(dest_l=1; dest_l < comm_size; dest_l++) {
row_start_l = dest_l*(num_nodes/comm_size);
if( dest_l != (comm_size - 1) ) {
row_end_l = (dest_l + 1)*(num_nodes/comm_size) - 1;
}
else {
row_end_l = num_nodes - 1;
}
for(i = row_start_l; i <= row_end_l; i++) {
MPI_Send(&g.matrix[i][1], 1, MPI_INT, dest_l, TAG_AM_DATA, MPI_COMM_WORLD);
// Send Adjacency matrix to appropriate destinations. You can first send the appropriate size
MPI_Send(&g.matrix[i], (g.matrix[i][1])+2, MPI_INT, dest_l, TAG_AM_DATA, MPI_COMM_WORLD);
}
}
for(j=0; j < num_nodes; ) {
for(k=0; k < 120; k++) {
if(j >= num_nodes) {
break;
}
sendrecv_buffer_double[k] = g.column_denominator[j];
j++;
}
MPI_Bcast(&k, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&sendrecv_buffer_double[0], k, MPI_DOUBLE, 0, MPI_COMM_WORLD);
} cnt++;
}
else {
int recv_count;
int recvd;
cnt++;
adj_matrix = (int **)malloc(my_num_rows*sizeof(int*));
for(i=0; i < my_num_rows; i++) {
MPI_Recv(&recv_count, 1, MPI_INT, 0, TAG_AM_DATA, MPI_COMM_WORLD, &status);
adj_matrix[i] = (int *)malloc((2 + recv_count)*sizeof(int));
// Receive adjacency matrix from root.
MPI_Recv(&adj_matrix[i], 2+recv_count, MPI_INT, 0, TAG_AM_DATA, MPI_COMM_WORLD, &status);
}
recvd = 0;
while(recvd < num_nodes) {
MPI_Bcast(&recv_count, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(&g.column_denominator[recvd], recv_count, MPI_DOUBLE, 0, MPI_COMM_WORLD);
recvd += recv_count;
}
}
// Wait till all the processes have their assigned parts of the matrix.
MPI_Barrier(MPI_COMM_WORLD);//I am getting error here
Error message:
Process 0 reading the input file.. Number of nodes = 100 Process 0
done reading.. Fatal error in PMPI_Barrier: Message truncated, error
stack: PMPI_Barrier(426)...................:
MPI_Barrier(MPI_COMM_WORLD) failed
MPIR_Barrier_impl(308)..............:
MPIR_Bcast_impl(1369)...............:
MPIR_Bcast_intra(1199)..............:
MPIR_Bcast_binomial(149)............:
MPIC_Recv(109)......................:
MPIDI_CH3U_Request_unpack_uebuf(605): Message truncated; 8 bytes
received but buffer size is 1
I'm not too sure of what your "adjacency matrix" looks like and how is must be distributed, but I guess this is a job for MPI_Scatter() rather than a series of MPI_Bcast()...

Detect change in Arduino potentiometer

I am trying to write my arduino code to upon detection of a change in the potentiometer analog read value to execute a function.
My question is how do I detect a change in the potentiometer value, I am reading in the potentiometer as normally done, but I am stuck as to how to compare this to see if it has changed.
My loop code for reading potentiometer value:
void loop()
{
val = analogRead(potpin);
val = map(val, 0, 1023, 0, 179);
Serial.println(val);
delay(15);
if (val >= 90)
{
sendSMS5();
delay(10000);
switchOff();
}
}
I am thinking that maybe a number of IF statments to compare if the value falls into a certain bracket is the only way to do this.
Save the value in a variable declared outside the loop.
#define TOLERANCE 10
int oldVal = 0;
void loop()
{
val = analogRead(potpin);
val = map(val, 0, 1023, 0, 179);
Serial.println(val);
delay(15);
int diff = abs(val - oldVal);
if(diff > TOLERANCE)
{
oldVal = val; // only save if the val has changed enough to avoid slowly drifting
// and so on
}
if (val >= 90)
{
sendSMS5();
delay(10000);
switchOff();
}
}

Resources