Source code for linotp.lib.tokenclass

# -*- coding: utf-8 -*-
'''

  product:  LinOTP2
  module:   linotpd
  edition:  Community Edition
  
  Copyright (C) 2010 - 2013 LSE Leading Security Experts GmbH
  License:  AGPLv3
  contact:  http://www.linotp.org
            http://www.lsexperts.de
            linotp@lsexperts.de

  Description:  This file containes the standard token definitions:
              - HmacTokenClas   (HOTP)
              - MotpTokenClass
              - PasswordTokenClass
              - RadiusTokenClass
              - RemoteTokenClass
              - SmsTokenClass
              - SpassTokenClass
              - TagespasswortTokenClass
              - TimeHmacTokenClass  (TOTP)
              - VascoTokenClass
              
              It also contains the base class "TokenClass", that you may use to 
              define your own tokenclasses.
              
              You can add your own Tokens by adding the modules comma seperated to the directive
                  linotpTokenModules
              in the linotp.ini file.
                 
  Dependencies: depends on several modules from linotp.lib but also in case of VascoTokenClass on 
              linotpee.lib.ImportOTP.vasco
  

'''
import re
import binascii
import random
import logging
import time
import math
import hashlib
import pickle
import datetime

import traceback


from linotp.lib.HMAC    import HmacOtp
from linotp.lib.error   import TokenAdminError
from linotp.lib.util    import getParam
from linotp.lib.config  import getFromConfig
from linotp.lib.user    import getUserResolverId 
from linotp.lib.mOTP    import mTimeOtp

from linotp.lib.dpwOTP  import dpwOtp
from linotp.lib.crypt   import decryptPin, encryptPin
from linotp.lib.crypt   import kdf2

from linotp.lib.crypt   import createNonce
from linotp.lib.crypt   import zerome
from linotp.lib.policy  import get_qrtan_url 


from linotp.lib.ocra    import OcraSuite
from linotp.model       import OcraChallenge

from linotp.model.meta  import Session

from sqlalchemy         import asc,desc


from linotp.lib.selftest import isSelfTest

# We need this for the remote token
import urllib, urllib2
from   simplejson import load

# we need this for the radius token
import pyrad.packet
from pyrad.client import Client
from pyrad.dictionary import Dictionary
from pylons.configuration import config as env 


try:
    from smsprovider.SMSProvider import getSMSProviderClass
    ## sms = getSMSProviderClass("SMSProvider", "ISMSProvider")
    EDITION="EE"
except ImportError:
    EDITION="CE"

try:
    from linotpee.lib.ImportOTP.vasco import vasco_otp_check
    VASCO = True
except ImportError:
    VASCO = False



import sys
if sys.version_info[0:2] >= (2,6):
    from json import loads, dumps
else:
    from simplejson import loads, dumps


optional = True
required = False



log = logging.getLogger(__name__)



