Subversion Repositories oidplus

Rev

Rev 1283 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
709 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
1086 daniel-mar 5
 * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
709 daniel-mar 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
 
1050 daniel-mar 20
namespace ViaThinkSoft\OIDplus;
709 daniel-mar 21
 
1086 daniel-mar 22
// phpcs:disable PSR1.Files.SideEffects
23
\defined('INSIDE_OIDPLUS') or die;
24
// phpcs:enable PSR1.Files.SideEffects
25
 
709 daniel-mar 26
class OIDplusCaptchaPluginVtsClientChallenge extends OIDplusCaptchaPlugin {
27
 
1116 daniel-mar 28
        /**
29
         * @return string
30
         */
709 daniel-mar 31
        public static function id(): string {
32
                return 'ViaThinkSoft Client Challenge';
33
        }
34
 
1116 daniel-mar 35
        /**
36
         * @return bool
37
         */
1016 daniel-mar 38
        public function isVisible(): bool {
709 daniel-mar 39
                return false;
40
        }
41
 
1116 daniel-mar 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);
709 daniel-mar 49
        }
50
 
1116 daniel-mar 51
        /**
1293 daniel-mar 52
         * @param array $params
53
         * @return array
54
         * @throws OIDplusException
55
         */
56
        private function action_GetChallenge(array $params): array {
57
                $offset = 0; // doesn't matter
58
                $min = $offset;
59
                $max = $offset + OIDplus::baseConfig()->getValue('VTS_CAPTCHA_COMPLEXITY', 50000);
60
                if ($max > mt_getrandmax()) $max = mt_getrandmax();
61
 
62
                $starttime = time();
63
                $random = mt_rand($min,$max);
64
                $ip_target = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
65
                $challenge = sha3_512($starttime.'/'.$ip_target.'/'.$random); // $random is secret!
66
                $challenge_integrity = OIDplus::authUtils()->makeAuthKey(['797bfc34-f4fa-11ed-86ca-3c4a92df8582',$challenge]);
67
                $send_to_client = array($starttime, $ip_target, $challenge, $min, $max, $challenge_integrity);
68
 
69
                $open_trans_file = self::getOpenTransFileName($ip_target, $random);
70
                if (@file_put_contents($open_trans_file, '') === false) {
71
                        throw new OIDplusException(_L('Cannot write file %1', $open_trans_file));
72
                }
73
 
74
                return array(
75
                        "status" => 0,
76
                        "challenge" => $send_to_client,
77
                        // Autosolve on=calculate result on page load; off=calculate result on form submit
78
                        "autosolve" => OIDplus::baseConfig()->getValue('VTS_CAPTCHA_AUTOSOLVE', true)
79
                );
80
        }
81
 
82
        /**
1116 daniel-mar 83
         * @param string $actionID
84
         * @param array $params
85
         * @return array
86
         * @throws OIDplusException
87
         */
88
        public function action(string $actionID, array $params): array {
709 daniel-mar 89
                if ($actionID == 'get_challenge') {
1293 daniel-mar 90
                        return $this->action_GetChallenge($params);
1116 daniel-mar 91
                } else {
92
                        return parent::action($actionID, $params);
709 daniel-mar 93
                }
94
        }
95
 
1116 daniel-mar 96
        /**
1130 daniel-mar 97
         * @param string $ip_target
98
         * @param string|int $random
1116 daniel-mar 99
         * @return string
100
         * @throws OIDplusException
101
         */
1130 daniel-mar 102
        private static function getOpenTransFileName(string $ip_target, $random): string {
1022 daniel-mar 103
                $dir = OIDplus::localpath().'/userdata/cache';
104
 
105
                // First, delete challenges which were never completed
106
                $files = glob($dir.'/vts_client_challenge_*.tmp');
107
                $expire = strtotime('-3 DAYS');
108
                foreach ($files as $file) {
109
                        if (!is_file($file)) continue;
110
                        if (filemtime($file) > $expire) continue;
111
                        @unlink($file);
112
                }
113
 
1283 daniel-mar 114
                return $dir.'/vts_client_challenge_'.OIDplus::authUtils()->makeSecret(['461f4a9e-f4fa-11ed-86ca-3c4a92df8582',$ip_target,$random]).'.tmp';
1022 daniel-mar 115
        }
116
 
