1
0
mirror of https://github.com/Yubico/yubikey-val.git synced 2024-11-29 00:24:13 +01:00
yubikey-val/ykval-verify.php

489 lines
13 KiB
PHP
Raw Normal View History

2013-04-17 17:24:50 +02:00
<?php
2015-07-20 22:01:16 +02:00
# Copyright (c) 2009-2015 Yubico AB
2013-04-17 17:24:50 +02:00
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
require_once 'ykval-common.php';
require_once 'ykval-config.php';
require_once 'ykval-synclib.php';
2015-07-21 22:01:24 +02:00
header('content-type: text/plain');
2013-04-17 17:24:50 +02:00
$ipaddr = $_SERVER['REMOTE_ADDR'];
2015-07-21 22:47:30 +02:00
$https = (array_key_exists('HTTPS', $_SERVER) === TRUE
&& strtolower($_SERVER['HTTPS']) !== 'off' ? TRUE : FALSE);
2015-07-21 23:45:07 +02:00
/**
* FIXME
*
* Refactor code which extracts the request arguments,
* pull it up here and avoid sprinlking the following in the "core":
*
* $_GET, $_POST, $_SERVER['QUERY_STRING'], getHttpVal()
*
* Avoid ambiguity with urldecode.
*/
2013-04-17 17:24:50 +02:00
$myLog = new Log('ykval-verify');
$myLog->addField('ip', $ipaddr);
2015-07-21 22:26:37 +02:00
2015-07-21 23:45:07 +02:00
// FIXME
2015-07-21 23:09:17 +02:00
$message = '';
2015-07-17 21:30:30 +02:00
if ($_POST)
{
$kv = array();
foreach ($_POST as $key => $value)
{
$kv[] = "$key=$value";
}
2015-07-21 23:09:17 +02:00
$message = 'POST: ' . join('&', $kv);
2015-07-17 21:30:30 +02:00
}
else
{
2015-07-21 23:09:17 +02:00
$message = 'Request: ' . $_SERVER['QUERY_STRING'];
2013-04-17 17:24:50 +02:00
}
2015-07-21 23:09:17 +02:00
$message .= ' (at ' . date('c') . ' ' . microtime() . ') HTTP' . ($https ? 'S' : '');
$myLog->log(LOG_INFO, $message);
unset($message);
2013-04-17 17:24:50 +02:00
/* Detect protocol version */
2015-07-21 22:01:24 +02:00
if (preg_match('/\/wsapi\/([0-9]+)\.([0-9]+)\//', $_SERVER['REQUEST_URI'], $out))
2015-07-17 21:20:14 +02:00
{
2015-07-21 22:26:37 +02:00
$protocol_version = $out[1] + $out[2] * 0.1;
2015-07-17 21:20:14 +02:00
}
else
{
2015-07-21 22:26:37 +02:00
$protocol_version = 1.0;
2015-07-17 21:20:14 +02:00
}
2013-04-17 17:24:50 +02:00
2015-07-21 22:01:24 +02:00
$myLog->log(LOG_DEBUG, "found protocol version $protocol_version");
2013-04-17 17:24:50 +02:00
/**
* Extract values from HTTP request
2013-04-17 17:24:50 +02:00
*/
$h = getHttpVal('h', '');
$client = getHttpVal('id', 0);
$timestamp = getHttpVal('timestamp', 0);
2013-04-17 17:24:50 +02:00
$otp = getHttpVal('otp', '');
2013-04-17 17:24:50 +02:00
$otp = strtolower($otp);
2015-07-21 22:01:24 +02:00
if (preg_match('/^[jxe.uidchtnbpygk]+$/', $otp))
2015-07-17 21:20:14 +02:00
{
2015-07-21 22:01:24 +02:00
$new_otp = strtr($otp, 'jxe.uidchtnbpygk', 'cbdefghijklnrtuv');
2015-07-21 22:26:37 +02:00
$myLog->log(LOG_INFO, "Dvorak OTP converting $otp to $new_otp");
2015-07-17 21:20:14 +02:00
$otp = $new_otp;
unset($new_otp);
2013-04-17 17:24:50 +02:00
}
2013-04-17 17:24:50 +02:00
/**
* Construct response parameters
*/
2015-07-17 21:20:14 +02:00
$extra = array();
2015-07-21 22:26:37 +02:00
2015-07-17 21:20:14 +02:00
if ($protocol_version >= 2.0)
{
2015-07-21 22:26:37 +02:00
$extra['otp'] = $otp;
2013-04-17 17:24:50 +02:00
}
2015-07-21 23:02:50 +02:00
/**
* We have the OTP now, so let's add it to the logging
*/
2013-04-17 17:24:50 +02:00
$myLog->addField('otp', $otp);
2015-07-21 23:02:50 +02:00
2015-07-17 21:20:14 +02:00
if ($protocol_version >= 2.0)
{
$sl = getHttpVal('sl', '');
$timeout = getHttpVal('timeout', '');
$nonce = getHttpVal('nonce', '');
2013-04-17 17:24:50 +02:00
2015-07-17 21:20:14 +02:00
/* Nonce is required from protocol 2.0 */
if (!$nonce)
{
$myLog->log(LOG_NOTICE, 'Nonce is missing and protocol version >= 2.0');
sendResp(S_MISSING_PARAMETER, $myLog);
}
/* Add nonce to response parameters */
$extra['nonce'] = $nonce;
2013-04-17 17:24:50 +02:00
}
2015-07-21 23:02:50 +02:00
/**
* Sanity check HTTP parameters
*
2013-04-17 17:24:50 +02:00
* otp: one-time password
* id: client id
* timeout: timeout in seconds to wait for external answers, optional: if absent the server decides
* nonce: random alphanumeric string, 16 to 40 characters long. Must be non-predictable and changing for each request, but need not be cryptographically strong
* sl: "sync level", percentage of external servers that needs to answer (integer 0 to 100), or "fast" or "secure" to use server-configured values
* h: signature (optional)
* timestamp: requests timestamp/counters in response
*/
/* Change default protocol "strings" to numeric values */
2015-07-17 21:30:30 +02:00
if (isset($sl) && strcasecmp($sl, 'fast') == 0)
{
$sl = $baseParams['__YKVAL_SYNC_FAST_LEVEL__'];
2013-04-17 17:24:50 +02:00
}
2015-07-17 21:30:30 +02:00
if (isset($sl) && strcasecmp($sl, 'secure') == 0)
{
$sl = $baseParams['__YKVAL_SYNC_SECURE_LEVEL__'];
2013-04-17 17:24:50 +02:00
}
2015-07-17 21:30:30 +02:00
if (!isset($sl) || $sl == '')
{
$sl = $baseParams['__YKVAL_SYNC_DEFAULT_LEVEL__'];
2013-04-17 17:24:50 +02:00
}
if ($sl && (preg_match("/^[0-9]+$/", $sl)==0 || ($sl<0 || $sl>100)))
{
$myLog->log(LOG_NOTICE, 'SL is provided but not correct');
sendResp(S_MISSING_PARAMETER, $myLog);
}
2015-07-17 21:30:30 +02:00
if (!isset($timeout) || $timeout == '')
{
$timeout = $baseParams['__YKVAL_SYNC_DEFAULT_TIMEOUT__'];
2013-04-17 17:24:50 +02:00
}
if ($timeout && preg_match("/^[0-9]+$/", $timeout) == 0)
{
$myLog->log(LOG_NOTICE, 'timeout is provided but not correct');
sendResp(S_MISSING_PARAMETER, $myLog);
}
2013-04-17 17:24:50 +02:00
2015-07-17 21:30:30 +02:00
if ($otp == '')
{
$myLog->log(LOG_NOTICE, 'OTP is missing');
sendResp(S_MISSING_PARAMETER, $myLog);
2013-04-17 17:24:50 +02:00
}
if (strlen($otp) < TOKEN_LEN || strlen($otp) > OTP_MAX_LEN)
2015-07-17 21:30:30 +02:00
{
$myLog->log(LOG_NOTICE, "Incorrect OTP length: $otp");
2015-07-17 21:30:30 +02:00
sendResp(S_BAD_OTP, $myLog);
2013-04-17 17:24:50 +02:00
}
2015-07-21 22:01:24 +02:00
if (preg_match('/^[cbdefghijklnrtuv]+$/', $otp) == 0)
2015-07-17 21:30:30 +02:00
{
$myLog->log(LOG_NOTICE, "Invalid OTP: $otp");
2015-07-17 21:30:30 +02:00
sendResp(S_BAD_OTP, $myLog);
2013-04-17 17:24:50 +02:00
}
2015-07-17 21:30:30 +02:00
if (preg_match("/^[0-9]+$/", $client) == 0)
{
$myLog->log(LOG_NOTICE, 'id provided in request must be an integer');
sendResp(S_MISSING_PARAMETER, $myLog);
2013-04-17 17:24:50 +02:00
}
2015-07-17 21:30:30 +02:00
if ($client <= 0)
{
$myLog->log(LOG_NOTICE, 'Client ID is missing');
sendResp(S_MISSING_PARAMETER, $myLog);
}
2013-04-17 17:24:50 +02:00
2015-07-17 21:30:30 +02:00
if (isset($nonce) && preg_match("/^[A-Za-z0-9]+$/", $nonce) == 0)
{
$myLog->log(LOG_NOTICE, 'NONCE is provided but not correct');
sendResp(S_MISSING_PARAMETER, $myLog);
2013-04-17 17:24:50 +02:00
}
2015-07-17 21:30:30 +02:00
if (isset($nonce) && (strlen($nonce) < 16 || strlen($nonce) > 40))
{
$myLog->log(LOG_NOTICE, 'Nonce too short or too long');
sendResp(S_MISSING_PARAMETER, $myLog);
2013-04-17 17:24:50 +02:00
}
/**
* Timestamp parameter is not checked since current protocol
* says that 1 means request timestamp and anything else is discarded.
*/
2013-04-17 17:24:50 +02:00
2015-07-21 23:02:50 +02:00
/**
* Initialize the sync library. Strive to use this instead of custom
* DB requests, custom comparisons etc.
*/
2013-04-17 17:24:50 +02:00
$sync = new SyncLib('ykval-verify:synclib');
$sync->addField('ip', $ipaddr);
2013-04-17 17:24:50 +02:00
$sync->addField('otp', $otp);
2015-07-17 21:20:14 +02:00
if (! $sync->isConnected())
{
sendResp(S_BACKEND_ERROR, $myLog);
}
2013-04-17 17:24:50 +02:00
if (($cd = $sync->getClientData($client)) === FALSE)
2015-07-17 21:20:14 +02:00
{
$myLog->log(LOG_NOTICE, "Invalid client id $client");
2015-07-17 21:20:14 +02:00
sendResp(S_NO_SUCH_CLIENT, $myLog);
}
2015-07-21 22:01:24 +02:00
$myLog->log(LOG_DEBUG, 'Client data:', $cd);
2013-04-17 17:24:50 +02:00
2015-07-21 22:26:37 +02:00
/**
* Check client signature
*/
2015-07-21 23:12:01 +02:00
$apiKey = $cd['secret'];
$apiKey = base64_decode($apiKey);
unset($cd);
2013-04-17 17:24:50 +02:00
2015-07-17 21:32:09 +02:00
if ($h != '')
{
// Create the signature using the API key
$a;
if ($_GET)
{
$a = $_GET;
}
elseif ($_POST)
{
$a = $_POST;
}
else
{
2015-07-18 00:09:19 +02:00
// FIXME sendResp
2015-07-17 21:32:09 +02:00
sendRest(S_BACKEND_ERROR);
exit;
}
unset($a['h']);
$hmac = sign($a, $apiKey, $myLog);
2015-07-21 23:03:03 +02:00
if (hash_equals($hmac, $h) === FALSE)
2015-07-17 21:32:09 +02:00
{
$myLog->log(LOG_DEBUG, "client hmac=$h, server hmac=$hmac");
2015-07-17 21:32:09 +02:00
sendResp(S_BAD_SIGNATURE, $myLog, $apiKey);
}
2013-04-17 17:24:50 +02:00
}
2015-07-17 23:01:36 +02:00
/**
* We need to add necessary parameters not available at
* earlier protocols after signature is computed.
2013-04-17 17:24:50 +02:00
*/
2015-07-17 21:17:29 +02:00
if ($protocol_version < 2.0)
{
2015-07-17 23:01:36 +02:00
// we need to create a nonce manually here
2015-07-17 21:17:29 +02:00
$nonce = md5(uniqid(rand()));
$myLog->log(LOG_INFO, "protocol version below 2.0. Created nonce $nonce");
2015-07-17 21:17:29 +02:00
}
2013-04-17 17:24:50 +02:00
2015-07-17 23:01:36 +02:00
// which YK-KSM should we talk to?
$urls = otp2ksmurls($otp, $client);
2015-07-17 21:17:29 +02:00
if (!is_array($urls))
{
sendResp(S_BACKEND_ERROR, $myLog, $apiKey);
2013-04-17 17:24:50 +02:00
}
2015-07-17 23:01:36 +02:00
// decode OTP from input
$curlopts = array();
2015-07-17 21:17:29 +02:00
if (array_key_exists('__YKVAL_KSM_CURL_OPTS__', $baseParams))
{
$curlopts = $baseParams['__YKVAL_KSM_CURL_OPTS__'];
}
if (($otpinfo = KSMdecryptOTP($urls, $myLog, $curlopts)) === FALSE)
2015-07-17 21:17:29 +02:00
{
sendResp(S_BAD_OTP, $myLog, $apiKey);
2013-04-17 17:24:50 +02:00
}
2015-07-21 22:01:24 +02:00
$myLog->log(LOG_DEBUG, 'Decrypted OTP:', $otpinfo);
2013-04-17 17:24:50 +02:00
2015-07-17 23:01:36 +02:00
// get Yubikey from DB
$yk_publicname = substr($otp, 0, strlen ($otp) - TOKEN_LEN);
if (($localParams = $sync->getLocalParams($yk_publicname)) === FALSE)
2015-07-17 21:17:29 +02:00
{
2015-07-17 23:11:32 +02:00
$myLog->log(LOG_NOTICE, "Invalid Yubikey $yk_publicname");
2015-07-17 21:17:29 +02:00
sendResp(S_BACKEND_ERROR, $myLog, $apiKey);
}
2013-04-17 17:24:50 +02:00
2015-07-21 22:01:24 +02:00
$myLog->log(LOG_DEBUG, 'Auth data:', $localParams);
2015-07-17 21:17:29 +02:00
if ($localParams['active'] != 1)
{
2015-07-17 23:11:32 +02:00
$myLog->log(LOG_NOTICE, "De-activated Yubikey $yk_publicname");
2015-07-17 21:17:29 +02:00
sendResp(S_BAD_OTP, $myLog, $apiKey);
2013-04-17 17:24:50 +02:00
}
/* Build OTP params */
2015-07-17 21:16:40 +02:00
$otpParams = array(
'modified' => time(),
'otp' => $otp,
'nonce' => $nonce,
'yk_publicname' => $yk_publicname,
2015-07-17 21:16:40 +02:00
'yk_counter' => $otpinfo['session_counter'],
'yk_use' => $otpinfo['session_use'],
'yk_high' => $otpinfo['high'],
'yk_low' => $otpinfo['low']
);
2013-04-17 17:24:50 +02:00
/* First check if OTP is seen with the same nonce, in such case we have an replayed request */
2015-07-21 22:01:24 +02:00
if ($sync->countersEqual($localParams, $otpParams) && $localParams['nonce'] == $otpParams['nonce'])
2015-07-17 21:16:40 +02:00
{
$myLog->log(LOG_WARNING, 'Replayed request');
sendResp(S_REPLAYED_REQUEST, $myLog, $apiKey, $extra);
}
2013-04-17 17:24:50 +02:00
/* Check the OTP counters against local db */
2015-07-17 21:16:40 +02:00
if ($sync->countersHigherThanOrEqual($localParams, $otpParams))
{
$sync->log(LOG_WARNING, 'replayed OTP: Local counters higher');
$sync->log(LOG_WARNING, 'replayed OTP: Local counters ', $localParams);
$sync->log(LOG_WARNING, 'replayed OTP: Otp counters ', $otpParams);
sendResp(S_REPLAYED_OTP, $myLog, $apiKey, $extra);
}
2013-04-17 17:24:50 +02:00
/* Valid OTP, update database. */
2015-07-17 21:16:40 +02:00
if (!$sync->updateDbCounters($otpParams))
{
2015-07-21 22:01:24 +02:00
$myLog->log(LOG_CRIT, 'Failed to update yubikey counters in database');
2015-07-17 21:16:40 +02:00
sendResp(S_BACKEND_ERROR, $myLog, $apiKey);
}
2013-04-17 17:24:50 +02:00
/* Queue sync requests */
2015-07-17 21:16:40 +02:00
if (!$sync->queue($otpParams, $localParams))
{
2015-07-21 22:01:24 +02:00
$myLog->log(LOG_CRIT, 'ykval-verify:critical:failed to queue sync requests');
2015-07-17 21:16:40 +02:00
sendResp(S_BACKEND_ERROR, $myLog, $apiKey);
}
2013-04-17 17:24:50 +02:00
2015-07-17 21:23:00 +02:00
$nr_servers = $sync->getNumberOfServers();
$req_answers = ceil($nr_servers * $sl / 100.0);
if ($req_answers > 0)
{
$syncres = $sync->sync($req_answers, $timeout);
$nr_answers = $sync->getNumberOfAnswers();
$nr_valid_answers = $sync->getNumberOfValidAnswers();
$sl_success_rate = floor(100.0 * $nr_valid_answers / $nr_servers);
}
else
{
$syncres = true;
$nr_answers = 0;
$nr_valid_answers = 0;
$sl_success_rate = 0;
}
2013-04-17 17:24:50 +02:00
$myLog->log(LOG_INFO, "ykval-verify:notice:synclevel=" . $sl .
2015-07-17 21:30:30 +02:00
" nr servers=" . $nr_servers .
" req answers=" . $req_answers .
" answers=" . $nr_answers .
" valid answers=" . $nr_valid_answers .
" sl success rate=" . $sl_success_rate .
" timeout=" . $timeout);
2013-04-17 17:24:50 +02:00
2015-07-17 21:23:00 +02:00
if ($syncres == False)
{
/* sync returned false, indicating that
either at least 1 answer marked OTP as invalid or
there were not enough answers */
2015-07-21 22:01:24 +02:00
$myLog->log(LOG_WARNING, 'ykval-verify:notice:Sync failed');
2015-07-17 21:23:00 +02:00
if ($nr_valid_answers != $nr_answers)
sendResp(S_REPLAYED_OTP, $myLog, $apiKey, $extra);
$extra['sl'] = $sl_success_rate;
sendResp(S_NOT_ENOUGH_ANSWERS, $myLog, $apiKey, $extra);
2015-07-17 21:23:00 +02:00
}
2013-04-17 17:24:50 +02:00
/* Recreate parameters to make phising test work out
TODO: use timefunctionality in deltatime library instead */
$sessionCounter = $otpParams['yk_counter'];
$sessionUse = $otpParams['yk_use'];
$seenSessionCounter = $localParams['yk_counter'];
$seenSessionUse = $localParams['yk_use'];
2015-07-17 21:23:00 +02:00
$ad['high'] = $localParams['yk_high'];
$ad['low'] = $localParams['yk_low'];
$ad['accessed'] = date('Y-m-d H:i:s', $localParams['modified']);
2013-04-17 17:24:50 +02:00
2015-07-17 21:25:15 +02:00
// check the time stamp
if ($sessionCounter == $seenSessionCounter && $sessionUse > $seenSessionUse)
{
$ts = ($otpinfo['high'] << 16) + $otpinfo['low'];
$seenTs = ($ad['high'] << 16) + $ad['low'];
$tsDiff = $ts - $seenTs;
$tsDelta = $tsDiff * TS_SEC;
// check the real time
$lastTime = strtotime($ad['accessed']);
$now = time();
$elapsed = $now - $lastTime;
$deviation = abs($elapsed - $tsDelta);
// Time delta server might verify multiple OTPS in a row. In such case validation server doesn't
// have time to tick a whole second and we need to avoid division by zero.
if ($elapsed != 0)
{
$percent = $deviation/$elapsed;
}
else
{
$percent = 1;
}
2015-07-24 10:50:21 +02:00
$data = array(
'seen' => $seenTs,
'this' => $ts,
'delta' => $tsDiff,
'secs' => $tsDelta,
2015-07-24 13:54:49 +02:00
'accessed' => sprintf('%s (%s)', $lastTime, $ad['accessed']),
'now' => sprintf('%s (%s)'. $now, strftime('%Y-%m-%d %H:%M:%S', $now)),
2015-07-24 10:50:21 +02:00
'elapsed' => $elapsed,
2015-07-24 13:54:49 +02:00
'deviation' => sprintf('%s secs or %s%%', $deviation, round(100 * $percent)),
2015-07-24 10:50:21 +02:00
);
$msg = 'Timestamp';
foreach ($data as $k => $v) $msg .= " $k=$v";
$myLog->log(LOG_INFO, $msg);
unset($data, $msg);
2015-07-17 21:25:15 +02:00
if ($deviation > TS_ABS_TOLERANCE && $percent > TS_REL_TOLERANCE)
{
2015-07-21 22:01:24 +02:00
$myLog->log(LOG_NOTICE, 'OTP failed phishing test');
2015-07-17 21:25:15 +02:00
2015-07-21 23:38:46 +02:00
// FIXME
// This was wrapped around if (0). should we nuke or enable?
// sendResp(S_DELAYED_OTP, $myLog, $apiKey, $extra);
2015-07-17 21:25:15 +02:00
}
2013-04-17 17:24:50 +02:00
}
2015-07-21 22:26:37 +02:00
/**
* Fill up with more response parameters
*/
2015-07-17 21:16:40 +02:00
if ($protocol_version >= 2.0)
{
$extra['sl'] = $sl_success_rate;
}
if ($timestamp == 1)
{
$extra['timestamp'] = ($otpinfo['high'] << 16) + $otpinfo['low'];
$extra['sessioncounter'] = $sessionCounter;
$extra['sessionuse'] = $sessionUse;
}
2013-04-17 17:24:50 +02:00
sendResp(S_OK, $myLog, $apiKey, $extra);