예제 #1
0
    def withdrawRFIDTag(self, user):
        while (self.lock == True):
            if config.DEBUG == False:
                print "still locked (withdrawRFIDTag)"
            time.sleep(0.3)

        try:
            self.lock = True

            time.sleep(0.2)

            print "background-worker withdrawRFIDTag"

            for i in range(0, 4):
                (status,
                 TagType) = RFIDReader.MFRC522_Request(RFIDReader.PICC_REQIDL)
                (status, uid) = RFIDReader.MFRC522_Anticoll()
                if status == RFIDReader.MI_OK:
                    break
                else:
                    print "retry anticoll card (withdrawRFIDTag)"
                    time.sleep(0.3)

            # If we have the UID, continue
            if status == RFIDReader.MI_OK:
                # Print UID
                uid_str = str(uid[0]) + "." + str(uid[1]) + "." + str(
                    uid[2]) + "." + str(uid[3])
                print "Card read UID: " + uid_str

                if (uid_str != user.cardID):
                    print "Wrong cardID detected while withdrawing RFID-tag to user"
                    self.lock = False
                    return False

                # This is the default key for authentication
                defaultkey = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                defaultsecret = [
                    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
                    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
                ]

                userkey = []
                usersecret = []

                userkeyString = user.cardAuthKeyA
                for x in userkeyString.split('-'):
                    userkey.append(int(x, 16))

                print "Userkey: " + str(userkey)

                usersecretString = user.cardSecret
                for x in usersecretString.split('-'):
                    usersecret.append(int(x, 16))

                print "Usersecret: " + str(usersecret)

                SecretBlockAddr = user.cardAuthSector * 4 + user.cardAuthBlock
                TrailerBlockAddr = user.cardAuthSector * 4 + 3

                # Select the scanned tag
                RFIDReader.MFRC522_SelectTag(uid)

                # Authenticate for secret-block
                status = RFIDReader.MFRC522_Auth(RFIDReader.PICC_AUTHENT1A,
                                                 SecretBlockAddr, userkey, uid)

                # write user secret
                if status == RFIDReader.MI_OK:
                    RFIDReader.MFRC522_Write(SecretBlockAddr, defaultsecret)
                else:
                    print "Authentication error while write rfid-tag secret sector"
                    self.lock = False
                    return False

                status = RFIDReader.MFRC522_Auth(RFIDReader.PICC_AUTHENT1A,
                                                 TrailerBlockAddr, userkey,
                                                 uid)

                # Check if authenticated
                if status == RFIDReader.MI_OK:
                    print "Read TrailerBlock :"
                    # Read block 8
                    result = RFIDReader.MFRC522_Read(TrailerBlockAddr)
                    print result

                    for x in range(0, 6):
                        result[x] = 0xFF
                    print result

                    print "Write new trailer:"
                    # Write the data
                    RFIDReader.MFRC522_Write(TrailerBlockAddr, result)
                    print "\n"

                    RFIDReader.MFRC522_StopCrypto1()
                    # unlock and return succesfully
                    self.lock = False
                    return True
                else:
                    print "Authentication error while write rfid-tag key sector"
                    self.lock = False
                    return False
            else:
                print "Authentication error while looking for cards"
                self.lock = False
                return False
        except:
            self.lock = False
            print "unexpected error withdrawRFIDTag"
            raise
예제 #2
0
    def assignRFIDTag(self, user):
        while(self.lock == True):
            print "still locked (assignRFIDTag)"
            time.sleep(0.15)

        self.lock = True

        print "background-worker assign"

        (status,TagType) = RFIDReader.MFRC522_Request(RFIDReader.PICC_REQIDL)

        (status,uid) = RFIDReader.MFRC522_Anticoll()

        # If we have the UID, continue
        if status == RFIDReader.MI_OK:

            # Print UID
            uid_str = str(uid[0])+"." +str(uid[1])+"."+str(uid[2])+"."+str(uid[3])
            print "Card read UID: " + uid_str

            if(uid_str != user.cardID)
                print "Wrong cardID detected while assigning RFID-tag to user"
                return False

            # This is the default key for authentication
            key = []
            secret = []

            # extract keyA from database and print it
            formated_key_list = user.cardAuthKeyA.split()
            for x in formated_key_list:
                key.append(int(x, 16))
            print key

            # extract secret from database and print it
            formated_secret_list = user.cardSecret.split()
            for x in formated_secret_list:
                secret.append(int(x, 16))
            print secret

            # Select the scanned tag
            RFIDReader.MFRC522_SelectTag(uid)

            # Authenticate for auth-sector
            status = RFIDReader.MFRC522_Auth(RFIDReader.PICC_AUTHENT1A, user.cardAuthSector * 4 + user, key, uid)

            # Check if authenticated
            if status == RFIDReader.MI_OK:
                # read trailer from auth-sector
                RFIDReader.MFRC522_Read(user.cardAuthSector * 4 + 3)
                # read auth block in auth-sector
                RFIDReader.MFRC522_Read(user.cardAuthSector * 4 + user.cardAuthBlock)
                # write secret to auth block in auth-sector
                RFIDReader.MFRC522_Write(user.cardAuthSector * 4 + user.cardAuthBlock, secret)
                # read back secret from  auth block in auth-sector
                RFIDReader.MFRC522_Read(user.cardAuthSector * 4 + user.cardAuthBlock)
                RFIDReader.MFRC522_StopCrypto1()
                # unlock and return succesfully
                self.lock = False
                return True
            else:
                print "Authentication error"
                self.lock = False
                return False

        self.lock = False
        return False
