Subversion Repositories php_clientchallenge

Rev

Rev 9 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 9 Rev 10
1
<?php
1
<?php
2
 
2
 
3
/*
3
/*
4
 * php_clientchallenge
4
 * php_clientchallenge
5
 * Copyright 2021-2022 Daniel Marschall, ViaThinkSoft
5
 * Copyright 2021-2022 Daniel Marschall, ViaThinkSoft
6
 *
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with 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
9
 * You may obtain a copy of the License at
10
 *
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
17
 * limitations under the License.
18
 */
18
 */
19
 
19
 
20
namespace ViaThinkSoft\RateLimitingChallenge;
20
namespace ViaThinkSoft\RateLimitingChallenge;
21
 
21
 
22
class ClientChallenge {
22
class ClientChallenge {
23
 
23
 
24
        private static function tryDownloadPhpSha3() {
24
        private static function tryDownloadPhpSha3() {
25
                // Download file if required (usually composer should do it)
25
                // Download file if required (usually composer should do it)
26
                if (file_exists(__DIR__.'/Sha3.php')) include_once __DIR__.'/Sha3.php';
26
                if (file_exists(__DIR__.'/Sha3.php')) include_once __DIR__.'/Sha3.php';
27
                if (!class_exists('\bb\Sha3\Sha3')) {
27
                if (!class_exists('\bb\Sha3\Sha3')) {
28
                        $sha3_lib = file_get_contents('https://raw.githubusercontent.com/danielmarschall/php-sha3/master/src/Sha3.php');
28
                        $sha3_lib = file_get_contents('https://raw.githubusercontent.com/danielmarschall/php-sha3/master/src/Sha3.php');
29
                        if (@file_put_contents(__DIR__.'/Sha3.php', $sha3_lib)) {
29
                        if (@file_put_contents(__DIR__.'/Sha3.php', $sha3_lib)) {
30
                                include_once __DIR__.'/Sha3.php';
30
                                include_once __DIR__.'/Sha3.php';
31
                        } else {
31
                        } else {
32
                                eval('?>'.$sha3_lib);
32
                                eval('?>'.$sha3_lib);
33
                        }
33
                        }
34
                }
34
                }
35
        }
35
        }
36
 
36
 
37
        private static function sha3_512($message, $raw_output=false) {
37
        private static function sha3_512($message, $raw_output=false) {
38
                if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
38
                if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
39
                        return hash('sha3-512', $message, $raw_output);
39
                        return hash('sha3-512', $message, $raw_output);
40
                } else {
40
                } else {
41
                        self::tryDownloadPhpSha3();
41
                        self::tryDownloadPhpSha3();
42
                        return \bb\Sha3\Sha3::hash($message, 512, $raw_output);
42
                        return \bb\Sha3\Sha3::hash($message, 512, $raw_output);
43
                }
43
                }
44
        }
44
        }
45
 
45
 
46
        private static function sha3_512_hmac($message, $key, $raw_output=false) {
46
        private static function sha3_512_hmac($message, $key, $raw_output=false) {
47
                // RFC 2104 HMAC
47
                // RFC 2104 HMAC
48
                if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
48
                if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
49
                        return hash_hmac('sha3-512', $message, $key, $raw_output);
49
                        return hash_hmac('sha3-512', $message, $key, $raw_output);
50
                } else {
50
                } else {
51
                        self::tryDownloadPhpSha3();
51
                        self::tryDownloadPhpSha3();
52
                        return \bb\Sha3\Sha3::hash_hmac($message, $key, 512, $raw_output);
52
                        return \bb\Sha3\Sha3::hash_hmac($message, $key, 512, $raw_output);
53
                }
53
                }
54
        }
54
        }
55
 
55
 
56
        private static function getOpenTransFileName($ip_target, $random) {
56
        private static function getOpenTransFileName($ip_target, $random, $server_secret) {
57
                $dir = defined('VTS_CS_OPEN_TRANS_DIR') ? VTS_CS_OPEN_TRANS_DIR : __DIR__.'/cache';
57
                $dir = defined('VTS_CS_OPEN_TRANS_DIR') ? VTS_CS_OPEN_TRANS_DIR : __DIR__.'/cache';
58
                if ($dir == '') $dir = '.'; /** @phpstan-ignore-line */
58
                if ($dir == '') $dir = '.'; /** @phpstan-ignore-line */
59
 
59
 
60
                // First, delete challenges which were never completed
60
                // First, delete challenges which were never completed
61
                $files = glob($dir.'/vts_client_challenge_*.tmp');
61
                $files = glob($dir.'/vts_client_challenge_*.tmp');
62
                $expire = strtotime('-3 DAYS');
62
                $expire = strtotime('-3 DAYS');
63
                foreach ($files as $file) {
63
                foreach ($files as $file) {
64
                        if (!is_file($file)) continue;
64
                        if (!is_file($file)) continue;
65
                        if (filemtime($file) > $expire) continue;
65
                        if (filemtime($file) > $expire) continue;
66
                        @unlink($file);
66
                        @unlink($file);
67
                }
67
                }
68
 
68
 
69
                return $dir.'/vts_client_challenge_'.self::sha3_512($ip_target.'/'.$random).'.tmp';
69
                return $dir.'/vts_client_challenge_'.self::sha3_512_hmac($ip_target.'/'.$random, $server_secret).'.tmp';
70
        }
70
        }
