-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthController.php
More file actions
144 lines (118 loc) · 5.04 KB
/
Copy pathAuthController.php
File metadata and controls
144 lines (118 loc) · 5.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
<?php
namespace Kanboard\Plugin\KanboardALTCHA;
use Kanboard\Controller\AuthController as BaseAuthController;
class AuthController extends BaseAuthController
{
/**
* Maximum number of failed login attempts before lockout.
*/
private const MAX_LOGIN_ATTEMPTS = 5;
/**
* Timeout in seconds for the ALTCHA verification API call.
*/
private const API_TIMEOUT = 5;
public function authenticate()
{
// Guard against calling session_start() when a session is already active.
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Rate-limit by IP address (server-side), not by session.
// Session-based counters are trivially reset by the attacker.
$ip = $this->getClientIp();
$attemptKey = 'login_attempts_' . md5($ip);
if (!isset($_SESSION[$attemptKey])) {
$_SESSION[$attemptKey] = 0;
}
if ($_SESSION[$attemptKey] >= self::MAX_LOGIN_ATTEMPTS) {
$this->flash->error(t('Too many login attempts. Please try again later.'));
return false;
}
// If ALTCHA is not configured, skip verification and log a warning.
// This allows the plugin to degrade gracefully during initial setup,
// but operators should treat missing config as a misconfiguration.
if (!defined('ALTCHA_SECRET') || !ALTCHA_SECRET || !defined('ALTCHA_PUBLIC_KEY') || !ALTCHA_PUBLIC_KEY) {
$this->logger->warning('ALTCHA is not configured. Proceeding without ALTCHA verification.');
return parent::authenticate();
}
// Reject immediately if the ALTCHA field was not posted at all.
if (empty($_POST['altcha'])) {
$_SESSION[$attemptKey]++;
$this->flash->error(t('ALTCHA response is missing.'));
return false;
}
// Strip any characters that are not valid in a base64 payload.
// ALTCHA tokens are base64url-encoded JSON; reject anything else.
$response = preg_replace('/[^A-Za-z0-9+\/=_\-]/', '', $_POST['altcha']);
if (empty($response)) {
$_SESSION[$attemptKey]++;
$this->flash->error(t('Invalid ALTCHA response.'));
return false;
}
if (!$this->verifyAltchaResponse($response)) {
$_SESSION[$attemptKey]++;
$safeUsername = str_replace(["\r", "\n", "\t"], '', $this->request->getPost('username'));
$this->logger->error('Invalid ALTCHA response for user: ' . $safeUsername . ' from IP: ' . $ip);
$this->flash->error(t('Invalid ALTCHA response.'));
return false;
}
// Verification passed — prevent session fixation and reset the counter.
session_regenerate_id(true);
$_SESSION[$attemptKey] = 0;
return parent::authenticate();
}
/**
* Call the ALTCHA verification API and return whether the token is valid.
* Returns false on any network or parse error (fail closed).
*/
private function verifyAltchaResponse(string $response): bool
{
$url = 'https://altcha.com/api/verify';
$data = [
'secret' => ALTCHA_SECRET,
'response' => $response,
];
$options = [
'http' => [
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
'timeout' => self::API_TIMEOUT,
// Do not follow redirects for a verification endpoint.
'follow_location' => 0,
],
];
$context = stream_context_create($options);
// Suppress the PHP warning on network failure; we handle false explicitly.
$result = @file_get_contents($url, false, $context);
if ($result === false) {
$this->logger->error('ALTCHA API request failed (network error or timeout).');
return false;
}
$resultJson = json_decode($result, true);
if (!is_array($resultJson)) {
$this->logger->error('ALTCHA API returned non-JSON response.');
return false;
}
return !empty($resultJson['success']);
}
/**
* Return the most specific client IP available, with a safe fallback.
*/
private function getClientIp(): string
{
// Note: X-Forwarded-For can be spoofed if your reverse proxy does not
// strip or overwrite it. Only trust this header if you run behind a
// known proxy that you control.
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// The header may be a comma-separated list; take the first entry.
$ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
} elseif (!empty($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = 'unknown';
}
// Validate that we have something that looks like an IP address.
return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : 'unknown';
}
}