예제 #3
0
    def checkRFIDTag(self):

        #if self.first == True:
        #    self.first = False
        #    raise ValueError('A very specific bad thing happened')

        while (self.lock == True):
            print "still locked (checkRFIDTag)"
            time.sleep(0.2)

        try:
            self.lock = True

            (status,
             TagType) = RFIDReader.MFRC522_Request(RFIDReader.PICC_REQIDL)

            for i in range(0, 2):
                (status, uid) = RFIDReader.MFRC522_Anticoll()
                if status == RFIDReader.MI_OK:
                    break
                else:
                    time.sleep(0.2)

            self.resetTagInfo()

            # If we have the UID, continue
            if status == RFIDReader.MI_OK:

                # Print UID
                self.tagInfo.tagId = str(uid[0]) + "." + str(
                    uid[1]) + "." + str(uid[2]) + "." + str(uid[3])
                self.tagInfo.userInfo = ""

                user = User.query.filter_by(cardID=self.tagInfo.tagId).first()

                if user is None:
                    self.ledState = self.LED_STATE_ACCESS_DENIED
                    self.lock = False
                    return

                self.tagInfo.userInfo = user.email
                # print user.email

                # This is the default key for authentication
                defaultkey = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
                userkey = []
                usersecret = []

                userkeyString = user.cardAuthKeyA
                for x in userkeyString.split('-'):
                    userkey.append(int(x, 16))

                # print "Userkey: " + str(userkey)

                usersecretString = user.cardSecret
                for x in usersecretString.split('-'):
                    usersecret.append(int(x, 16))

                # print "Usersecret: " + str(usersecret)

                SecretBlockAddr = user.cardAuthSector * 4 + user.cardAuthBlock
                TrailerBlockAddr = user.cardAuthSector * 4 + 3

                # Select the scanned tag
                RFIDReader.MFRC522_SelectTag(uid)

                # Authenticate
                status = RFIDReader.MFRC522_Auth(RFIDReader.PICC_AUTHENT1A,
                                                 SecretBlockAddr, userkey, uid)

                # Check if authenticated
                if status == RFIDReader.MI_OK:

                    readSecret = RFIDReader.MFRC522_Read(SecretBlockAddr)
                    # print readSecret
                    readSecretString = ''
                    i = 0

                    if not readSecret:
                        print "Read secret string is empty."
                        self.lock = False
                        RFIDReader.MFRC522_StopCrypto1()
                        return False

                    for x in readSecret:
                        if i != 0:
                            readSecretString = readSecretString + '-'
                        i = i + 1
                        readSecretString = readSecretString + format(x, '02X')

                    # print readSecretString

                    if readSecretString == user.cardSecret:
                        print "correct secret"
                        if security.checkUserAccessPrivleges(
                                datetime.datetime.now(),
                                user) == "Access granted.":
                            if datetime.datetime.now(
                            ) > user.lastAccessDateTime + datetime.timedelta(
                                    minutes=config.NODE_LOG_MERGE):
                                user.lastAccessDateTime = datetime.datetime.now(
                                )

                                logentry = Action(
                                    datetime.datetime.utcnow(),
                                    config.NODE_NAME,
                                    user.firstName + ' ' + user.lastName,
                                    user.email, 'Opening request (' + str(1) +
                                    ' attempts)', 'Opening request', 'L2', 1,
                                    'Card based',
                                    Action.ACTION_OPENING_REQUEST, 1)
                                print "Log-entry created"
                                try:
                                    db.session.add(logentry)
                                    db.session.commit()
                                except:
                                    self.ledState = self.LED_STATE_ACCESS_DENIED
                                    db.session.rollback()
                                    raise

                            else:
                                lastlogEntry = Action.query.filter_by(
                                    logType='Opening request',
                                    userMail=user.email).order_by(
                                        Action.date.desc()).first()
                                if lastlogEntry is not None:
                                    if lastlogEntry.synced is 0:
                                        lastlogEntry.date = datetime.datetime.utcnow(
                                        )
                                        lastlogEntry.actionParameter += 1
                                        lastlogEntry.logText = 'Opening request (' + str(
                                            lastlogEntry.actionParameter
                                        ) + ' attempts)'
                                    else:
                                        lastlogEntry.synced = 0
                                        lastlogEntry.date = datetime.datetime.utcnow(
                                        )
                                        lastlogEntry.actionParameter = 1
                                        lastlogEntry.logText = 'Opening request (' + str(
                                            lastlogEntry.actionParameter
                                        ) + ' attempts)'
                                print "Log-entry is in merge-range ts = " + str(
                                    datetime.datetime.now(
                                    )) + " last = " + str(
                                        user.lastAccessDateTime
                                    ) + " merge = " + str(
                                        config.NODE_LOG_MERGE) + " minutes"
                                try:
                                    db.session.commit()
                                except:
                                    self.ledState = self.LED_STATE_ACCESS_DENIED
                                    db.session.rollback()
                                    raise

                            self.requestOpening = True
                            self.ledState = self.LED_STATE_ACCESS_GRANTED
                        else:
                            self.ledState = self.LED_STATE_ACCESS_DENIED
                            print "no user-access privilege"
                    else:
                        self.tagInfo.userInfo = user.email + '(inv. sec.)'
                        print "no user-access privilege"
                        self.ledState = self.LED_STATE_ACCESS_DENIED

                    RFIDReader.MFRC522_StopCrypto1()
                    self.lock = False
                    return True
                else:
                    self.tagInfo.userInfo = user.email + '(inv. key.)'
                    print "Authentication error"
                    self.ledState = self.LED_STATE_ACCESS_DENIED
                    self.lock = False
                    return False
            else:
                self.lock = False
                return False
        except:
            self.lock = False
            print "unexpected error in checkRFIDTag"
            self.ledState = self.LED_STATE_ACCESS_DENIED
            raise