1116 daniel-mar 117
        /**
118
         * @param string|null $header_text
119
         * @param string|null $footer_text
120
         * @return string
121
         * @throws OIDplusException
122
         */
123
        public function captchaGenerate(string $header_text=null, string $footer_text=null): string {
709 daniel-mar 124
                return '<noscript>'.
1024 daniel-mar 125
                       '<p><font color="red">'._L('You need to enable JavaScript to solve the CAPTCHA.').'</font></p>'.
126
                       '</noscript>'.
127
                       '<input type="hidden" id="vts_validation_result" name="vts_validation_result" value="">'.
128
                       '<script>'.
129
                       'OIDplusCaptchaPluginVtsClientChallenge.captchaShow('.js_escape(OIDplus::webpath(null,OIDplus::PATH_RELATIVE)).');'.
130
                       '</script>';
709 daniel-mar 131
        }
132
 
1116 daniel-mar 133
        /**
134
         * @param array $params
135
         * @param string|null $fieldname
136
         * @return void
137
         * @throws OIDplusException
138
         */
139
        public function captchaVerify(array $params, string $fieldname=null) {
709 daniel-mar 140
 
141
                if (is_null($fieldname)) $fieldname = 'vts_validation_result';
142
 
1024 daniel-mar 143
                if (!isset($params[$fieldname])) throw new OIDplusException(_L('No challenge response found').' (A)');
709 daniel-mar 144
 
1022 daniel-mar 145
                $client_response = @json_decode($params[$fieldname], true);
1024 daniel-mar 146
 
147
                if (!is_array($client_response)) throw new OIDplusException(_L('Challenge response is invalid').' (B)');
148
                if (count($client_response) != 5) throw new OIDplusException(_L('Challenge response is invalid').' (C)');
1022 daniel-mar 149
                list($starttime, $ip_target, $challenge, $answer, $challenge_integrity) = $client_response;
1024 daniel-mar 150
                if (!is_numeric($starttime)) throw new OIDplusException(_L('Challenge response is invalid').' (D)');
151
                if (!is_string($ip_target)) throw new OIDplusException(_L('Challenge response is invalid').' (E)');
152
                if (!is_string($challenge)) throw new OIDplusException(_L('Challenge response is invalid').' (F)');
153
                if (!is_numeric($answer)) throw new OIDplusException(_L('Challenge response is invalid').' (G)');
154
                if (!is_string($challenge_integrity)) throw new OIDplusException(_L('Challenge response is invalid').' (H)');
155
 
1022 daniel-mar 156
                $open_trans_file = self::getOpenTransFileName($ip_target, $answer);
709 daniel-mar 157
 
1130 daniel-mar 158
                $current_ip = ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
1024 daniel-mar 159
                if ($ip_target != $current_ip) {
160
                        throw new OIDplusException(_L('IP address has changed. Please try again. (current IP %1, expected %2)', $current_ip, $ip_target));
1283 daniel-mar 161
                //} else if (time()-$starttime > OIDplus::baseConfig()->getValue('VTS_CAPTCHA_MAXTIME', 10*60/*10 minutes*/)) {
162
                //      throw new OIDplusException(_L('Challenge expired. Please try again.'));
163
                } else if (!OIDplus::authUtils()->validateAuthKey(['797bfc34-f4fa-11ed-86ca-3c4a92df8582',$challenge],$challenge_integrity,OIDplus::baseConfig()->getValue('VTS_CAPTCHA_MAXTIME', 10*60/*10 minutes*/))) {
164
                        throw new OIDplusException(_L('Invalid or expired authentication key'));
709 daniel-mar 165
                } else if ($challenge !== sha3_512($starttime.'/'.$ip_target.'/'.$answer)) {
718 daniel-mar 166
                        throw new OIDplusException(_L('Wrong answer'));
1022 daniel-mar 167
                } else if (!file_exists($open_trans_file)) {
168
                        throw new OIDplusException(_L('Challenge submitted twice or transaction missing'));
169
                } else {
170
                        @unlink($open_trans_file);
709 daniel-mar 171
                }
172
        }
173
 
1116 daniel-mar 174
        /**
175
         * @return string
176
         */
709 daniel-mar 177
        public static function setupHTML(): string {
178
                return '<div id="CAPTCHAPLUGIN_PARAMS_VtsClientChallenge">'.
179
                       '<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>'.
180
                       '</div>';
181
        }
182
 
183
}