|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <unordered_map> |
| 4 | +#include <string> |
| 5 | +#include <algorithm> |
| 6 | +#include <limits> |
| 7 | + |
| 8 | +#include "jmutex.hpp" |
| 9 | +#include "jutil.hpp" |
| 10 | + |
| 11 | +struct FailedAuthEntry |
| 12 | +{ |
| 13 | + unsigned firstFailureTick; |
| 14 | + unsigned failedAttempts; |
| 15 | + |
| 16 | + FailedAuthEntry() : firstFailureTick(0), failedAttempts(0) {} |
| 17 | + FailedAuthEntry(unsigned tick, unsigned attempts) |
| 18 | + : firstFailureTick(tick), failedAttempts(attempts) {} |
| 19 | +}; |
| 20 | + |
| 21 | +// FailedAuthCache is primarily a load-reduction mechanism to prevent repeated failed |
| 22 | +// authentication attempts from hammering the LDAP/Active Directory server with unnecessary |
| 23 | +// traffic and round-trips. Once a configurable threshold of local failures is reached, the cache |
| 24 | +// blocks further attempts for the configured timeout period, avoiding LDAP queries. |
| 25 | +// NOTE: This is NOT the primary lockout mechanism; Active Directory's own account.lockout |
| 26 | +// policy remains authoritative. This cache layer simply reduces network load during failure bursts. |
| 27 | +// IMPORTANT: The TTL is measured from the FIRST failure, not continuously updated on each new failure. |
| 28 | +// This allows automatic recovery: if the underlying AD condition (temporary outage, account unlock, etc.) |
| 29 | +// is fixed within the timeout period, the entry expires and retries are allowed. This prevents permanent |
| 30 | +// blocking of services that are retrying after a transient AD issue. |
| 31 | +class FailedAuthCache |
| 32 | +{ |
| 33 | +public: |
| 34 | + static constexpr unsigned defaultMaxFailedAttempts = 5; |
| 35 | + static constexpr unsigned defaultCacheTimeoutSeconds = 300; // 5 minutes |
| 36 | + static constexpr unsigned defaultMaxAllowedEntries = 25; |
| 37 | + |
| 38 | + FailedAuthCache(unsigned maxFailedAttempts = defaultMaxFailedAttempts, |
| 39 | + unsigned cacheTimeoutSeconds = defaultCacheTimeoutSeconds, |
| 40 | + unsigned maxAllowedEntries = defaultMaxAllowedEntries) |
| 41 | + : m_maxFailedAttempts(maxFailedAttempts), |
| 42 | + m_cacheTimeoutSeconds(cacheTimeoutSeconds), |
| 43 | + m_maxAllowedEntries(maxAllowedEntries) |
| 44 | + { |
| 45 | + } |
| 46 | + |
| 47 | + // Check if a user should be blocked locally to prevent repeated LDAP queries on failure. |
| 48 | + // This is a load-reduction mechanism, not account lockout enforcement. |
| 49 | + // Returns true if the user has exceeded the failed attempt threshold within the timeout window. |
| 50 | + bool isUserLockedOut(const char* username) |
| 51 | + { |
| 52 | + if (!username || !*username) |
| 53 | + return false; |
| 54 | + |
| 55 | + CriticalBlock block(m_lock); |
| 56 | + |
| 57 | + auto it = m_cache.find(username); |
| 58 | + if (it == m_cache.end()) |
| 59 | + return false; |
| 60 | + |
| 61 | + const unsigned currentTick = msTick(); |
| 62 | + if (isExpired(it->second, currentTick)) |
| 63 | + { |
| 64 | + m_cache.erase(it); |
| 65 | + trimFailedAuthCache(); |
| 66 | + return false; |
| 67 | + } |
| 68 | + |
| 69 | + return it->second.failedAttempts >= m_maxFailedAttempts; |
| 70 | + } |
| 71 | + |
| 72 | + // Record a failed authentication attempt for a username to track repeated failures. |
| 73 | + // Used to compute local blocking to reduce LDAP traffic. |
| 74 | + // IMPORTANT: The timeout window is measured from the FIRST failure, not updated on each new failure. |
| 75 | + // This allows automatic recovery if the underlying AD condition (e.g., service outage, password reset) |
| 76 | + // is fixed within the timeout period. Once the timeout expires, the entry resets and retries are allowed. |
| 77 | + // Without this behavior, a service in a failed-auth loop would be permanently blocked even after AD recovers. |
| 78 | + void updateUserLockoutStatus(const char* username) |
| 79 | + { |
| 80 | + if (!username || !*username) |
| 81 | + return; |
| 82 | + |
| 83 | + CriticalBlock block(m_lock); |
| 84 | + |
| 85 | + const unsigned currentTick = msTick(); |
| 86 | + auto it = m_cache.find(username); |
| 87 | + if (it == m_cache.end()) |
| 88 | + { |
| 89 | + m_cache[username] = FailedAuthEntry(currentTick, 1); |
| 90 | + trimFailedAuthCache(); |
| 91 | + return; |
| 92 | + } |
| 93 | + |
| 94 | + if (isExpired(it->second, currentTick)) |
| 95 | + { |
| 96 | + // Timeout expired from first failure; reset to allow retries. |
| 97 | + // If the underlying AD condition (e.g., temporary outage, account unlock) was fixed, |
| 98 | + // the service can now attempt authentication again. |
| 99 | + it->second.firstFailureTick = currentTick; |
| 100 | + it->second.failedAttempts = 1; |
| 101 | + } |
| 102 | + else |
| 103 | + ++(it->second.failedAttempts); |
| 104 | + } |
| 105 | + |
| 106 | + // Remove a user from the failed auth cache (e.g., on successful authentication). |
| 107 | + void removeUser(const char* username) |
| 108 | + { |
| 109 | + if (!username || !*username) |
| 110 | + return; |
| 111 | + |
| 112 | + CriticalBlock block(m_lock); |
| 113 | + |
| 114 | + auto it = m_cache.find(username); |
| 115 | + if (it != m_cache.end()) |
| 116 | + { |
| 117 | + m_cache.erase(it); |
| 118 | + trimFailedAuthCache(); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + // Optional setters/getters |
| 123 | + void setMaxFailedAttempts(unsigned v) { m_maxFailedAttempts = v; } |
| 124 | + void setCacheTimeoutSeconds(unsigned v) { m_cacheTimeoutSeconds = v; } |
| 125 | + void setMaxAllowedEntries(unsigned v) { m_maxAllowedEntries = v; } |
| 126 | + |
| 127 | + unsigned getMaxFailedAttempts() const { return m_maxFailedAttempts; } |
| 128 | + unsigned getCacheTimeoutSeconds() const { return m_cacheTimeoutSeconds; } |
| 129 | + unsigned getMaxAllowedEntries() const { return m_maxAllowedEntries; } |
| 130 | + |
| 131 | + // Clear entire cache |
| 132 | + void clear() |
| 133 | + { |
| 134 | + CriticalBlock block(m_lock); |
| 135 | + m_cache.clear(); |
| 136 | + } |
| 137 | + |
| 138 | +private: |
| 139 | + unsigned queryCacheTimeoutMs() const |
| 140 | + { |
| 141 | + if (m_cacheTimeoutSeconds >= (std::numeric_limits<unsigned>::max() / 1000U)) |
| 142 | + return std::numeric_limits<unsigned>::max(); |
| 143 | + return m_cacheTimeoutSeconds * 1000U; |
| 144 | + } |
| 145 | + |
| 146 | + // Check if a cached entry has expired based on time elapsed since FIRST failure. |
| 147 | + // NOTE: TTL is from firstFailureTick (the initial failure time), NOT updated to the latest failure. |
| 148 | + // This design prevents permanent blocking and allows recovery if the underlying condition is resolved. |
| 149 | + bool isExpired(const FailedAuthEntry &entry, unsigned currentTick) const |
| 150 | + { |
| 151 | + const unsigned elapsedMs = currentTick - entry.firstFailureTick; // unsigned wrap is intentional |
| 152 | + return elapsedMs >= queryCacheTimeoutMs(); |
| 153 | + } |
| 154 | + |
| 155 | + void trimFailedAuthCache() |
| 156 | + { |
| 157 | + // Expect lock is held by caller. |
| 158 | + const unsigned currentTick = msTick(); |
| 159 | + |
| 160 | + // Remove expired entries. |
| 161 | + for (auto it = m_cache.begin(); it != m_cache.end();) |
| 162 | + { |
| 163 | + if (isExpired(it->second, currentTick)) |
| 164 | + it = m_cache.erase(it); |
| 165 | + else |
| 166 | + ++it; |
| 167 | + } |
| 168 | + |
| 169 | + // If still too large, remove oldest entries by age. |
| 170 | + while (m_cache.size() > m_maxAllowedEntries) |
| 171 | + { |
| 172 | + auto oldestIt = std::max_element( |
| 173 | + m_cache.begin(), |
| 174 | + m_cache.end(), |
| 175 | + [currentTick](const auto& a, const auto& b) { |
| 176 | + const unsigned ageA = currentTick - a.second.firstFailureTick; |
| 177 | + const unsigned ageB = currentTick - b.second.firstFailureTick; |
| 178 | + return ageA < ageB; |
| 179 | + }); |
| 180 | + if (oldestIt != m_cache.end()) |
| 181 | + m_cache.erase(oldestIt); |
| 182 | + else |
| 183 | + break; |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | +private: |
| 188 | + std::unordered_map<std::string, FailedAuthEntry> m_cache; |
| 189 | + CriticalSection m_lock; |
| 190 | + |
| 191 | + unsigned m_maxFailedAttempts; |
| 192 | + unsigned m_cacheTimeoutSeconds; |
| 193 | + unsigned m_maxAllowedEntries; |
| 194 | +}; |
0 commit comments