[docs]class TokenClass(object): def __init__(self,token): self.token = token def setType(self,typ): typ = u'' + typ self.type = typ self.token.setType(typ) @classmethod def getClassType(cls): return None def getType(self): return self.type
[docs] def getInfo(self): return {}
[docs] def checkOtp(self, anOtpVal,counter,window,initTime="" , options=None): ''' This checks the OTP value, AFTER the upper level did the checkPIN return: counter of the matching OTP value. ''' return -1
[docs] def getOtp(self, curtTime=""): ''' The default token does not support getting the otp value will return something like: 1, pin, otpval, combined a negative value is a failure. ''' return (-2, 0,0,0 )
[docs] def get_multi_otp(self,count=0, epoch_start=0, epoch_end=0, curTime=None): ''' This returns a dictionary of multiple future OTP values of a token. parameter count - how many otp values should be returned epoch_start - time based tokens: start when epoch_end - time based tokens: stop when return True/False error text OTP dictionary ''' return (False,"get_multi_otp not implemented for this tokentype", {})
def update(self,param,reset_failcount=True): tdesc = getParam(param,"description",optional) if tdesc != None: self.token.setDescription(tdesc) otpKey = getParam(param,"otpkey",optional) if otpKey != None: self.token.setHKey(otpKey,reset_failcount=reset_failcount) pin = getParam(param,"pin",optional) if pin != None: storeHashed = True enc = getParam(param,"encryptpin",optional) if enc != None and "true" == enc.lower(): storeHashed = False self.token.setPin(pin,storeHashed) def setDescription(self,description): self.token.setDescription(u'' + description)
[docs] def setUser(self, user,report): ''' param: a User() object, consisting of loginname and realm ''' (uuserid,uidResolver,uidResolverClass) = getUserResolverId(user,report) self.token.LinOtpIdResolver = uidResolver self.token.LinOtpIdResClass = uidResolverClass self.token.LinOtpUserid = uuserid
def getUser(self): uidResolver = self.token.LinOtpIdResolver uidResolverClass = self.token.LinOtpIdResClass uuserid = self.token.LinOtpUserid return (uuserid,uidResolver,uidResolverClass)
[docs] def setUid(self, uid, uidResolver, uidResClass): ''' sets the UID values in the database ''' self.token.LinOtpIdResolver = uidResolver self.token.LinOtpIdResClass = uidResClass self.token.LinOtpUserid = uid
def reset(self): self.token.LinOtpFailCount = 0 def addToSession(self,Session): Session.add(self.token) def deletFromSession(self,Session): Session.delete(self.token) def storeToken(self): self.token.storeToken() def resync(self,otp1,otp2, options=None): pass def getOtpCountWindow(self): return self.token.LinOtpCountWindow def getOtpCount(self): return self.token.LinOtpCount def isActive(self): return self.token.LinOtpIsactive def getFailCount(self): return self.token.LinOtpFailCount def setFailCount(self,failCount): self.token.LinOtpFailCount = failCount def getMaxFailCount(self): return self.token.LinOtpMaxFail def getUserId(self): return self.token.LinOtpUserid def setRealms(self,realms): self.token.setRealms(realms) def getSerial(self): return self.token.getSerial() def setSoPin(self,soPin): self.token.setSoPin(soPin) def setUserPin(self,userPin): self.token.setUserPin(userPin) def setOtpKey(self,otpKey): self.token.setHKey(otpKey) def setOtpLen(self,otplen): self.token.LinOtpOtpLen = int(otplen) def setOtpCount(self,otpCount): self.token.LinOtpCount = int(otpCount)
[docs] def setPin(self,pin, param={}): ''' set the PIN. The optional parameter "param" can hold the information, if the PIN is encrypted or hashed. ''' storeHashed = True enc = getParam(param,"encryptpin",optional) if enc != None and "true" == enc.lower(): storeHashed = False self.token.setPin(pin, storeHashed)
def getPinHashSeed(self): return self.token.LinOtpPinHash, self.token.LinOtpSeed def setPinHashSeed(self, pinhash, seed): self.token.LinOtpPinHash = pinhash self.token.LinOtpSeed = seed def enable(self,enable): self.token.LinOtpIsactive = enable def setMaxFail(self,maxFail): self.token.LinOtpMaxFail = maxFail def setHashLib(self,hashlib): self.addToTokenInfo("hashlib", hashlib) def incOtpFailCounter(self): log.debug('incOtpFailCounter') if self.token.LinOtpFailCount < self.token.LinOtpMaxFail: self.token.LinOtpFailCount = self.token.LinOtpFailCount + 1 try: self.token.storeToken() except: log.error('update failed') raise TokenAdminError(1106, "Token Fail Counter update failed") return self.token.LinOtpFailCount ### TODO: - this is only HMAC?? def setCounterWindow(self,countWindow): self.token.LinOtpCountWindow = int(countWindow) def getCounterWindow(self): return self.token.LinOtpCountWindow def setSyncWindow(self,syncWindow): self.token.LinOtpSyncWindow = int(syncWindow) def getSyncWindow(self): return self.token.LinOtpSyncWindow """ hashlib algorithms: http://www.doughellmann.com/PyMOTW/hashlib/index.html#module-hashlib """ def getHashlib(self,hLibStr): if None == hLibStr: return hashlib.sha1 hashlibStr = hLibStr.lower() if hashlibStr == "md5": return hashlib.md5 elif hashlibStr == "sha1": return hashlib.sha1 elif hashlibStr == "sha224": return hashlib.sha224 elif hashlibStr == "sha256": return hashlib.sha256 elif hashlibStr == "sha384": return hashlib.sha384 elif hashlibStr == "sha512": return hashlib.sha512 else: return hashlib.sha1 def getTokenInfo(self): info = {} tokeninfo = self.token.getInfo() try: info = loads(tokeninfo) except Exception, e: log.error('getTokenInfo %s', str(e)) return info def setTokenInfo(self,info): if info != None: tokeninfo = u'' + dumps(info,indent=0) self.token.setInfo(tokeninfo) def addToTokenInfo(self,key,value): info = {} tokeninfo = self.token.getInfo() if tokeninfo != None: if len(tokeninfo) > 0 : info = loads(tokeninfo) #if info.has_key(key) == True: info[key]=value self.setTokenInfo(info) def getFromTokenInfo(self,key, default = None): ret = default info = self.getTokenInfo() if info.has_key(key) == True: ret = info.get(key) return ret # FIXME: we could store the # count_auth_success_max # count_auth_success # and # count_auth_max # count_auth # in dedicated columns!
[docs] def set_count_auth_success_max(self,count): ''' Sets the counter for the maximum allowed successfull logins ''' self.addToTokenInfo("count_auth_success_max", int(count))
[docs] def set_count_auth_success(self,count): ''' Sets the counter for the occurred successfull logins ''' self.addToTokenInfo("count_auth_success", int(count))
[docs] def set_count_auth_max(self,count): ''' Sets the counter for the maximum allowed login attemps ''' self.addToTokenInfo("count_auth_max", int(count))
[docs] def set_count_auth(self,count): ''' Sets the counter for the occurred login attepms ''' self.addToTokenInfo("count_auth", int(count))
def get_count_auth_success_max(self): ret = 0 try: ret = int(self.getFromTokenInfo("count_auth_success_max")) except: pass return ret def get_count_auth_success(self): ret = 0 try: ret=int(self.getFromTokenInfo("count_auth_success")) except: pass return ret def get_count_auth_max(self): ret = 0 try: ret=int(self.getFromTokenInfo("count_auth_max")) except: pass return ret def get_count_auth(self): ret = 0 try: ret=int(self.getFromTokenInfo("count_auth")) except: pass return ret
[docs] def get_validity_period_end(self): ''' returns the end of validity period (if set) ''' ret = "" try: ret = self.getFromTokenInfo("validity_period_end") except: pass return ret
[docs] def set_validity_period_end(self, end_date): ''' sets the end date of the validity period for a token ''' '''' upper layer will catch. we just try to verify the date format ''' datetime.datetime.strptime(end_date, "%d/%m/%y %H:%M") self.addToTokenInfo("validity_period_end", end_date)
[docs] def get_validity_period_start(self): ''' returns the start of validity period (if set) ''' ret = "" try: ret = self.getFromTokenInfo("validity_period_start") except: pass return ret
[docs] def set_validity_period_start(self, start_date): ''' sets the start date of the validity period for a token ''' ''' upper layer will catch. we just try to verify the date format ''' datetime.datetime.strptime(start_date, "%d/%m/%y %H:%M") self.addToTokenInfo("validity_period_start", start_date)
def inc_count_auth_success(self): count = self.get_count_auth_success() count += 1 self.set_count_auth_success(count) return count def inc_count_auth(self): count = self.get_count_auth() count += 1 self.set_count_auth(count) return count
[docs] def check_auth_counter(self): ''' This function checks the count_auth and the count_auth_success ''' if 0 != self.get_count_auth_max(): if self.get_count_auth() >= self.get_count_auth_max(): return False if 0 != self.get_count_auth_success_max(): if self.get_count_auth_success() >= self.get_count_auth_success_max(): return False return True
[docs] def check_validity_period(self): ''' This checks if the datetime.datetime.now() is within the validity period of the token. Returns either True/False ''' start = self.get_validity_period_start() end = self.get_validity_period_end() check_start = False check_end = False try: dt_start = datetime.datetime.strptime(start, "%d/%m/%y %H:%M") check_start = True except: pass try: dt_end = datetime.datetime.strptime(end, "%d/%m/%y %H:%M") check_end = True except: pass if check_end: if dt_end < datetime.datetime.now(): return False if check_start: if dt_start > datetime.datetime.now(): return False return True
[docs] def incOtpCounter(self,counter, reset = True): """ method incOtpCounter(aToken, counter) parameters: token - a token object counter - the new counter reset - optional - exception: in case of an transaction fail an exception is thrown side effects: default of reset will reset the failCounter """ log.debug('incOtpCounter') resetCounter = False #CKO, FIX: in case of SMS Token, we always get a counter==0 ??? #if 0 == counter: # counter = self.token.LinOtpCount log.debug("[incOtpCounter] got counter %s, %s" % (self.token.LinOtpCount, counter)) self.token.LinOtpCount = counter + 1 if reset == True: if getFromConfig("DefaultResetFailCount") == "True" : resetCounter = True #log.error("Serial %s: LinOtpFailCount %d < LinOtpMaxFail %d",token.LinOtpTokenSerialnumber, token.LinOtpFailCount,token.LinOtpMaxFail) if resetCounter == True: if self.token.LinOtpFailCount < self.token.LinOtpMaxFail and self.token.LinOtpIsactive == True: self.token.LinOtpFailCount = 0; try: self.token.storeToken() except Exception,e : log.error("Token Counter update failed: %s" % str(e)) raise TokenAdminError(1106, "Token Counter update failed: " + str(e)) log.debug("[incOtpCounter] now got counter %s, %s" % (self.token.LinOtpCount, counter)) return self.token.LinOtpCount
[docs] def checkPass(self,passw): ''' This function is called to ONLY check the OTP PIN of the token ''' return False
[docs] def check_otp_exist(self, otp, range=None ): ''' checks if the given OTP value is/are values of this very token. This is used to autoassign and to determine the serial number of a token. ''' return -1
def splitPinPass(self, passw): res = 0 try: otplen = int(self.token.LinOtpOtpLen) except ValueError: otplen = 6 if getFromConfig("PrependPin") == "True" : pin = passw[0:-otplen] otpval = passw[-otplen:] else: pin = passw[otplen:] otpval = passw[0:otplen] #log.error("Pin: %s, otpval:%s",pin,otpval) return (res,pin,otpval) def checkPin(self, passw): log.debug("[checkPin] entering checkPin function") (res,pin,otpval) = self.splitPinPass(passw) # TODO CKO: remove the logging of the pin and otpval #log.debug("[checkPin] splitted the PIN: res: %s, pin: %s, otpval: %s" % (str(res),pin,otpval)) if self.token.comparePin(pin) == False: res = -2 return (res,pin,otpval)
[docs] def statusValidationFail(self): ''' callback to enable a status change, if auth failed''' return
[docs] def statusValidationSuccess(self): ''' callback to enable a status change, if auth failed''' return ###############################################
class HmacTokenClass(TokenClass): def __init__(self,aToken): TokenClass.__init__(self,aToken) self.setType(u"HMAC") self.hKeyRequired = True # we support various hashlib methods, but only on create # which is effectivly set in the update try: self.hashlibStr = getFromConfig("hotp.hashlib") except: self.hashlibStr = u"sha1" if self.hashlibStr == None: self.hashlibStr = u"sha1" @classmethod def getClassType(cls): return "hmac" def update(self,param): ## check for the required parameters if (self.hKeyRequired == True): getParam(param,"otpkey",required) val = getParam(param,"hashlib",optional) if val != None: self.hashlibStr = val TokenClass.update(self,param) self.addToTokenInfo("hashlib", self.hashlibStr) def reset(self): TokenClass.reset(self) def checkOtp(self, anOtpVal,counter,window, initTime="", options=None ): res = -1 try: otplen = int(self.token.LinOtpOtpLen) except ValueError: return res try: self.hashlibStr = self.getFromTokenInfo("hashlib") except: self.hashlibStr = "sha1" secretHOtp = self.token.getHOtpKey() #serialNum = self.token.LinOtpTokenSerialnumber #log.debug("serial: %s",serialNum) hmac2Otp = HmacOtp(secretHOtp, counter, otplen,self.getHashlib(self.hashlibStr)) res = hmac2Otp.checkOtp(anOtpVal, window) if -1 == res: res = self.autosync(hmac2Otp,anOtpVal) return res def check_otp_exist( self, otp, range=10 ): ''' checks if the given OTP value is/are values of this very token. This is used to autoassign and to determine the serial number of a token. ''' res = -1 try: otplen = int(self.token.LinOtpOtpLen) counter = int(self.token.LinOtpCount) except ValueError: return res try: self.hashlibStr = self.getFromTokenInfo("hashlib") except: self.hashlibStr = "sha1" secretHOtp = self.token.getHOtpKey() hmac2Otp = HmacOtp(secretHOtp, counter, otplen, self.getHashlib(self.hashlibStr)) res = hmac2Otp.checkOtp(otp, range) if res >= 0: # As usually the counter is increased in lib.token.checkUserPass, we # need to do this manually here: self.incOtpCounter(res) return res def autosync(self, hmac2Otp, anOtpVal): res = -1 autosync = False ## is autosync derfined ? try: async = getFromConfig("AutoResync") if async == None: autosync = False elif "true" == async.lower(): autosync = True elif "false" == async.lower(): autosync = False except Exception, e: log.error('autosync check failed %s', str(e)) return res ## if autosync is enabled if False == autosync: return res info = self.getTokenInfo(); syncWindow = self.getSyncWindow() #check if the otpval is valid in the sync scope res = hmac2Otp.checkOtp(anOtpVal, syncWindow) #if yes: if res != -1: # if former is defined if (info.has_key("otp1c")): #check if this is consecutive otp1c = info.get("otp1c"); otp2c = res if (otp1c + 1) != otp2c: res = -1 if info.has_key("dueDate"): dueDate = info.get("dueDate") now = int(time.time()) if dueDate <= now: res = -1 else: res = -1 ## now clean the resync data del info["dueDate"] del info["otp1c"] self.setTokenInfo(info) else: info["otp1c"]=res info["dueDate"]=int(time.time()) + self.getSyncTimeOut() self.setTokenInfo(info) res = -1 return res; def resync(self,otp1,otp2, options=None): ret = False try: otplen = int(self.token.LinOtpOtpLen) except ValueError: return ret try: self.hashlibStr = self.getFromTokenInfo("hashlib") except: self.hashlibStr = "sha1" secretHOtp = self.token.getHOtpKey() counter = self.token.getOtpCounter() syncWindow = self.token.getSyncWindow() #log.debug("serial: %s",serialNum) hmac2Otp = HmacOtp(secretHOtp, counter, otplen, self.getHashlib(self.hashlibStr)) counter = hmac2Otp.checkOtp(otp1,syncWindow) if counter == -1: return ret nextOtp = hmac2Otp.generate(counter+1) if nextOtp != otp2: return ret ret = True self.incOtpCounter(counter+1, True) return ret def getSyncTimeOut(self): try: timeOut = int(getFromConfig("AutoResyncTimeout")) except: log.debug("AutoResyncTimeout: value error - reset to 5*60") timeOut = 5 * 60 return timeOut def getOtp(self, curTime=None): ''' return the next OTP value ''' res = (-1,0,0,0) try: otplen = int(self.token.LinOtpOtpLen) except ValueError: return res try: self.hashlibStr = self.getFromTokenInfo("hashlib") except: self.hashlibStr = "sha1" secretHOtp = self.token.getHOtpKey() hmac2Otp = HmacOtp(secretHOtp, self.getOtpCount(), otplen,self.getHashlib(self.hashlibStr)) otpval = hmac2Otp.generate(inc_counter=False) pin = self.token.getPin() combined = "%s%s" % (otpval,pin) if getFromConfig("PrependPin") == "True" : combined = "%s%s" % (pin,otpval) return ( 1, pin, otpval, combined ) def get_multi_otp(self,count=0, epoch_start=0, epoch_end=0, curTime=None): ''' This returns a dictionary of multiple future OTP values of the HOTP/HMAC token parameter count - how many otp values should be returned return True/False error text OTP dictionary ''' otp_dict={"type" : "HMAC", "otp": {}} ret = False error = "No count specified" try: otplen = int(self.token.LinOtpOtpLen) except ValueError, e: log.error("[get_multi_otp] %s" % str(e)) return (False, str(e), otp_dict) secretHOtp = self.token.getHOtpKey() hmac2Otp = HmacOtp(secretHOtp, self.getOtpCount(), otplen,self.getHashlib(self.hashlibStr)) log.debug("[get_multi_otp] retrieving %i OTP values for token %s" % (count, hmac2Otp)) if count>0: for i in range(count): otpval = hmac2Otp.generate(self.getOtpCount()+i,inc_counter=False) otp_dict["otp"][i] = otpval ret = True log.debug("[get_multi_otp] %s" % otp_dict) return (ret,error, otp_dict) ############################################### """ TOTP Algorithm This variant of the HOTP algorithm specifies the calculation of a one-time password value, based on a representation of the counter as a time factor. 4.1. Notations - X represents the time step in seconds (default value X = 30 seconds) and is a system parameter; - T0 is the Unix time to start counting time steps (default value is 0, Unix epoch) and is also a system parameter. 4.2. Description Basically, we define TOTP as TOTP = HOTP(K, T) where T is an integer and represents the number of time steps between the initial counter time T0 and the current Unix time (i.e. the number of seconds elapsed since midnight UTC of January 1, 1970). More specifically T = (Current Unix time - T0) / X where: - X represents the time step in seconds (default value X = 30 seconds) and is a system parameter; - T0 is the Unix time to start counting time steps (default value is 0, Unix epoch) and is also a system parameter; - The default floor function is used in the computation. For example, with T0 = 0 and time step X = 30, T = 1 if the current Unix time is 59 seconds and T = 2 if the current Unix time is 60 seconds. M'Raihi, et al. Expires March 12, 2011 [Page 5] Internet-Draft HOTPTimeBased September 2010 """ ############################################### class TimeHmacTokenClass(TokenClass): resyncDiffLimit = 3 def __init__(self,aToken): TokenClass.__init__(self,aToken) self.setType(u"TOTP") self.hKeyRequired = True ''' timeStep defines the granularity: ''' self.timeStep = getFromConfig("totp.timeStep",30) ''' window size in seconds: 30 seconds with as step width of 30 seconds results in a window of 1 which is one attempt ''' self.timeWindow = getFromConfig("totp.timeWindow",180) '''the time shift is specified in seconds - and could be positive and negative ''' self.timeShift = getFromConfig("totp.timeShift",0) '''we support various hashlib methods, but only on create which is effectivly set in the update ''' self.hashlibStr = getFromConfig("totp.hashlib",u'sha1') @classmethod def getClassType(cls): return "totp" def update(self,param): ## check for the required parameters if (self.hKeyRequired == True): getParam(param,"otpkey",required) val = getParam(param,"otplen", optional) if val != None: self.setOtpLen(int(val)) else: self.setOtpLen(getFromConfig("DefaultOtpLen")) val = getParam(param,"timeStep",optional) if val != None: self.timeStep = val val = getParam(param,"timeWindow",optional) if val != None: self.timeWindow = val val = getParam(param,"timeShift",optional) if val != None: self.timeShift = val val = getParam(param,"hashlib",optional) if val != None: self.hashlibStr = val TokenClass.update(self,param) self.addToTokenInfo("timeWindow", self.timeWindow) self.addToTokenInfo("timeShift",self.timeShift) self.addToTokenInfo("timeStep", self.timeStep) #TODO check key len if SHA256 or SHA512 self.addToTokenInfo("hashlib", self.hashlibStr) def reset(self): TokenClass.reset(self) def check_otp_exist( self, otp, range=10 ): ''' checks if the given OTP value is/are values of this very token. This is used to autoassign and to determine the serial number of a token. ''' res = -1 try: counter = int(self.token.LinOtpCount) except ValueError: return res res = self.checkOtp(otp,counter,range) return res def checkOtp(self, anOtpVal, counter, window, initTime="", options=None): ''' check the time based otp value @param anOtpVal: the to be checked otp value @type anOtpVal: string @param counter: the otp counter @type counter: int @param window: test range, which should be added around the counter @type window: int @param initTime: the timestamp, which is used in the base tests (legacy - will be removed) @type initTime: int - seconds unix time @param options: additional parameters, which could be token specific @type options: dict @return: result value - otp counter or -1# @rtype: int ''' res = -1 rnd = 1 try: otplen = int(self.token.LinOtpOtpLen) except ValueError,e: raise e secretHOtp = self.token.getHOtpKey() self.hashlibStr = self.getFromTokenInfo("hashlib", self.hashlibStr) timeStepping = int( self.getFromTokenInfo("timeStep", self.timeStep) ) window = int( self.getFromTokenInfo("timeWindow", self.timeWindow) ) shift = int( self.getFromTokenInfo("timeShift", self.timeShift) ) ''' oldCounter we have to remove one, as the normal otp handling will increment ''' oCount = self.getOtpCount() - 1 if oCount < 0: oCount = 0 log.debug("[checkOTP] timestep: %i, timeWindow: %i, timeShift: %i" % (timeStepping, window, shift)) now = time.time() inow = int(time.time()) T0 = time.time() + shift if initTime != "": T0 = int(initTime) counter = int(T0 / timeStepping) + rnd log.debug("[checkOTP] T0 : %i" % T0) otime = self._getTimeFromCounter(oCount, timeStepping=timeStepping) ttime = self._getTimeFromCounter(counter, timeStepping=timeStepping) ntime = datetime.datetime.now() log.debug("[checkOTP] last log: %s :: %s" % (str(oCount), str(otime)) ) log.debug("[checkOTP] counter : %s :: %s <==> %s" % (str(counter), str(ttime), str(datetime.datetime.now())) ) log.debug("[checkOTP] shift : %s " % (str(shift))) hmac2Otp = HmacOtp(secretHOtp, counter, otplen, self.getHashlib(self.hashlibStr)) res = hmac2Otp.checkOtp(anOtpVal, int (window / timeStepping ), symetric=True ) log.debug("[checkOTP] comparing the result %i to the old counter %i." % (res, oCount)) if res <= oCount: if initTime == "": log.warning("[checkOTP] a previous OTP value was used again! tokencounter: %i, presented counter %i" % ( oCount, res)) res = -1 return res if -1 == res : ''' autosync: test if two consecutive otps have been provided ''' res = self.autosync(hmac2Otp, anOtpVal) if res != -1: ''' on success, we have to save the last attempt ''' self.setOtpCount(counter) ''' # here we calculate the new drift/shift between the server time and the tokentime ''' tokentime = int(res - rnd) * timeStepping tokenDt = datetime.datetime.fromtimestamp(tokentime / 1.0) nowDt = datetime.datetime.fromtimestamp(inow / 1.0) lastauth = int(oCount - rnd) * timeStepping lastauthDt = datetime.datetime.fromtimestamp(lastauth / 1.0) log.debug("[checkOTP] last auth : %s" % (str(lastauthDt)) ) log.debug("[checkOTP] tokentime : %s" % (str(tokenDt)) ) log.debug("[checkOTP] now : %s" % (str(nowDt)) ) log.debug("[checkOTP] delta : %s" % (str(tokentime - inow)) ) new_shift = (tokentime - inow) log.debug("[checkOTP] the counter %s matched. New shift: %s" % (str(res),str(new_shift) )) self.addToTokenInfo('timeShift', new_shift) return res def _getTimeFromCounter(self, counter, timeStepping=30, rnd=1): idate = int(counter - rnd) * timeStepping ddate = datetime.datetime.fromtimestamp(idate / 1.0) return ddate def autosync(self, hmac2Otp, anOtpVal): ''' autosync of totp will set the shift value in case of two consecutive values in the sync window are provided @param hmac2Otp: hmach object, to generate the next otp value @type hmac2Otp: hmac obejct @param anOtpVal: the otpVal in request @type anOtpVal: string ''' res = -1 autosync = False try: async = getFromConfig("AutoResync") if async == None: autosync = False elif "true" == async.lower(): autosync = True elif "false" == async.lower(): autosync = False except Exception, e: log.error('autosync check failed %s', str(e)) return res ' if autosync is not enabled: do nothing ' if False == autosync: return res info = self.getTokenInfo(); syncWindow = self.getSyncWindow() #check if the otpval is valid in the sync scope res = hmac2Otp.checkOtp(anOtpVal, syncWindow, symetric = True) log.debug("[autosync] found otpval %s in syncwindow (%s): %s" % (str(anOtpVal), str(syncWindow), str(res) )) #if yes: if res != -1: # if former is defined if (info.has_key("otp1c")): #check if this is consecutive otp1c = info.get("otp1c"); otp2c = res log.debug("[autosync] otp1c: %s, otp2c: %s" % (str(otp1c),str(otp2c))) diff = math.fabs(otp2c - otp1c) if ( diff > self.resyncDiffLimit ): res = -1 else: T0 = time.time() timeStepping = int( self.getFromTokenInfo("timeStep") ) counter = int((T0 / timeStepping) + 0.5) shift = otp2c - counter info["timeShift"] = shift self.setTokenInfo(info) ## now clean the resync data del info["otp1c"] self.setTokenInfo(info) else: log.debug("[autosync] setting otp1c: %s" % res) info["otp1c"] = res self.setTokenInfo(info) res = -1 return res def resync(self,otp1,otp2, options=None): ret = False try: otplen = int(self.token.LinOtpOtpLen) except ValueError: return ret secretHOtp = self.token.getHOtpKey() try: self.hashlibStr = self.getFromTokenInfo("hashlib") except: self.hashlibStr = "sha1" try: timeStepping = int( self.getFromTokenInfo("timeStep") ) except: timeStepping = 30 try: window = int( self.token.LinOtpSyncWindow ) * timeStepping except: window = 10 * timeStepping try: shift = int( self.getFromTokenInfo("timeShift") ) except: pass shift = 0 log.debug("[resync] timestep: %i, syncWindow: %i, timeShift: %i" % (timeStepping, window, shift)) T0 = time.time() - shift log.debug("[resync] T0 : %i" % T0) counter = int((T0 / timeStepping)+0.5) # T = (Current Unix time - T0) / timeStepping log.debug("[resync] counter (current time): %i" % counter) oCount = self.getOtpCount() log.debug("[resync] tokenCounter: %s" % str(oCount)) log.debug("[resync] now checking window %s, timeStepping %s" %(window, timeStepping) ) # check 2nd value hmac2Otp = HmacOtp(secretHOtp, counter, otplen, self.getHashlib(self.hashlibStr)) log.debug("[resync] %s in otpkey: %s "% (otp2, secretHOtp)) res2 = hmac2Otp.checkOtp(otp2, int (window / timeStepping ), symetric=True ) #TEST -remove the 10 log.debug("[resync] res 2: %s" % str(res2)) # check 1st value hmac2Otp = HmacOtp(secretHOtp, counter-1, otplen, self.getHashlib(self.hashlibStr)) log.debug("[resync] %s in otpkey: %s "% (otp1, secretHOtp)) res1 = hmac2Otp.checkOtp(otp1, int (window / timeStepping ), symetric=True ) #TEST -remove the 10 log.debug("[resync] res 1: %s" % str(res1)) if res1 < oCount: if initTime == "": # A previous OTP value was used again! log.warning("[resync] a previous OTP value was used again! tokencounter: %i, presented counter %i" % ( oCount, res1)) res1 = -1 if res1 != -1 and res1+1 == res2: # here we calculate the new drift/shift between the server time and the tokentime tokentime = (res2 + 0.5) * timeStepping currenttime = T0 + shift new_shift = (tokentime - currenttime) log.debug("[resync] the counters %s and %s matched. New shift: %s" % (str(res1),str(res2),str(new_shift) )) self.addToTokenInfo('timeShift', new_shift) self.setOtpCount(res2) ret = True return ret def getSyncTimeOut(self): try: timeOut = int(getFromConfig("AutoResyncTimeout")) except: log.debug("AutoResyncTimeout: value error - reset to 5*60") timeOut = 5 * 60 return timeOut def getOtp(self, curTime=None): ''' Returns an OTP value of the TOTP token ''' res = (-1,0,0,0) try: otplen = int(self.token.LinOtpOtpLen) except ValueError: return res secretHOtp = self.token.getHOtpKey() try: self.hashlibStr = self.getFromTokenInfo("hashlib") except: self.hashlibStr = "sha1" try: timeStepping = int( self.getFromTokenInfo("timeStep") ) except: timeStepping = 30 try: shift = int( self.getFromTokenInfo("timeShift") ) except: shift = 0 hmac2Otp = HmacOtp(secretHOtp, self.getOtpCount(), otplen, self.getHashlib(self.hashlibStr)) tCounter=int(datetime.datetime.now().strftime("%s")) if curTime: if type(curTime)==datetime.datetime: tCounter = int(curTime.strftime("%s")) elif type(curTime)==unicode: tCounter = int(datetime.datetime.strptime("2012-05-16 09:00:52.227413","%Y-%m-%d %H:%M:%S.%f").strftime("%s")) else: log.error("[getOtp] invalid curTime: %s. You need to specify a datetime.datetime" % type(curTime)) counter = int(((tCounter-shift) / timeStepping)+0.5) otpval = hmac2Otp.generate(counter=counter, inc_counter=False) pin = self.token.getPin() combined = "%s%s" % (otpval,pin) if getFromConfig("PrependPin") == "True" : combined = "%s%s" % (pin,otpval) return ( 1, pin, otpval, combined ) def get_multi_otp(self,count=0, epoch_start=0, epoch_end=0, curTime=None): ''' This returns a dictionary of multiple future OTP values of the Tagespasswort token parameter count - how many otp values should be returned epoch_start - time based tokens: start when epoch_end - time based tokens: stop when return True/False error text OTP dictionary ''' otp_dict={"type" : "TOTP", "otp": {}} ret = False error = "No count specified" try: otplen = int(self.token.LinOtpOtpLen) except ValueError: return ret secretHOtp = self.token.getHOtpKey() try: self.hashlibStr = self.getFromTokenInfo("hashlib") except: self.hashlibStr = "sha1" try: timeStepping = int( self.getFromTokenInfo("timeStep") ) except: timeStepping = 30 try: shift = int( self.getFromTokenInfo("timeShift") ) except: shift = 0 hmac2Otp = HmacOtp(secretHOtp, self.getOtpCount(), otplen, self.getHashlib(self.hashlibStr)) tCounter=int(datetime.datetime.now().strftime("%s")) if curTime: if type(curTime)==datetime.datetime: tCounter = int(curTime.strftime("%s")) elif type(curTime)==unicode: tCounter = int(datetime.datetime.strptime("2012-05-16 09:00:52.227413","%Y-%m-%d %H:%M:%S.%f").strftime("%s")) else: log.error("[getOtp] invalid curTime: %s. You need to specify a datetime.datetime" % type(curTime)) raise TokenAdminError(2001, "[get_multi_otp] wrong curTime type: %s (%s)" % (type(curTime),curTime)) counter = int(((tCounter-shift) / timeStepping)+0.5) otp_dict["shift"] = shift otp_dict["timeStepping"] = timeStepping if count>0: for i in range(count): otpval = hmac2Otp.generate(counter=counter+i, inc_counter=False) otp_dict["otp"][ counter+i ] = { 'otpval' : otpval, 'time' : datetime.datetime.fromtimestamp(((counter+i-0.5)*timeStepping)+shift).strftime("%Y-%m-%d %H:%M:%S") } ret = True log.debug("[get_multi_otp] %s" % otp_dict) return (ret,error, otp_dict) ############################################### class PasswordTokenClass(TokenClass): ''' This Token does use a fixed Password as the OTP value. In addition, the OTP PIN can be used with this token. This Token can be used for a scenario like losttoken ''' class __secretPassword__(object): def __init__(self, secObj): self.secretObject = secObj def checkOtp(self,anOtpVal): res = -1 key = self.secretObject.getKey() if key == anOtpVal: res = 0 zerome(key) del key return res def __init__(self,aToken): TokenClass.__init__(self,aToken) self.hKeyRequired = True self.setType(u"pw") @classmethod def getClassType(cls): return "pw" def update(self,param): otpkey="" if (self.hKeyRequired == True): otpkey = getParam(param,"otpkey",required) self.token.setOtpLen(len(otpkey)) TokenClass.update(self,param) def reset(self): TokenClass.reset(self) def checkOtp(self,anOtpVal,counter,window,initTime="", options=None): ''' This checks the static password ''' log.debug("checkOtp of PasswordToken") res = -1 secretHOtp = self.token.getHOtpKey() sp = PasswordTokenClass.__secretPassword__(secretHOtp) res = sp.checkOtp(anOtpVal) return res ############################################### class MotpTokenClass(TokenClass): def __init__(self,aToken): TokenClass.__init__(self,aToken) self.setType(u"mOTP") @classmethod def getClassType(cls): return "motp" def update(self,param): getParam(param,"otpkey",required) ## motp token specific otpPin = getParam(param,"otppin",required) self.token.setUserPin(otpPin) TokenClass.update(self, param) def reset(self): TokenClass.reset(self) def checkOtp(self,anOtpVal,counter,window,initTime="", options=None): log.debug("checkMTimeOtp") otplen = self.token.LinOtpOtpLen #otime contains the previous verification time # the new one must be newer than this! otime = self.token.LinOtpCount secretHOtp = self.token.getHOtpKey() window = self.token.LinOtpCountWindow secretPin = self.token.getUserPin() log.debug("otime %s",otime) log.debug("iniTime %s",initTime) mtimeOtp = mTimeOtp(secretHOtp,secretPin, otime, otplen) res = mtimeOtp.checkOtp(anOtpVal,window,initTime=initTime) if (res != -1): res = res -1 ## later on this will be incremented by 1 return res class SmsTokenClass(HmacTokenClass): def __init__(self,aToken): TokenClass.__init__(self,aToken) self.setType(u"sms") self.hKeyRequired = False # we support various hashlib methods, but only on create # which is effectivly set in the update try: self.hashlibStr = getFromConfig("hotp.hashlib") except: self.hashlibStr = "sha1" @classmethod def getClassType(cls): return "sms" def update(self,param): # specific - phone phone = getParam(param,"phone",required) self.setPhone(phone) # CKO: if no otpkey is given, the server generates one! # @Kay: fix this ;-) otpKey = getParam(param,"otpkey",optional) if otpKey == None: key = "" for _i in range(0,31): key += chr(random.randrange(0,255)) self.setOtpKey(binascii.hexlify(key)) HmacTokenClass.update(self,param) ## !!! ## this function is to be called in the sms controller ## !!! def checkPass(self,passw, message=""): ret = False otp = "" mypHash = self.token.getHashedPin(passw) pHash = self.token.LinOtpPinHash if (mypHash == pHash): if (self.isActive() == True): counter = self.getOtpCount() log.debug("[checkPass] counter=%s" % str(counter)) self.incOtpCounter(counter, reset=False) otp = self.sendSMS(message=message) ret = True return (ret, otp) def checkPin(self, passw): log.debug("[checkPin] entering checkPin function") (res,pin,otpval) = self.splitPinPass(passw) if self.token.comparePin(pin) == False: res = -2 # Check if the passw matches the PIN, then we send an SMS if self.token.comparePin(passw): # TODO: We could make this configurable send_by_PIN_entry = True if send_by_PIN_entry: if (self.isActive() == True): counter = self.getOtpCount() log.debug("[checkPin] counter=%s" % str(counter)) self.incOtpCounter(counter, reset=False) self.sendSMS() return (res,pin,otpval) def checkOtp(self, anOtpVal,counter,window,initTime="", options=None): ret = HmacTokenClass.checkOtp(self, anOtpVal,counter,window) if ret != -1: if self.isValid() == False: ret = -1 return ret def getNextOtp(self): try: ### TODO - replace tokenLen otplen = int(self.token.LinOtpOtpLen) except ValueError: return -1 secretHOtp = self.token.getHOtpKey() counter = self.token.getOtpCounter() #log.debug("serial: %s",serialNum) hmac2Otp = HmacOtp(secretHOtp, counter, otplen) nextOtp = hmac2Otp.generate(counter+1) return nextOtp; ### in the SMS token we use the generic TokenInfo ### to store the phone number def setPhone(self,phone): self.setSMSInfo("phone",phone) def setUntil(self,until): self.setSMSInfo("until",until) def getPhone(self): (phone,_till) = self.getSMSInfo() return phone def getUntil(self): (_phone,until) = self.getSMSInfo() return until def setSMSInfo(self,key,value): self.addToTokenInfo(key,value) def getSMSInfo(self): phone = "" until = 0 info = self.getTokenInfo() if info.has_key("phone") == True: phone = info.get("phone") if info.has_key("until") == True: until = info.get("until") return (phone,until) ### we take the countWindow.column to store the time ## in int format (cut off the .2 from the time() ) ### def setValidUntil(self): timeScope = self.loadLinOtpSMSValidTime() dueDate = int (time.time()) + timeScope self.setUntil(dueDate) #self.token.setCountWindow(dueDate) def isValid(self): ret = False dueDate = self.getUntil() now = int(time.time()) if dueDate > now: ret = True return ret def sendSMS(self, message="<otp>"): # FIXME: In case of EDITION == CE, we should do nothing here... phone = self.getPhone() otp = self.getNextOtp() serial = self.getSerial() message = message.replace("<otp>", otp) message = message.replace("<serial>", serial) log.debug("[sendSMS] sending SMS to phone number %s " % phone ) ## TODO: remove - test purpose ## should be done after submit self.setValidUntil() (SMSProvider,SMSProviderClass) = self.loadLinOtpSMSProvider() log.debug("[sendSMS] smsprovider: %s, class: %s" % (SMSProvider, SMSProviderClass)) sms = getSMSProviderClass(SMSProvider, SMSProviderClass)() ## now we need the config from the env log.debug("[sendSMS] loading SMS configuration for class %s" % sms) config = self.loadLinOtpSMSProviderConfig() log.debug("[sendSMS] config: %s" % str(config)) sms.loadConfig(config) log.debug("[sendSMS] submitMessage: %s, to phone %s" % (message,phone) ) sms.submitMessage(phone,message) log.debug("[sendSMS] message submitted") ## after submit set validity time self.setValidUntil() # return OTP for selftest purposes return message def loadLinOtpSMSProvider(self): smsProvider = getFromConfig("SMSProvider") if isSelfTest(): smsProvider = "smsprovider.TestSMSProvider.TestSMSProvider" if smsProvider != None: (SMSProvider,SMSProviderClass) = smsProvider.rsplit(".",1) return (SMSProvider,SMSProviderClass) #SMSProvider = "smsprovider.HttpSMSProvider" ##SMSProvider = "HttpSMSProvider" #SMSProviderClass = "HttpSMSProvider" #return (SMSProvider,SMSProviderClass) def loadLinOtpSMSProviderConfig(self): ## get User realm config = {} tConfig = getFromConfig("SMSProviderConfig") log.debug("[loadLinOtpSMSProviderConfig] providerconfig: %s" % tConfig ) if tConfig != None: config = loads(tConfig) return config #config = {'URL':'http://127.0.0.1:5001/validate/ok', # 'PARAMETER': { # 'von':'OWN_NUMBER', # 'passwort':'PASSWORD', # 'absender':'TYPE', # 'konto':'1' # }, # 'SMS_TEXT_KEY':'text', # 'SMS_PHONENUMBER_KEY':'ziel', # 'HTTP_Method':'GET', # } #return config def loadLinOtpSMSValidTime(self): try: timeOut = int(getFromConfig("SMSProviderTimeout")) except: log.error("SMSProviderTimeout: value error - reset to 5*60") timeOut = 5 * 60 return timeOut ############################################### class RemoteTokenClass(TokenClass): def __init__(self,aToken): TokenClass.__init__(self,aToken) self.setType(u"remote") self.remoteServer = "" self.remoteLocalCheckpin = None self.remoteSerial = None self.remoteUser = None self.remoteRealm = None self.remoteResConf = None @classmethod def getClassType(cls): return "remote" def update(self,param): self.remoteServer = getParam(param,"remote.server",required) self.setOtpLen(6) val = getParam(param,"remote.local_checkpin",optional) if val != None: self.remoteLocalCheckpin = val val = getParam(param,"remote.serial",optional) if val != None: self.remoteSerial = val val = getParam(param,"remote.user",optional) if val != None: self.remoteUser = val val = getParam(param,"remote.realm",optional) if val != None: self.remoteRealm = val val = getParam(param,"remote.resConf",optional) if val != None: self.remoteResConf = val TokenClass.update(self,param) self.addToTokenInfo("remote.server", self.remoteServer) self.addToTokenInfo("remote.serial",self.remoteSerial) self.addToTokenInfo("remote.user", self.remoteUser) self.addToTokenInfo("remote.local_checkpin", self.remoteLocalCheckpin) self.addToTokenInfo("remote.realm", self.remoteRealm) self.addToTokenInfo("remote.resConf", self.remoteResConf) def checkPin(self, passw): (res,pin,otpval) = self.splitPinPass(passw); if 1 == int(self.getFromTokenInfo("remote.local_checkpin")): (res,_pin,_otpval) = TokenClass.checkPin(self, passw) return (res,pin,otpval) def splitPinPass(self, passw): ''' Split the PIN and the OTP value. Only if it is locally checked and not remotely. ''' res = 0 local_check = self.getFromTokenInfo("remote.local_checkpin") log.debug("[splitPinPass] [remotetoken] local checking pin? %s" % local_check) if 1 == int(local_check): (res,pin,otpval) = TokenClass.splitPinPass(self, passw) else: pin = "" otpval = passw log.debug("[splitPinPass] [remotetoken] returnung (len:%s) (len:%s)" % (len(pin), len(otpval))) return (res,pin,otpval) def checkOtp(self,anOtpVal,counter,window,initTime="", options=None): ''' Here we contact the other LinOTP server to validate the OtpVal. ''' log.debug("checkRemoteOTP") res = -1 remoteServer = self.getFromTokenInfo("remote.server") remoteSerial = self.getFromTokenInfo("remote.serial") remoteUser = self.getFromTokenInfo("remote.user") remoteRealm = self.getFromTokenInfo("remote.realm") remoteResConf = self.getFromTokenInfo("remote.resConf") ''' here we also need to check for remote.user and so on.... ''' log.debug("[checkOtp] checking OTP len:%s remotely on server: %s, serial: %s, user: %s" % (len(anOtpVal), remoteServer, remoteSerial, remoteUser) ) f = None path = "" p = "" if len(remoteSerial)>0: p = urllib.urlencode( {'serial':remoteSerial, 'pass': anOtpVal} ) path = '/validate/check_s?' elif len(remoteUser)>0 : p = urllib.urlencode( {'user':remoteUser, 'realm':remoteRealm, 'resConf':remoteResConf, 'pass': anOtpVal} ) path = '/validate/check?' else: ''' There is no remote.serial and no remote.user, so we will pass the our own user. FIXME: At this point, we do not know our user! ''' log.warning("FIXME: We do not know the user at the moment!") URL = "%s%s%s" % (remoteServer, path, p) try: f = urllib2.urlopen( urllib2.Request(URL)) rv = load(f) log.debug(rv) status = rv['result']['status'] log.debug(status) if True == status: if True == rv['result']['value']: res = 1 except Exception, e: log.error("[checkOtp] [RemoteToken] Error getting response from remote Server (%s): %s" % (URL, str(e))) return res ############################################### class RadiusTokenClass(TokenClass): def __init__(self,aToken): TokenClass.__init__(self,aToken) self.setType(u"radius") self.radiusServer = "" self.radiusUser = "" self.radiusLocal_checkpin = "0" self.radiusSecret = "voidRadiusSecret" @classmethod def getClassType(cls): return "radius" def update(self,param): self.radiusServer = getParam(param,"radius.server",required) self.setOtpLen(6) val = getParam(param,"radius.local_checkpin",optional) if val != None: self.radiusLocal_checkpin = val val = getParam(param,"radius.user",required) if val != None: self.radiusUser = val val = getParam(param,"radius.secret",required) if val != None: self.radiusSecret = val TokenClass.update(self,param) # We need to write the secret! self.token.setHKey(binascii.hexlify(self.radiusSecret)) self.addToTokenInfo("radius.server", self.radiusServer) self.addToTokenInfo("radius.local_checkpin",self.radiusLocal_checkpin) self.addToTokenInfo("radius.user", self.radiusUser) def checkPin(self, passw): (res,pin,otpval) = self.splitPinPass(passw); log.debug("[checkPin] [radiustoken] %s, %s, %s" % (res,pin,otpval)) if 1 == int(self.getFromTokenInfo("radius.local_checkpin")): log.debug("[checkPin] [radiustoken] checking PIN locally") (res,_pin,_otpval) = TokenClass.checkPin(self, passw) return (res,pin,otpval) def splitPinPass(self, passw): ''' Split the PIN and the OTP value. Only if it is locally checked and not remotely. ''' res = 0 pin = "" otpval = "" local_check = self.getFromTokenInfo("radius.local_checkpin") log.debug("[splitPinPass] [radiustoken] local checking pin? %s" % local_check) if 1 == int(local_check): log.debug("[splitPinPass] [radiustoken] locally checked") (res,pin,otpval) = TokenClass.splitPinPass(self, passw) else: log.debug("[splitPinPass] [radiustoken] remotely checked") pin = "" otpval = passw log.debug("[splitPinPass] [radiustoken] returning (len:%s) (len:%s)" % (len(pin), len(otpval))) return (res,pin,otpval) def checkOtp(self,anOtpVal,counter,window,initTime="", options=None): ''' Here we contact the Radius Server to verify the pass ''' log.debug("checkRemoteRadius") res = -1 radiusServer = self.getFromTokenInfo("radius.server") radiusUser = self.getFromTokenInfo("radius.user") # Read the secret!!! secret = self.token.getHOtpKey() radiusSecret = binascii.unhexlify(secret.getKey()) #log.debug("[checkOTP] [RadiusToken] read the radiusSecret %s" % radiusSecret) ''' here we also need to check for radius.user ''' log.debug("[checkOtp] checking OTP len:%s on radius server: %s, user: %s" % (len(anOtpVal), radiusServer, radiusUser) ) try: # pyrad does not allow to set timeout and retries. # it defaults to retries=3, timeout=5 # TODO: At the moment we support only one radius server. No round robin. server = radiusServer.split(':') r_server = server[0] r_authport=1812 nas_identifier=env.get("radius.nas_identifier") dict = env.get("radius.dictfile") #dict = getConfig("/usr/share/pyshared/linotp/dictionary") #dict = "/usr/share/pyshared/linotp/dictionary" if len(server)>=2: r_authport=int(server[1]) log.debug("[checkOTP] [RadiusToken] NAS Identifier: %s, Dictionary: %s" % (nas_identifier, dict)) log.debug("[checkOTP] [RadiusToken] constructing client object with server: %s, port: %s, secret: %s" % (r_server, r_authport, radiusSecret)) srv=Client(server=r_server, authport=r_authport, secret=radiusSecret, dict=Dictionary(dict)) #log.debug("[checkOTP [RadiusToken] building Request packet") req=srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=radiusUser.encode('ascii'), NAS_Identifier=nas_identifier.encode('ascii')) #log.debug("[checkOTP [RadiusToken] adding password to request") req["User-Password"]=req.PwCrypt(anOtpVal) #log.debug("[checkOTP [RadiusToken] sending request") #log.debug(req) reply=srv.SendPacket(req) #log.debug("[checkOTP [RadiusToken] got reply") if reply.code==pyrad.packet.AccessAccept: log.info("[checkOTP] [RadiusToken] Radiusserver %s granted access to user %s." % (r_server, radiusUser)) res = 1 else: log.warning("[checkOTP] [RadiusToken] Radiusserver %s rejected access to user %s." % (r_server,radiusUser)) except Exception, e: log.error("[checkOtp] [RadiusToken] Error contacting radius Server: %s", str(e)) log.error("[checkOtp] [RadiusToken] %s" % str(traceback.format_exc())) return res ############################################### class TagespasswortTokenClass(TokenClass): ''' The Tagespasswort is a one time password that is calculated based on the day input. ''' def __init__(self,aToken): TokenClass.__init__(self,aToken) self.setType(u"DPW") self.hKeyRequired = True @classmethod def getClassType(cls): return "dpw" def update(self,param): ## check for the required parameters if (self.hKeyRequired == True): getParam(param,"otpkey",required) TokenClass.update(self,param) def reset(self): TokenClass.reset(self) def checkOtp(self, anOtpVal,counter,window,initTime="", options=None): res = -1 try: otplen = int(self.token.LinOtpOtpLen) except ValueError: return res secretHOtp = self.token.getHOtpKey() dpw = dpwOtp(secretHOtp, otplen) res = dpw.checkOtp(anOtpVal, window=window) return res def getOtp(self, curTime=None): ## kay: init value res = (-1,0,0,0) try: otplen = int(self.token.LinOtpOtpLen) except ValueError: return res secretHOtp = self.token.getHOtpKey() dpw = dpwOtp(secretHOtp, otplen) date_string=None if curTime: if type(curTime)==datetime.datetime: date_string = curTime.strftime("%d%m%y") elif type(curTime)==unicode: date_string = datetime.datetime.strptime("2012-05-16 09:00:52.227413","%Y-%m-%d %H:%M:%S.%f").strftime("%d%m%y") else: log.error("[getOtp] invalid curTime: %s. You need to specify a datetime.datetime" % type(curTime)) otpval = dpw.getOtp(date_string) pin = self.token.getPin() combined = "%s%s" % (otpval,pin) if getFromConfig("PrependPin") == "True" : combined = "%s%s" % (pin,otpval) return ( 1, pin, otpval, combined ) def get_multi_otp(self,count=0, epoch_start=0, epoch_end=0, curTime=None): ''' This returns a dictionary of multiple future OTP values of the Tagespasswort token parameter count - how many otp values should be returned epoch_start - time based tokens: start when epoch_end - time based tokens: stop when return True/False error text OTP dictionary ''' otp_dict={"type" : "DPW", "otp": {}} ret = False error = "No count specified" try: otplen = int(self.token.LinOtpOtpLen) except ValueError, e: log.error("[get_multi_otp] %s" % str(e)) return (False, str(e), otp_dict) secretHOtp = self.token.getHOtpKey() dpw = dpwOtp(secretHOtp, otplen) log.debug("[get_multi_otp] retrieving %i OTP values for token %s" % (count, dpw)) if count>0: now = datetime.datetime.now() if curTime: if type(curTime)==datetime.datetime: now=curTime elif type(curTime)==unicode: now=datetime.datetime.strptime("2012-05-16 09:00:52.227413","%Y-%m-%d %H:%M:%S.%f") else: log.error("[get_multi_otp] wrong curTime type: %s" % type(curTime)) raise TokenAdminError(2001, "[get_multi_otp] wrong curTime type: %s (%s)" % (type(curTime),curTime)) for i in range(count): delta = datetime.timedelta(days=i) date_string=(now + delta).strftime("%d%m%y") otpval = dpw.getOtp(date_string=date_string) otp_dict["otp"][ (now+delta).strftime("%y-%m-%d")] = otpval ret = True log.debug("[get_multi_otp] %s" % otp_dict) return (ret,error, otp_dict) ############################################### class VascoTokenClass(TokenClass): def __init__(self,aToken): TokenClass.__init__(self,aToken) self.setType(u"VASCO") self.hKeyRequired = True @classmethod def getClassType(cls): return "VASCO" def update(self,param): ## check for the required parameters if (self.hKeyRequired == True): getParam(param,"otpkey",required) val = getParam(param,"otplen", optional) if val != None: self.setOtpLen(int(val)) TokenClass.update(self,param,reset_failcount=False) for key in ["vasco_appl", "vasco_type", "vasco_auth"]: val = getParam(param,key,optional) if val != None: self.addToTokenInfo(key, val) def reset(self): TokenClass.reset(self) def check_otp_exist( self, otp, range=10 ): ''' checks if the given OTP value is/are values of this very token. This is used to autoassign and to determine the serial number of a token. ''' res = -1 res = self.checkOtp(otp,0,range) return res def checkOtp(self, anOtpVal,counter,window,initTime="", options=None): res = -1 secObject = self.token.getHOtpKey() otpkey = secObject.getKey() data = pickle.loads(otpkey) if True == VASCO: (res, data) = vasco_otp_check(data, anOtpVal) else: log.warning("[checkOtp] Trying to validate a vasco token, but the module is not loaded!") # update the vasco data blob self.update({"otpkey" : pickle.dumps(data)}) if 0!=res: log.warning("[checkOtp] Vasco token failed to authenticate. Vasco Error code: %d" % res ) # TODO: Vasco gives much more detailed error codes. But at the moment we do not handle more error codes! res = -1 return res ######################################### class SpassTokenClass(TokenClass): ''' This is a simple pass token. It does have no OTP component. The OTP checking will always succeed. Of course, an OTP PIN can be used. ''' def __init__(self,aToken): TokenClass.__init__(self,aToken) self.setType(u"spass") @classmethod def getClassType(cls): return "spass" def update(self,param): # cko: changed for backward compat getParam(param,"pin",optional) TokenClass.update(self,param) def reset(self): TokenClass.reset(self) def checkOtp(self,anOtpVal,counter,window,initTime="" , options=None): log.debug("checkSPassOtp") res = 0 return res def splitPinPass(self, passw): res = 0 otpval = '' return (res,passw,otpval) ''' #### OcraTokenClass ##################################### ''' class OcraTokenClass(TokenClass): ''' OcraTokenClass : implement an ocra compliant token used from Config OcraMaxChallenges - number of open challenges per token if None: 3 OcraChallengeTimeout - timeout definition like 1D, 2H or 3M if None: 1M OcraDefaultSuite - if none :'OCRA-1:HOTP-SHA256-8:C-QN08' QrOcraDefaultSuite - if none :'OCRA-1:HOTP-SHA256-8:C-QA64' @todo: - autosync ''' ''' Ocra Token Rollout zweistufiger prozess 1. https://linotpserver/admin/init? type=ocra& genkey=1& sharedsecret=1& user=BENUTZERNAME& session=SESSIONKEY =>> "serial" : SERIENNUMMER, "sharedsecret" : DATAOBJECT, "app_import" : IMPORTURL - genSharedSecret - vom HSM oder urandom ? - app_import : + linotp:// + ocrasuite ->> default aus dem config: (DefaultOcraSuite) + sharedsecret (Länge wie ???) + seriennummer - seriennummer: uuid - token wird angelegt ist aber nicht aktiv!!! (counter == 0) 2. https://linotpserver/admin/init? type=ocra& genkey=1& activationcode=AKTIVIERUNGSCODE& user=BENUTZERNAME& message=MESSAGE& session=SESSIONKEY =>> "serial" : SERIENNUMMER, "nonce" : DATAOBJECT, "transactionid" : "TRANSAKTIONSID, "app_import" : IMPORTURL - nonce - von HSM oder random ? - pkcs5 - kdf2 - es darf zur einer Zeit nur eine QR Token inaktiv (== im Ausrollzustand) sein !!!!! der Token wird über den User gefunden - seed = pdkdf2(nonce + activcode + shared secret) - challenge generiern - von urandom oder HSM 3. check_t - counter ist > nach der ersten Transaktion - if counter >= 1: delete sharedsecret löschen ''' @classmethod def getClassType(cls): ''' getClassType - return the token type shortname @return: 'ocra' @rtype: string ''' log.debug('[getClassType] ocra') return "ocra" def __init__(self,aToken): ''' getInfo - return the status of the token rollout @return: info of the ocra token state @rtype: dict ''' log.debug('[__init__]') TokenClass.__init__(self,aToken) self.setType(u"ocra") self.transId = 0 self.info = {} log.debug('[__init__]:') return def getInfo(self): ''' getInfo - return the status of the token rollout @return: info of the ocra token state @rtype: dict ''' log.debug('[getInfo] %s ' % (str(self.info))) return self.info def update(self,params,reset_failcount=True): ''' update: add further defintion for token from param in case of init ''' log.debug('[update] %s: %s: ' %(str(params),str(reset_failcount))) TokenClass.update(self,params,reset_failcount=reset_failcount) if params.has_key('ocrasuite'): self.ocraSuite = params.get('ocrasuite') else: activationcode = params.get('activationcode',None) sharedSecret = params.get('sharedsecret',None) if activationcode == None and sharedSecret == None: self.ocraSuite = self.getOcraSuiteSuite() else: self.ocraSuite = self.getQROcraSuiteSuite() self.addToTokenInfo('ocrasuite', self.ocraSuite) ocraSuite = OcraSuite(self.ocraSuite) otplen = ocraSuite.truncation self.setOtpLen(otplen) ocraPin = params.get('ocrapin',None) if ocraPin != None: self.token.setUserPin(ocraPin) if params.has_key('otpkey'): self.setOtpKey(params.get('otpkey')) self._rollout_1(params) self._rollout_2(params) log.debug('[update]:') return def _rollout_1(self, params): ''' do the rollout 1 step 1. https://linotpserver/admin/init? type=ocra& genkey=1& sharedsecret=1& user=BENUTZERNAME& session=SESSIONKEY =>> "serial" : SERIENNUMMER, "sharedsecret" : DATAOBJECT, "app_import" : IMPORTURL - genSharedSecret - vom HSM oder urandom ? - app_import : + linotp:// + ocrasuite ->> default aus dem config: (DefaultOcraSuite) + sharedsecret (Länge wie ???) + seriennummer - seriennummer: uuid ?? - token wird angelegt ist aber nicht aktiv!!! (counter == 0) ''' log.debug('[_rollout_1] %s ' %(str(params))) sharedSecret = params.get('sharedsecret',None) if sharedSecret == '1': ''' preserve the rollout state ''' self.addToTokenInfo('rollout', '1') ''' preseerver the current key as sharedSecret''' secObj = self.token.getHOtpKey() key = secObj.getKey() encSharedSecret = encryptPin(key) self.addToTokenInfo('sharedSecret',encSharedSecret) info = {} uInfo = {} info['sharedsecret'] = key uInfo['sh'] = key info['ocrasuite'] = self.getOcraSuiteSuite() uInfo['os'] = self.getOcraSuiteSuite() info['serial'] = self.getSerial() uInfo['se'] = self.getSerial() info['app_import'] = 'lseqr://init?%s' %(urllib.urlencode(uInfo)) del info['ocrasuite'] self.info = info self.token.LinOtpIsactive = False log.debug('[_rollout_1]:') return def _rollout_2(self, params): ''' 2. https://linotpserver/admin/init? type=ocra& genkey=1& activationcode=AKTIVIERUNGSCODE& user=BENUTZERNAME& message=MESSAGE& session=SESSIONKEY =>> "serial" : SERIENNUMMER, "nonce" : DATAOBJECT, "transactionid" : "TRANSAKTIONSID, "app_import" : IMPORTURL - nonce - von HSM oder random ? - pkcs5 - kdf2 - es darf zur einer Zeit nur eine QR Token inaktiv (== im Ausrollzustand) sein !!!!! der Token wird über den User gefunden - seed = pdkdf2(nonce + activcode + shared secret) - challenge generiern - von urandom oder HSM ''' log.debug('[_rollout_2] %s ' %(str(params))) activationcode = params.get('activationcode',None) if activationcode != None: ''' genkey might have created a new key, so we have to rely on ''' encSharedSecret = self.getFromTokenInfo('sharedSecret', None) if encSharedSecret == None: raise Exception ('missing shared secret of initialition for token %s' % (str(self.getSerial()))) sharedSecret = decryptPin(encSharedSecret) ''' we generate a nonce, which in the end is a challenge ''' nonce = createNonce() self.addToTokenInfo('nonce', nonce) ''' create a new key from the ocrasuite ''' key_len = 20 if self.ocraSuite.find('-SHA256'): key_len = 32 elif self.ocraSuite.find('-SHA512'): key_len = 64 newkey = kdf2(sharedSecret, nonce, activationcode, key_len) self.setOtpKey(binascii.hexlify(newkey)) ''' generate challenge, which is part of the app_import ''' message = params.get('message',None) (transid,challenge,ret,url) = self.challenge(message) ''' generate response ''' info = {} uInfo = {} info['serial'] = self.getSerial() uInfo['se'] = self.getSerial() info['nonce'] = nonce uInfo['no'] = nonce info['transactionid'] = transid uInfo['tr'] = transid info['challenge'] = challenge uInfo['ch'] = challenge if message != None: uInfo['me'] = str(message.encode("utf-8")) ustr = urllib.urlencode({'u':str(url.encode("utf-8"))}) uInfo['u'] = ustr[2:] info['url'] = str(url.encode("utf-8")) app_import = 'lseqr://nonce?%s' % (urllib.urlencode(uInfo)) ''' add a signature of the url''' signature = {'si': self.signData(app_import) } info['signature'] = signature.get('si') info['app_import'] = "%s&%s" % (app_import,urllib.urlencode(signature)) self.info = info ''' setup new state ''' self.addToTokenInfo('rollout', '2') self.enable(True) log.debug('[_rollout_2]:') return def getOcraSuiteSuite(self): ''' getQROcraSuiteSuite - return the QR Ocra Suite - if none, it will return the default @return: Ocrasuite of token @rtype: string ''' log.debug('[getOcraSuiteSuite]') defaultOcraSuite = getFromConfig("OcraDefaultSuite",'OCRA-1:HOTP-SHA256-8:C-QN08') self.ocraSuite = self.getFromTokenInfo('ocrasuite',defaultOcraSuite) log.debug('[getOcraSuiteSuite] %s:' % (str(self.ocraSuite))) return self.ocraSuite def getQROcraSuiteSuite(self): ''' getQROcraSuiteSuite - return the QR Ocra Suite - if none, it will return the default @return: QROcrasuite of token @rtype: string ''' log.debug('[getQROcraSuiteSuite]') defaultOcraSuite = getFromConfig("QrOcraDefaultSuite",'OCRA-1:HOTP-SHA256-8:C-QA64') self.ocraSuite = self.getFromTokenInfo('ocrasuite',defaultOcraSuite) log.debug('[getQROcraSuiteSuite] %s:' % (str(self.ocraSuite))) return self.ocraSuite def signData(self,data): ''' sign the received data with the secret key @param data: arbitrary string object @type param: string @return: hexlified signature of the data ''' log.debug('[signData] %s:' % (str(data))) secretHOtp = self.token.getHOtpKey() ocraSuite = OcraSuite(self.getOcraSuiteSuite(),secretHOtp) signature = ocraSuite.signData(data) log.debug('[signData]: %s:' % (str(signature))) return signature def challenge(self, data, session= '',typ='raw', challenge = None): ''' the challenge method is for creating an transaction / challenge object remark: the transaction has a maximum lifetime and a reference to the OcraSuite token (serial) @param data: data, which is the base for the challenge or None @type data: string or None @param session: session support for ocratokens @type session: string @type typ: define, which kind of challenge base should be used could be raw - take the data input as is (extract chars accordind challenge definition Q) or random - will generate a random input or hased - will take the hash of the input data @return: challenge response containing the transcation id and the challenge for the ocrasuite @rtype : tupple of (transId(string), challenge(string)) ''' s_data = 'None' s_session = 'None' s_challenge = 'None' if data != None: s_data = data if session != None: s_session = session if challenge == None: s_challenge = challenge log.debug('[challenge] %s: %s: %s' % (s_data,s_session,s_challenge)) secretHOtp = self.token.getHOtpKey() ocraSuite = OcraSuite(self.getOcraSuiteSuite(),secretHOtp) if data == None or len(data) == 0: typ = 'random' if challenge == None: if typ == 'raw': challenge = ocraSuite.data2rawChallenge(data) elif typ == 'random': challenge = ocraSuite.data2randomChallenge(data) elif typ == 'hash': challenge = ocraSuite.data2hashChallenge(data) log.debug('[OcraTokenClass] challenge: %s '%(str(challenge))) serial = self.getSerial() counter = self.getOtpCount() '''set the pin onyl in the compliant hashed mode ''' pin = '' if ocraSuite.P != None: pinObj = self.token.getUserPin() pin = pinObj.getKey() try: param = {} param['C'] = counter param['Q'] = challenge param['P'] = pin param['S'] = session if ocraSuite.T != None: now = datetime.datetime.now() stime = now.strftime("%s") itime = int(stime) param['T'] = itime ''' verify that the data is compliant with the OcraSuitesuite and the client is able to calc the otp ''' c_data = ocraSuite.combineData(**param) ocraSuite.compute(c_data) except Exception, e: log.error("[OcraTokenClass] %s" % str(traceback.format_exc())) raise Exception('[OcraTokenClass] Failed to create ocrasuite challenge: %s'%(str(e))) ''' save the object ''' digits = '0123456789' transid = '' transactionIdLen = 12 try: transactionIdLen = int(getFromConfig("OcraDefaultSuite",'12')) except: transactionIdLen = 12 log.debug("[OcraTokenClass] Failed to set transactionId length from config - using fallback %d" % (transactionIdLen)) ''' create a non exisiting challenge ''' try: while True: for c in range(0,transactionIdLen): transid += random.choice(digits) chall = OcraTokenClass.getTransaction(transid) if chall == None: break ddata = '' if data != None: ddata = data chall = OcraChallenge(transid, typ+':'+challenge,serial,typ+':'+ddata) chall.save() except Exception,e: ''' this might happen if we have a db problem or the uniqnes constrain does not fit ''' log.error("[OcraTokenClass] %s" % str(traceback.format_exc())) raise Exception('[OcraTokenClass] Failed to create challenge object: %s'%(str(e))) realm = None realms = self.token.getRealms() if len(realms) > 0: realm = realms[0] url = '' if realm != None: url = get_qrtan_url( realm.name ) log.debug('[challenge]: %s: %s: %s' % (str(transid),str(challenge),str(url))) return (transid,challenge,True,url) def checkOtp(self, passw ,counter ,window ,initTime="", options = None): ''' checkOtp - standard callback of linotp to verity the token @param passw: the passw / otp, which has to be checked @type passw: string @param counter: the start counter @type counter: int @param window: the window, in which the token is valid @type window: int @param initTime: parameter to support check of time based otp tokens - not used here @type initTime: - @param options: options contains the transaction id, eg. if check_t checks one transaction this will support assynchreonous otp checks (when check_t is used) @type options: dict @return: verification counter or -1 @rtype: int (-1) ''' log.debug('[checkOtp] %s: %s: %s' % (str(passw),str(counter),str(window))) ret = -1 secretHOtp = self.token.getHOtpKey() ocraSuite = OcraSuite(self.getOcraSuiteSuite(),secretHOtp) ''' if we have no transactionid given through the options, we have to retrieve the eldest challenge for this ocra token''' serial = self.getSerial() challenges =[] '''set the ocra token pin ''' ocraPin = '' if ocraSuite.P != None: ocraPinObj = self.token.getUserPin() ocraPin = ocraPinObj.getKey() if ocraPin == None or len(ocraPin) == 0: ocraPin = '' timeShift = 0 if ocraSuite.T != None: defTimeWindow = int( getFromConfig("ocra.timeWindow",180)) window = int( self.getFromTokenInfo('timeWindow', defTimeWindow )) / ocraSuite.T defTimeShift = int( getFromConfig("ocra.timeShift",0)) timeShift = int( self.getFromTokenInfo("timeShift",defTimeShift) ) if options == None: challenges = OcraTokenClass.getTransactions4serial(serial,currentOnly=True) elif options != None: if type(options).__name__ != 'dict': err = '[chekOtp] "options" not of type dict!' %(str(type(options))) log.error(err) raise Exception(err) if options.has_key('transactionid'): transid = options.get('transactionid') challenges.append(OcraTokenClass.getTransaction(transid)) elif options.has_key('challenge'): challenges.append(options) if len(challenges) == 0: ''' verify that there has already been a challenge ''' challenges = OcraTokenClass.getTransactions4serial(serial) if len(challenges) > 0: err = 'No current transaction found!' ret = -1 return ret else: err = 'No open transaction found!' log.error( err) if type(options) == dict and options.has_key('transactionid'): raise Exception(err) ret = -1 return ret for ch in challenges: challenge = {} if type(ch) == dict: ''' transaction less checkOtp''' self.transId = 0 challenge.update(ch) elif type(ch) == OcraChallenge: ''' preserve transaction context, so we could use this in the status callback ''' self.transId = ch.transid challenge['challenge'] = ch.challenge challenge['transid'] = ch.transid challenge['session'] = ch.session ret = ocraSuite.checkOtp(passw, counter, window, challenge, pin = ocraPin , options=options, timeshift = timeShift) log.debug('[checkOtp]: %s' % (str(ret))) if ret != -1: break if -1 == ret: ''' autosync: test if two consecutive challenges + it's counter match ''' ret = self.autosync(ocraSuite, passw, challenge) return ret def autosync(self, ocraSuite, passw, challenge): ''' try to resync a token automaticaly, if a former and the current request failed @param ocraSuite: the ocraSuite of the current Token @type ocraSuite: ocra object @param passw: ''' log.debug('[OcraToken::autosync] %s : %s' % (str(passw), str(challenge)) ) res = -1 autosync = False try: async = getFromConfig("AutoResync") if async == None: autosync = False elif "true" == async.lower(): autosync = True elif "false" == async.lower(): autosync = False except Exception, e: log.error('autosync check undefined %s', str(e)) return res ' if autosync is not enabled: do nothing ' if False == autosync: return res ''' AUTOSYNC starts here ''' counter = self.token.getOtpCounter() syncWindow = self.token.getSyncWindow() if ocraSuite.T != None: syncWindow = syncWindow / 10 '''set the ocra token pin ''' ocraPin = '' if ocraSuite.P != None: ocraPinObj = self.token.getUserPin() ocraPin = ocraPinObj.getKey() if ocraPin == None or len(ocraPin) == 0: ocraPin = '' timeShift = 0 if ocraSuite.T != None: timeShift = int( self.getFromTokenInfo("timeShift",0) ) timeStepping = int(ocraSuite.T) tinfo = self.getTokenInfo() ''' autosync does only work, if we have a token info, where the last challenge and the last sync-counter is stored if no tokeninfo, we start with a autosync request, thus start the lookup in the sync window ''' if tinfo.has_key('lChallenge') == False: ''' run checkOtp, with sync window for the current challenge ''' log.info('[OcraToken:autosync] initial sync') count_0 = -1 try: otp0 = passw count_0 = ocraSuite.checkOtp(otp0, counter, syncWindow, challenge, pin = ocraPin, timeshift=timeShift) except Exception as e: log.error(' error during autosync0 %s' % (str(e))) if count_0 != -1: tinfo['lChallenge'] = {'otpc' : count_0} self.setTokenInfo(tinfo) log.info('[OcraToken:autosync] initial sync - success: %s' % (str(count_0))) res = -1 log.info('[OcraToken:autosync] initial sync done!') else: ''' run checkOtp, with sync window for the current challenge ''' log.info('[OcraToken:autosync] sync') count_1 = -1 try: otp1 = passw count_1 = ocraSuite.checkOtp(otp1, counter, syncWindow, challenge, pin = ocraPin, timeshift=timeShift) except Exception as e: log.error(' error during autosync1 %s' % (str(e))) if count_1 == -1: del tinfo['lChallenge'] self.setTokenInfo(tinfo) log.info('[OcraToken:autosync] sync failed! Not a valid pass in scope (%s)' % (str(otp1))) res = -1 else: ''' run checkOtp, with sync window for the old challenge ''' lChallange = tinfo.get('lChallenge') count_0 = lChallange.get('otpc') if ocraSuite.C != None: ''' sync the counter based ocra token ''' if count_1 - count_0 < 2: self.setOtpCount(count_1) res = count_1 if ocraSuite.T != None: ''' sync the timebased ocra token ''' if count_1 - count_0 < ocraSuite.T *2 : '''calc the new timeshift !''' log.debug("[autosync] the counter %s matches: %s" % (str(count_1),str(datetime.datetime.fromtimestamp(count_1)) )) currenttime = int(time.time()) new_shift = (count_1 - currenttime) tinfo['timeShift'] = new_shift self.setOtpCount(count_1) res = count_1 ''' if we came here, the old challenge is not required anymore ''' del tinfo['lChallenge'] self.setTokenInfo(tinfo) log.info('[OcraToken:autosync] sync done!') log.debug('[autosync]: %s ' % (str(res)) ) return res def statusValidationFail(self): ''' statusValidationFail - callback to enable a status change, will be called if the token verification has failed @return - nothing ''' log.debug('[statusValidationFail]') if self.transId == 0 : return try: ocraChallenge = OcraTokenClass.getTransaction(self.transId) ocraChallenge.setTanStatus(received=True,valid=False) ''' still in rollout state?? ''' rolloutState = self.getFromTokenInfo('rollout', '0') if rolloutState == '1': log.info('rollout state 1 for token %s not completed' %(str(self.getSerial()))) elif rolloutState == '2': if ocraChallenge.received_count >= int(getFromConfig("OcraMaxChallengeRequests",'3')): ''' after 3 fails in rollout state 2 - reset to rescan ''' self.addToTokenInfo('rollout','1') log.info('rollout for token %s reset to phase 1:' %(str(self.getSerial()))) log.info('rollout for token %s not completed' %(str(self.getSerial()))) except Exception, e: log.error('[OcraTokenClass:statusValidationFail] Error during validation finalisation for token %s :%s' %(str(self.getSerial()),str(e))) log.error("[OcraTokenClass:statusValidationFail] %s" % str(traceback.format_exc())) raise Exception(e) finally: ocraChallenge.save() log.debug('[statusValidationFail]') return def statusValidationSuccess(self): ''' statusValidationSuccess - callback to enable a status change, will be called if the token shas been succesfull verified @return - nothing ''' log.debug('[statusValidationSuccess]') if self.transId == 0 : return ocraChallenge = OcraTokenClass.getTransaction(self.transId) ocraChallenge.setTanStatus(received=True,valid=True) ocraChallenge.save() ''' still in rollout state?? ''' rolloutState = self.getFromTokenInfo('rollout', '0') if rolloutState == '2': t_info = self.getTokenInfo() if t_info.has_key('rollout'): del t_info['rollout'] if t_info.has_key('sharedSecret'): del t_info['sharedSecret'] if t_info.has_key('nonce'): del t_info['nonce'] self.setTokenInfo(t_info) log.info('rollout for token %s completed' %(str(self.getSerial()))) elif rolloutState == '1': raise Exception('unable to complete the rollout ') log.debug('[statusValidationSuccess]:') return def resync(self, otp1, otp2, options=None): ''' - for the resync to work, we take the last two transactions and their challenges - for each challenge, we search forward the sync window length ''' log.debug('[resync] %s : %s' % (str(otp1), str(otp2)) ) ret = False challenges = [] o_challenges = OcraTokenClass.getTransactions4serial(self.getSerial()) for challenge in o_challenges: challenges.append(challenge) ''' check if there are enough challenges around''' if len(challenges) < 2: return False challenge1 = {} challenge2 = {} if options == None: ch1 = challenges[0] challenge1['challenge'] = ch1.challenge challenge1['transid'] = ch1.transid challenge1['session'] = ch1.session ch2 = challenges[1] challenge2['challenge'] = ch2.challenge challenge2['transid'] = ch2.transid challenge2['session'] = ch2.session else: if options.has_key('challenge1'): challenge1['challenge'] = options.get('challenge1') if options.has_key('challenge2'): challenge2['challenge'] = options.get('challenge2') if len(challenge1) == 0 or len(challenge2) == 0: error = "No challeges found!" log.error('[OcraTokenClass:resync] %s' % (error)) raise Exception('[OcraTokenClass:resync] %s' % (error)) secretHOtp = self.token.getHOtpKey() ocraSuite = OcraSuite(self.getOcraSuiteSuite(),secretHOtp) syncWindow = self.token.getSyncWindow() if ocraSuite.T != None: syncWindow = syncWindow / 10 counter = self.token.getOtpCounter() '''set the ocra token pin ''' ocraPin = '' if ocraSuite.P != None: ocraPinObj = self.token.getUserPin() ocraPin = ocraPinObj.getKey() if ocraPin == None or len(ocraPin) == 0: ocraPin = '' timeShift = 0 if ocraSuite.T != None: timeShift = int( self.getFromTokenInfo("timeShift",0) ) try: count_1 = ocraSuite.checkOtp(otp1, counter, syncWindow, challenge1, pin = ocraPin, timeshift=timeShift) if count_1 == -1: log.info('[resync] lookup for first otp value failed!') ret = False else: count_2 = ocraSuite.checkOtp(otp2, counter, syncWindow, challenge2, pin = ocraPin, timeshift=timeShift) if count_2 == -1: log.info('[resync] lookup for second otp value failed!') ret = False else: if ocraSuite.C != None: if count_1 + 1 == count_2: self.setOtpCount(count_2) ret = True if ocraSuite.T != None: if count_1 - count_2 <= ocraSuite.T * 2: ''' callculate the timeshift ''' date = datetime.datetime.fromtimestamp(count_2) log.info('[resync] syncing token to new timestamp: %s' %(str(date))) now = datetime.datetime.now() stime = now.strftime("%s") timeShift = count_2 - int(stime) self.addToTokenInfo('timeShift', timeShift) ret = True except Exception as e: log.error('[OcraTokenClass:resync] unknown error: %s' % (str(e))) raise Exception('[OcraTokenClass:resync] unknown error: %s' % (str(e))) log.debug('[resync]: %s ' % (str(ret)) ) return ret def getStatus(self,transactionId): ''' getStatus - assembles the status of a transaction / challenge in a dict { "serial": SERIENNUMMER1, "transactionid": TRANSACTIONID1, "received_tan": true, "valid_tan": true, "failcount": 0 } @param transactionId: the transaction / challenge id @type transactionId: string @return: status dict @rtype: dict ''' log.debug('[getStatus] %s' % (str(transactionId)) ) statusDict = {} ocraChallenge = OcraTokenClass.getTransaction(transactionId) if ocraChallenge != None: statusDict['serial'] = ocraChallenge.tokenserial statusDict['transactionid'] = ocraChallenge.transid statusDict['received_tan'] = ocraChallenge.received_tan statusDict['valid_tan'] = ocraChallenge.valid_tan statusDict['failcount'] = self.getFailCount() statusDict['id'] = ocraChallenge.id statusDict['timestamp'] = str(ocraChallenge.timestamp) statusDict['active'] = str(self.isActive()) log.debug('[getStatus]: %s' % (str(statusDict)) ) return statusDict @classmethod def timeoutJanitor(cls): ''' timeoutJanitor - remove all outdated transactions / challenges @return - nothing ''' log.debug('[timeoutJanitor]') scopeDef = getFromConfig("OcraChallengeTimeout",'1D') delta = datetime.timedelta(days =0) ''' timedelta supports : days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) ''' if not re.match('^(\d+[DHMS])+$', scopeDef): log.error('Faild to convert OcraChallengeTimeout value from config: %s' %(str(scopeDef))) delta = datetime.timedelta(days = 1) else: parts = re.findall('\d+[DHMS]', scopeDef) for part in parts: period = part[-1] quantity = int(part[:-1]) if period == 'D': delta = delta + datetime.timedelta(days = quantity) elif period == 'H': delta = delta + datetime.timedelta(hours = quantity) elif period == 'M': delta = delta + datetime.timedelta(minutes = quantity) elif period == 'S': delta = delta + datetime.timedelta(seconds = quantity) ocraChallenges = Session.query(OcraChallenge).filter( OcraChallenge.timestamp < datetime.datetime.now() - delta ) for ocraChallenge in ocraChallenges: log.warning("[OcraToken:timeoutJanitor] - dropping outdated ocraChallenge): %s for token %s" % (str(ocraChallenge.transid),str(ocraChallenge.tokenserial))) Session.delete(ocraChallenge) log.debug('[timeoutJanitor]') return @classmethod def maxChallengeRequestJanitor(cls): ''' maxChallengeRequestJanitor - remove all transactions / challenges which have been made more than maxChallengeRequests @return - nothing ''' log.debug('[maxChallengeRequestJanitor]') maxRequests = int(getFromConfig("OcraMaxChallengeRequests",'3')) ocraChallenges = Session.query(OcraChallenge).filter( OcraChallenge.received_count >= maxRequests ) for ocraChallenge in ocraChallenges: log.warning("[OcraToken:timeoutJanitor] - dropping outdated ocraChallenge): %s for token %s" % (str(ocraChallenge.transid),str(ocraChallenge.tokenserial))) Session.delete(ocraChallenge) log.debug('[maxChallengeRequestJanitor]') return @classmethod def maxChallengeJanitor(cls, transId = None, serial = None): ''' maxChallengeJanitor - remove for one token (serial) all challengens but the last ones @param transId: the current transaction, which provides a the lookup for the serial number @type transId: string @param serial: the serial number of the token @type serial: string @return - nothing ''' log.debug('[maxChallengeJanitor] %s : %s' % (str(transId),str(serial))) maxCahllDef = getFromConfig("OcraMaxChallenges",'3') try: ones = int(maxCahllDef) except: log.error('[OcraTokrenClass:maxChallengeJanitor] Faild to convert OcraMaxChallenges value from config: %s' %(str(maxCahllDef))) ones = 3 if ones <= 0: ones = 3 if transId != None: challenges = Session.query(OcraChallenge).filter(OcraChallenge.transid == u'' + transId) if challenges == None: log.info('[OcraTokrenClass:maxChallengeJanitor] no ocraChallenge found for tranid %s' % (str(transId))) return for challenge in challenges: serial = challenge.tokenserial if serial == None: log.error('[OcraTokrenClass:maxChallengeJanitor] failed to lookup for transid %s or serial %s' % (str(transId), (str(serial)))) return challenges = Session.query(OcraChallenge).filter(OcraChallenge.tokenserial == u'' + serial)\ .order_by(desc(OcraChallenge.id)) lastIds = set() for challenge in challenges: if len(lastIds) < ones: lastIds.add(challenge.id) else: log.warning("[OcraToken:maxChallengeJanitor] - dropping max ocraChallenges: %s :: %s for token %s" % \ (str(challenge.id),str(challenge.transid),str(challenge.tokenserial))) Session.delete(challenge) log.debug('[maxChallengeJanitor]') return @classmethod def getTransaction(cls,transId): ''' getTransaction - lookup for the challenge object of the given id @param transId: challenge identifier @type transId: string @return: the challenge data object @rtype: OcraChallenge ''' log.debug('[getTransaction] %s' % (str(transId))) ''' first do housekeeping - remove outdated transactions ''' cls.timeoutJanitor() cls.maxChallengeRequestJanitor() cls.maxChallengeJanitor(transId = transId) ocraChallenge = None count = 0 if transId != None: challenges = Session.query(OcraChallenge).filter(OcraChallenge.transid == u'' + transId) if challenges == None: log.info('no ocraChallenge found for tranid %s' % (str(transId))) return None for ocraChallenge in challenges: log.debug("[OcraSuite:getTransactionId] %s for token: %s" % (str(ocraChallenge.transid),str(ocraChallenge.tokenserial))) count += 1 if count == 0 or count > 1: log.error('%s ocraChallenge token found for this transaction %s '%(str(count),transId)) #raise Exception('%s ocraChallenge token found for this transaction %s '%(str(count),transId)) log.debug('[getTransaction] %s' % (str(ocraChallenge))) return ocraChallenge @classmethod def getTransactions4serial(cls,serial,currentOnly=False): ''' getTransactions4serial - give all challenges for a given token serial number @param serial: token serial identifier @type serial: string @param currentOnly: boolean Flag to return all Challenges (like for status request) or to return the eldest open transaction / challenge @type currentOnly: boolean flag @return: return a list of Challenges @rtype: OcraChallenge obejct list ''' log.debug('[getTransactions4serial] %s: %s' % (str(serial),str(currentOnly))) ''' first do housekeeping - remove outdated transactions ''' cls.timeoutJanitor() cls.maxChallengeRequestJanitor() cls.maxChallengeJanitor(serial = serial) ocraChallenges = [] ocraChallenge = None challenges = [] if serial != None: if currentOnly == False: challenges = Session.query(OcraChallenge).filter(OcraChallenge.tokenserial == u'' + serial)\ .order_by(desc(OcraChallenge.id)) else: ''' return the oldest transaction onyl - orderby(id).limit(1)''' challenges = Session.query(OcraChallenge).filter(OcraChallenge.tokenserial == u'' + serial)\ .filter(OcraChallenge.received_tan == False)\ .order_by(asc(OcraChallenge.id)) if challenges == None: log.info('no ocraChallenge found for serial %s' % (str(serial))) return None for ocraChallenge in challenges: log.debug("[OcraSuite:getTransactionId] %s for token: %s" % (str(ocraChallenge.transid),str(ocraChallenge.tokenserial))) ocraChallenges.append(ocraChallenge) log.debug('[getTransactions4serial]') return ocraChallenges