Subversion Repositories oidplus

Rev

Rev 1086 | Rev 1130 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *     http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19.  
  20. namespace ViaThinkSoft\OIDplus;
  21.  
  22. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. class OIDplusCaptchaPluginVtsClientChallenge extends OIDplusCaptchaPlugin {
  27.  
  28.         /**
  29.          * @return string
  30.          */
  31.         public static function id(): string {
  32.                 return 'ViaThinkSoft Client Challenge';
  33.         }
  34.  
  35.         /**
  36.          * @return bool
  37.          */
  38.         public function isVisible(): bool {
  39.                 return false;
  40.         }
  41.  
  42.         /**
  43.          * @param string $actionID
  44.          * @return bool
  45.          */
  46.         public function csrfUnlock(string $actionID): bool {
  47.                 if ($actionID == 'get_challenge') return true;
  48.                 return parent::csrfUnlock($actionID);
  49.         }
  50.  
  51.         /**
  52.          * @param string $actionID
  53.          * @param array $params
  54.          * @return array
  55.          * @throws OIDplusException
  56.          */
  57.         public function action(string $actionID, array $params): array {
  58.                 if ($actionID == 'get_challenge') {
  59.                         $server_secret='VtsClientChallenge:'.OIDplus::baseConfig()->getValue('SERVER_SECRET');
  60.  
  61.                         $offset = 0; // doesn't matter
  62.                         $min = $offset;
  63.                         $max = $offset + OIDplus::baseConfig()->getValue('VTS_CAPTCHA_COMPLEXITY', 50000);
  64.                         if ($max > mt_getrandmax()) $max = mt_getrandmax();
  65.  
  66.                         $starttime = time();
  67.                         $random = mt_rand($min,$max);
  68.                         $ip_target = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown';
  69.                         $challenge = sha3_512($starttime.'/'.$ip_target.'/'.$random);
  70.                         $challenge_integrity = sha3_512_hmac($challenge,$server_secret);
  71.                         $send_to_client = array($starttime, $ip_target, $challenge, $min, $max, $challenge_integrity);
  72.  
  73.                         $open_trans_file = self::getOpenTransFileName($ip_target, $random);
  74.                         if (@file_put_contents($open_trans_file, '') === false) {
  75.                                 throw new OIDplusException(_L('Cannot write file %1', $open_trans_file));
  76.                         }
  77.  
  78.                         return array(
  79.                                 "status" => 0,
  80.                                 "challenge" => $send_to_client,
  81.                                 // Autosolve on=calculate result on page load; off=calculate result on form submit
  82.                                 "autosolve" => OIDplus::baseConfig()->getValue('VTS_CAPTCHA_AUTOSOLVE', true)
  83.                         );
  84.                 } else {
  85.                         return parent::action($actionID, $params);
  86.                 }
  87.         }
  88.  
  89.         /**
  90.          * @param $ip_target
  91.          * @param $random
  92.          * @return string
  93.          * @throws OIDplusException
  94.          */
  95.         private static function getOpenTransFileName($ip_target, $random) {
  96.                 $dir = OIDplus::localpath().'/userdata/cache';
  97.                 $server_secret='VtsClientChallenge:'.OIDplus::baseConfig()->getValue('SERVER_SECRET');
  98.  
  99.                 // First, delete challenges which were never completed
  100.                 $files = glob($dir.'/vts_client_challenge_*.tmp');
  101.                 $expire = strtotime('-3 DAYS');
  102.                 foreach ($files as $file) {
  103.                         if (!is_file($file)) continue;
  104.                         if (filemtime($file) > $expire) continue;
  105.                         @unlink($file);
  106.                 }
  107.  
  108.                 return $dir.'/vts_client_challenge_'.sha3_512_hmac($ip_target.'/'.$random, $server_secret).'.tmp';
  109.         }
  110.  
  111.         /**
  112.          * @param string|null $header_text
  113.          * @param string|null $footer_text
  114.          * @return string
  115.          * @throws OIDplusException
  116.          */
  117.         public function captchaGenerate(string $header_text=null, string $footer_text=null): string {
  118.                 return '<noscript>'.
  119.                        '<p><font color="red">'._L('You need to enable JavaScript to solve the CAPTCHA.').'</font></p>'.
  120.                        '</noscript>'.
  121.                        '<input type="hidden" id="vts_validation_result" name="vts_validation_result" value="">'.
  122.                        '<script>'.
  123.                        'OIDplusCaptchaPluginVtsClientChallenge.captchaShow('.js_escape(OIDplus::webpath(null,OIDplus::PATH_RELATIVE)).');'.
  124.                        '</script>';
  125.         }
  126.  
  127.         /**
  128.          * @param array $params
  129.          * @param string|null $fieldname
  130.          * @return void
  131.          * @throws OIDplusException
  132.          */
  133.         public function captchaVerify(array $params, string $fieldname=null) {
  134.  
  135.                 if (is_null($fieldname)) $fieldname = 'vts_validation_result';
  136.  
  137.                 $server_secret='VtsClientChallenge:'.OIDplus::baseConfig()->getValue('SERVER_SECRET');
  138.  
  139.                 if (!isset($params[$fieldname])) throw new OIDplusException(_L('No challenge response found').' (A)');
  140.  
  141.                 $client_response = @json_decode($params[$fieldname], true);
  142.  
  143.                 if (!is_array($client_response)) throw new OIDplusException(_L('Challenge response is invalid').' (B)');
  144.                 if (count($client_response) != 5) throw new OIDplusException(_L('Challenge response is invalid').' (C)');
  145.                 list($starttime, $ip_target, $challenge, $answer, $challenge_integrity) = $client_response;
  146.                 if (!is_numeric($starttime)) throw new OIDplusException(_L('Challenge response is invalid').' (D)');
  147.                 if (!is_string($ip_target)) throw new OIDplusException(_L('Challenge response is invalid').' (E)');
  148.                 if (!is_string($challenge)) throw new OIDplusException(_L('Challenge response is invalid').' (F)');
  149.                 if (!is_numeric($answer)) throw new OIDplusException(_L('Challenge response is invalid').' (G)');
  150.                 if (!is_string($challenge_integrity)) throw new OIDplusException(_L('Challenge response is invalid').' (H)');
  151.  
  152.                 $open_trans_file = self::getOpenTransFileName($ip_target, $answer);
  153.  
  154.                 $current_ip = (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown');
  155.                 if ($ip_target != $current_ip) {
  156.                         throw new OIDplusException(_L('IP address has changed. Please try again. (current IP %1, expected %2)', $current_ip, $ip_target));
  157.                 } else if (time()-$starttime > OIDplus::baseConfig()->getValue('VTS_CAPTCHA_MAXTIME', 10*60/*10 minutes*/)) {
  158.                         throw new OIDplusException(_L('Challenge expired. Please try again.'));
  159.                 } else if ($challenge_integrity != sha3_512_hmac($challenge,$server_secret)) {
  160.                         throw new OIDplusException(_L('Challenge integrity failed'));
  161.                 } else if ($challenge !== sha3_512($starttime.'/'.$ip_target.'/'.$answer)) {
  162.                         throw new OIDplusException(_L('Wrong answer'));
  163.                 } else if (!file_exists($open_trans_file)) {
  164.                         throw new OIDplusException(_L('Challenge submitted twice or transaction missing'));
  165.                 } else {
  166.                         @unlink($open_trans_file);
  167.                 }
  168.         }
  169.  
  170.         /**
  171.          * @return string
  172.          */
  173.         public static function setupHTML(): string {
  174.                 return '<div id="CAPTCHAPLUGIN_PARAMS_VtsClientChallenge">'.
  175.                        '<p>'._L('ViaThinkSoft Client Challenge lets the client computer solve a cryptographic problem instead of letting the user solve a CAPTCHA. This slows down brute-force attacks.').'</p>'.
  176.                        '</div>';
  177.         }
  178.  
  179. }
  180.