# -*- 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: Interface for the Challenge Response Token (OCRA)
This file is part of the linotpd service
Dependencies: -
'''
import simplejson
import re
import StringIO
from pylons import request, response, config, tmpl_context as c
from linotp.model.meta import Session
from linotp.lib.base import BaseController
from linotp.lib.config import storeConfig
from linotp.lib.config import getLinotpConfig
from linotp.lib.config import getFromConfig
from linotp.lib.config import initLinotpConfig
from linotp.lib.config import updateConfig
from linotp.lib.config import removeFromConfig
from linotp.lib.realm import setDefaultRealm
from linotp.lib.realm import isRealmDefined
from linotp.lib.util import check_session
from linotp.lib.resolver import Resolver
from linotp.lib.resolver import splitResolver
from linotp.lib.resolver import getResolverList
from linotp.lib.resolver import getResolver
from linotp.lib.resolver import deleteResolver
from linotp.lib.resolver import reloadResolverConfig
from linotp.lib.error import ParameterError
from linotp.lib.util import getParam, getLowerParams
from linotp.lib.reply import sendResult, sendError
from linotp.lib.reply import sendQRImageResult
from linotp.lib.realm import getRealms
from linotp.lib.realm import getDefaultRealm
from linotp.lib.user import setRealm
from linotp.lib.user import getUserFromRequest
from linotp.lib.user import getUserInfo
from linotp.lib.user import User
from linotp.lib.realm import deleteRealm
from linotp.lib.policy import checkPolicyPre
from linotp.lib.policy import checkPolicyPost
from linotp.lib.policy import PolicyException
from linotp.lib.policy import getPolicy
from linotp.lib.policy import deletePolicy
from linotp.lib.policy import getPolicyDefinitions
from linotp.lib.token import getTokens4UserOrSerial
from linotp.lib.tokenclass import OcraTokenClass
from urllib import urlencode
from linotp.lib.token import checkUserPass, checkSerialPass
from linotp.lib.user import getUserFromParam, getUserList
from linotp.lib.selftest import isSelfTest
from linotp.lib.policy import check_user_authorization
from linotp.lib.policy import check_auth_tokentype
from linotp.lib.policy import AuthorizeException
from linotp.lib.policy import get_auth_AutoSMSPolicy
from linotp.lib.policy import set_realm
audit = config.get('audit')
import traceback
import logging
log = logging.getLogger(__name__)
optional = True
required = False
[docs]class OcraController(BaseController):
'''
The OcraController implements challenges/response tokens according to RFC 6287
'''
def __before__(self, action, **params):
'''
Here we see, what action is to be called and check the authorization
'''
log.debug("[__before__] done")
audit.initialize()
c.audit['success'] = False
def __after__(self):
c.audit['administrator'] = getUserFromRequest(request).get("login")
audit.log(c.audit)
########################################################
[docs] def request(self):
"""
method:
orcra/request
description:
request a challenge for a user or for a serial number (token).
arguments:
* serial: (required - string)
Serial number of the token, for which a challenge should
be generated (either serial or user is required)
* user: (required - string)
The user for whose token a challenge should be generated
If the user has more than one token, an error is returend.
(either serial or user is required)
* data: (required - String: URLendoced)
These are the display data, that can be used to generate the challenge
returns:
A JSON respone::
{
"version": "LinOTP 2.4",
"jsonrpc": "2.0",
"result": {
"status": true,
"value": false,
},
"detail": {
"transactionid" : TRANSAKTIONSID,
"data" : DATAOBJECT,
}
}
* transactionid:
This is the transaction ID, that is used later for
verifying the Return code /TAN.
* data:
This is an object (URL) which can be used to generate a
QR-Coide to be displayed to the QRTAN App
exception:
"""
res = {}
count = 0
description = 'ocra/request: request a challenge for a given user or token (serial). You must either provide a parameter "user" or a parameter "serial".'
param = getLowerParams(request.params)
log.info("[request] saving default configuration: %s" % str(param))
direct_qr = False
dataobj = ""
try:
#checkPolicyPre('ocra', "request" )
serial = getParam(param, 'serial',optional)
user = getUserFromParam(param,optional)
if user.isEmpty() and serial == None:
''' raise exception'''
log.error("[request] user or serial is required")
raise ParameterError(77,"Usage:" + description)
pass
message = getParam(param, 'data' ,optional)
if message == None:
message = ''
''' ocra token '''
tokens = getTokens4UserOrSerial(user,serial)
if len(tokens) > 1 :
error = 'More than one token found: unable to create challenge for (u:%s,s:%s)!' % (str(user), str(serial))
log.error(error)
raise Exception(error)
if len(tokens) == 0:
error = 'No token found: unable to create challenge for (u:%s,s:%s)!' % (str(user), str(serial))
log.error(error)
raise Exception(error)
ocra = tokens[0]
(transId,challenge,res,url) = ocra.challenge(message)
u = urlencode({'u':str(url.encode("utf-8"))})
uInfo = {'tr': transId, 'ch' : challenge, 'me': str(message.encode("utf-8")), 'u': u[2:]}
detail = {"transactionid" : transId,
'challenge' : challenge,
'message' : str(message.encode("utf-8")),
'url' : str(url.encode("utf-8")),
}
''' create the app_url from the data'''
dataobj = 'lseqr://req?%s' %(str(urlencode(uInfo)))
''' append the signature to the url '''
signature = {'si' : ocra.signData(dataobj)}
uInfo['si'] = signature
dataobj = '%s&%s' % (dataobj,str(urlencode(signature)))
detail["data"] = dataobj
c.audit['success'] = res
#c.audit['info'] += "%s=%s, " % (k, value)
Session.commit()
except Exception, e :
error = '%s' % (str(e))
log.error("[request] failed: %s" % (str(error)))
log.error("[request] %s" % traceback.format_exc())
Session.rollback()
Session.close()
return sendResult(response,error,0)
Session.close()
qr = getParam(param, 'qr',optional)
if qr != None:
param['alt'] = detail
return sendQRImageResult(response, dataobj, param)
else:
return sendResult(response, res, 1, opt=detail)
'''
https://linotpserver/ocra/check_t?transactionid=TRANSACTIONID&pass=TAN
'''
[docs] def check_t(self):
"""
method:
orcra/check_t
description:
verify the response of the ocra token
arguments:
* transactionid: (required - string)
Dies ist eine Transaktions-ID, die bei der Challenge ausgegeben wurde.
* pass: (required - string)
die response, die der OCRA Token auf Grund der Challenge berechnet hat
returns:
A JSON response::
{
"version": "LinOTP 2.4",
"jsonrpc": "2.0",
"result": {
"status": true,
"value": {
"failcount" : 3,
"result": false
}
},
"id": 0
}
exception:
"""
res = {}
count = 0
description = 'ocra/check_t: validate a token request. '
param = getLowerParams(request.params)
log.info("[check_t] check OCRA token: %s" % str(param))
try:
# checkPolicyPre('ocra', "check_t" )
passw = getParam(param, 'pass' ,optional)
if passw == None:
''' raise exception'''
log.error("[check_t] missing pass ")
raise ParameterError(77,"Usage:" + description + "Missing parameter 'pass'.")
transid = getParam(param, 'transactionid',optional)
if transid == None:
''' raise exception'''
log.error("[check_t] missing transactionid, user or serial number of token")
raise ParameterError(77,"Usage:" + description + "Missing parameter 'transactionid'.")
''' if we have a transaction, get serial from this challenge'''
value = {}
ocraChallenge = OcraTokenClass.getTransaction(transid)
if ocraChallenge != None:
serial = ocraChallenge.tokenserial
tokens = getTokens4UserOrSerial(serial = serial)
if len(tokens) == 0 or len(tokens) > 1:
raise Exception('tokenmismatch for token serial: %s' %(str(serial)))
theToken = tokens[0]
tok = theToken.token
desc = tok.get()
realms = desc.get('LinOtp.RealmNames')
if realms == None or len(realms) == 0:
realm = getDefaultRealm
elif len(realms) > 0:
realm = realms[0]
userInfo = getUserInfo(tok.LinOtpUserid,tok.LinOtpIdResolver,tok.LinOtpIdResClass)
user = User(login=userInfo.get('username'), realm=realm)
ok = checkSerialPass(serial, passw, user=user, options={'transactionid':transid})
failcount = theToken.getFailCount()
value['result'] = ok
value['failcount'] = int(failcount)
else:
''' no challenge found for this transid '''
value['result'] = False
value['failure'] = 'No challenge for transaction %s found' % (str(transid))
c.audit['success'] = res
#c.audit['info'] += "%s=%s, " % (k, value)
Session.commit()
except Exception, e :
error = '%s' % (str(e))
log.error("[ocra/check_t] failed: %s" % (str(error)))
Session.rollback()
Session.close()
return sendResult(response,error,0)
Session.close()
return sendResult(response,value,1)
'''
https://linotpserver/ocra/checkstatus?transactionid=TRANSACTIONID
https://linotpserver/ocra/checkstatus?serial=SERIENNUMMER
https://linotpserver/ocra/checkstatus?user=BENUTZER
'''
[docs] def checkstatus(self):
"""
method:
orcra/checkstatus
description:
Methode zur assynchronen Ueberpruefungen eines Challenge Response Valiadation requests
arguments:
* transactionid: (required one of - string - (hex))
Dies ist eine Transaktions-ID, die bei der Challenge ausgegeben wurde.
* serial: (required one of - string)
die Serien Nummer des OCRA Token
* user: (required one of - string)
die Benutzer eines Tokens
required is one of (user,serial,transactionid)
returns:
A JSON response::
{
"version": "LinOTP 2.4",
"jsonrpc": "2.0",
"result": {
"status": true,
"value": [
{
"serial": SERIENNUMMER1,
"transactionid": TRANSACTIONID1,
"received_tan": true,
"valid_tan": true,
"failcount": 0
},
{
"serial": SERIENNUMMER1,
"transactionid": TRANSACTIONID2,
"received_tan": false,
"valid_tan": false,
"failcount": 0
},
{
"serial": SERIENNUMMER2,
"transactionid": TRANSACTIONID3,
"received_tan": true,
"valid_tan": false,
"failcount": 2
},
]
},
"id": 0
}
exception:
"""
res = {}
count = 0
description = 'ocra/checkstatus: check the token status - for assynchronous verification. Missing parameter: You need to provide one of the parameters "transactionid", "user" or "serial"'
param = getLowerParams(request.params)
log.debug("[checkstatus] check OCRA token status: %s" % str(param))
try:
#checkPolicyPre('ocra', "checkstatus" )
transid = getParam(param, 'transactionid' ,optional)
user = getUserFromParam(param,optional)
#user = getParam(param, 'user' ,optional)
serial = getParam(param, 'serial' ,optional)
if transid == None and user.isEmpty() and serial == None:
''' raise exception'''
log.error("[ocra/checkstatus] : missing transactionid, user or serial number for token")
raise ParameterError(77,"Usage:" + description)
tokens = []
serials = set()
status = []
if serial != None:
serials.add(serial)
''' if we have a transaction, get serial from this challenge'''
if transid != None :
ocraChallenge = None
try:
ocraChallenge = OcraTokenClass.getTransaction(transid)
except:
pass
if ocraChallenge != None:
serials.add(ocraChallenge.tokenserial)
''' if we have a serial number of token '''
if len(serials) > 0:
for serial in serials:
tokens.extend(getTokens4UserOrSerial(serial = serial))
''' if we have a user '''
if user.isEmpty() == False:
try:
tokens.extend(getTokens4UserOrSerial(user = user))
except:
log.warning("no token or user %s found!" %(str(user)))
for token in tokens:
if token.getType() == 'ocra':
challenges = []
if transid == None:
serial = token.getSerial()
challenges = OcraTokenClass.getTransactions4serial(serial)
else:
challenges.append(OcraTokenClass.getTransaction(transid))
for challenge in challenges:
stat = token.getStatus(challenge.transid)
if stat != None and len(stat) > 0:
status.append(stat)
res['values'] = status
c.audit['success'] = res
Session.commit()
except Exception, e :
error = '%s' % (str(e))
log.error("[ocra/checkstatus] failed: %s" % (str(error)))
Session.rollback()
Session.close()
return sendResult(response,error,0)
Session.close()
return sendResult(response,res,1)
def qr(self):
'''
This method is used to return OR images.
Parameter:
data: The text for the qr code
'''
param = getLowerParams(request.params)
try:
data = getParam(param,"data",required)
qs = request.query_string
if qs.startswith('data='):
data = qs[len("data="):]
return sendQRImageResult(response,data,param)
except Exception, e:
log.error("[qr] QR Code generation failed failed!" + str(e))
Session.rollback()
return sendError(response,e,1)
[docs] def getActivationCode(self):
from linotp.lib.crypt import createActivationCode
res = {}
count = 0
description = 'ocra/getActivationCode '
params = getLowerParams(request.params)
log.debug("[getActivationCode]: %s" % str(params))
try:
ac = str(params.get('activationcode'))
activationCode = createActivationCode(acode=ac)
res = {'activationcode':activationCode}
Session.commit()
except Exception, e :
error = '%s' % (str(e))
log.error("[ocra/getActivationCode] failed: %s" % (str(error)))
Session.rollback()
Session.close()
return sendResult(response,error,0)
Session.close()
return sendResult(response,res,1)
[docs] def calculateOtp(self):
from linotp.lib.crypt import kdf2
from linotp.lib.ocra import OcraSuite
import binascii
from datetime import datetime
import json
from urlparse import urlparse
from urlparse import parse_qs
res = {}
count = 0
description = 'ocra/calculateOtp: calculate the first otp from the given init2 reponse '
params = getLowerParams(request.params)
log.debug("[calculateOtp]: %s" % str(params))
try:
sharedsecret = params.get('sharedsecret')
activationcode = params.get('activationcode')
nonce = params.get('nonce')
ocrasuite = params.get('ocrasuite')
challenge = params.get('challenge')
counter = params.get('counter')
ocrapin = params.get('ocrapin')
nonce3 = params.get('no')
ocrasuite3 = params.get('os')
serial3 = params.get('se')
challenge = params.get('challenge')
counter = params.get('counter')
ocrapin = params.get('ocrapin')
init1 = params.get('init1')
init2 = params.get('init2')
''' parse init1 '''
if init1 != None:
''' now parse the appurl for the ocrasuite '''
uri = urlparse(init1.replace('lseqr://','http://'))
qs = uri.query
qdict = parse_qs(qs)
ocrasuite2 = qdict.get('os',None)
if ocrasuite2 != None and len(ocrasuite2) > 0:
ocrasuite2= ocrasuite2[0]
if ocrasuite == None:
ocrasuite = ocrasuite2
sharedsecret2 = qdict.get('sh',None)
if sharedsecret2 != None and len(sharedsecret2) > 0:
sharedsecret2 = sharedsecret2[0]
if sharedsecret == None:
sharedsecret = sharedsecret2
''' parse init1 '''
if init2 != None:
''' now parse the appurl for the ocrasuite '''
uri = urlparse(init2.replace('lseqr://','http://'))
qs = uri.query
qdict = parse_qs(qs)
challenge2 = qdict.get('ch',None)
if challenge2 != None and len(challenge2) > 0:
challenge2 = challenge2[0]
if challenge == None:
challenge = challenge2
nonce2 = qdict.get('no',None)
if nonce2 != None and len(nonce2) > 0:
nonce2 = nonce2[0]
if nonce == None:
nonce = nonce2
if ocrapin == None:
ocrapin = ''
if counter == None:
counter = 0
if nonce3 != None:
nonce = str(nonce3)
if ocrasuite3 != None:
ocrasuite = str(ocrasuite3)
'''
now we have all in place for the key derivation to create the new key
sharedsecret, activationcode and nonce
'''
key_len = 20
if ocrasuite.find('-SHA256'):
key_len = 32
elif ocrasuite.find('-SHA512'):
key_len = 64
if sharedsecret != None:
sharedsecret = str(sharedsecret)
if nonce != None:
nonce = str(nonce)
if activationcode != None:
activationcode = str(activationcode)
newkey = kdf2(sharedsecret, nonce, activationcode, len = key_len)
hnewkey = binascii.hexlify(newkey)
ocra = OcraSuite(ocrasuite)
param = {}
param['C'] = int(counter)
param['Q'] = str(challenge)
param['P'] = str(ocrapin)
param['S'] = ''
if ocra.T != None:
''' Default value for G is 1M, i.e., time-step size is one minute and the
T represents the number of minutes since epoch time [UT].
'''
now = datetime.now()
stime = now.strftime("%s")
itime = int(stime)
param['T'] = itime
data = ocra.combineData(**param)
otp = ocra.compute(data,newkey)
res = {'otp':otp}
Session.commit()
except Exception, e :
error = '%s' % (str(e))
log.error("[ocra/calculateOtp] failed: %s" % (str(error)))
Session.rollback()
Session.close()
return sendResult(response,error,0)
Session.close()
return sendResult(response,res,1)