71
 
71
 
72
        public static function checkValidation($client_response, $max_time=10, $server_secret) {
72
        public static function checkValidation($client_response, $max_time=10, $server_secret) {
73
                list($starttime, $ip_target, $challenge, $answer, $challenge_integrity) = $client_response;
73
                list($starttime, $ip_target, $challenge, $answer, $challenge_integrity) = $client_response;
74
                $open_trans_file = self::getOpenTransFileName($ip_target, $answer);
74
                $open_trans_file = self::getOpenTransFileName($ip_target, $answer, $server_secret);
75
 
75
 
76
                if ($ip_target != $_SERVER['REMOTE_ADDR']) {
76
                if ($ip_target != $_SERVER['REMOTE_ADDR']) {
77
                        throw new \Exception('Wrong IP');
77
                        throw new \Exception('Wrong IP');
78
                } else if (time()-$starttime > $max_time) {
78
                } else if (time()-$starttime > $max_time) {
79
                        throw new \Exception('Challenge expired');
79
                        throw new \Exception('Challenge expired');
80
                } else if ($challenge_integrity != self::sha3_512_hmac($challenge,$server_secret)) {
80
                } else if ($challenge_integrity != self::sha3_512_hmac($challenge,$server_secret)) {
81
                        throw new \Exception('Challenge integrity failed');
81
                        throw new \Exception('Challenge integrity failed');
82
                } else if ($challenge !== self::sha3_512($starttime.'/'.$ip_target.'/'.$answer)) {
82
                } else if ($challenge !== self::sha3_512($starttime.'/'.$ip_target.'/'.$answer)) {
83
                        throw new \Exception('Wrong answer');
83
                        throw new \Exception('Wrong answer');
84
                } else if (!file_exists($open_trans_file)) {
84
                } else if (!file_exists($open_trans_file)) {
85
                        throw new \Exception('Challenge submitted twice or transaction missing');
85
                        throw new \Exception('Challenge submitted twice or transaction missing');
86
                } else {
86
                } else {
87
                        @unlink($open_trans_file);
87
                        @unlink($open_trans_file);
88
                        return true;
88
                        return true;
89
                }
89
                }
90
        }
90
        }
91
 
91
 
92
        public static function createChallenge($complexity=50000, $server_secret) {
92
        public static function createChallenge($complexity=50000, $server_secret) {
93
                $offset = 0; // doesn't matter
93
                $offset = 0; // doesn't matter
94
                $min = $offset;
94
                $min = $offset;
95
                $max = $offset + $complexity;
95
                $max = $offset + $complexity;
96
 
96
 
97
                $starttime = time();
97
                $starttime = time();
98
 
98
 
99
                $random = rand($min,$max); // TODO: cryptographic rand
99
                $random = rand($min,$max); // TODO: cryptographic rand
100
 
100
 
101
                $ip_target = $_SERVER['REMOTE_ADDR'];
101
                $ip_target = $_SERVER['REMOTE_ADDR'];
102
 
102
 
103
                $challenge = self::sha3_512($starttime.'/'.$ip_target.'/'.$random);
103
                $challenge = self::sha3_512($starttime.'/'.$ip_target.'/'.$random);
104
 
104
 
105
                $challenge_integrity = self::sha3_512_hmac($challenge,$server_secret);
105
                $challenge_integrity = self::sha3_512_hmac($challenge,$server_secret);
106
 
106
 
107
                $send_to_client = array($starttime, $ip_target, $challenge, $min, $max, $challenge_integrity);
107
                $send_to_client = array($starttime, $ip_target, $challenge, $min, $max, $challenge_integrity);
108
 
108
 
109
                $open_trans_file = self::getOpenTransFileName($ip_target, $random);
109
                $open_trans_file = self::getOpenTransFileName($ip_target, $random, $server_secret);
110
                if (@file_put_contents($open_trans_file, '') === false) {
110
                if (@file_put_contents($open_trans_file, '') === false) {
111
                        throw new \Exception("Cannot write $open_trans_file");
111
                        throw new \Exception("Cannot write $open_trans_file");
112
                }
112
                }
113
 
113
 
114
                return $send_to_client;
114
                return $send_to_client;
115
        }
115
        }
116
 
116
 
117
}
117
}
118
 
118