Added authentication backends: internal, pam and http-headers. fixes #119
This commit is contained in:
@@ -1,8 +1,12 @@
|
||||
|
||||
add_library(lmsauth SHARED
|
||||
impl/AuthTokenService.cpp
|
||||
impl/PasswordService.cpp
|
||||
impl/AuthServiceBase.cpp
|
||||
impl/EnvService.cpp
|
||||
impl/LoginThrottler.cpp
|
||||
impl/PasswordServiceBase.cpp
|
||||
impl/http-headers/HttpHeadersEnvService.cpp
|
||||
impl/internal/InternalPasswordService.cpp
|
||||
)
|
||||
|
||||
target_include_directories(lmsauth INTERFACE
|
||||
@@ -11,6 +15,7 @@ target_include_directories(lmsauth INTERFACE
|
||||
|
||||
target_include_directories(lmsauth PRIVATE
|
||||
include
|
||||
impl
|
||||
)
|
||||
|
||||
target_link_libraries(lmsauth PRIVATE
|
||||
@@ -26,7 +31,7 @@ target_link_libraries(lmsauth PUBLIC
|
||||
|
||||
if (USE_PAM)
|
||||
target_compile_options(lmsauth PRIVATE "-DLMS_SUPPORT_PAM")
|
||||
target_sources(lmsauth PRIVATE impl/pam/PAM.cpp)
|
||||
target_sources(lmsauth PRIVATE impl/pam/PAMPasswordService.cpp)
|
||||
target_include_directories(lmsauth PRIVATE ${PAM_INCLUDE_DIR})
|
||||
target_link_libraries(lmsauth PRIVATE ${PAM_LIBRARIES})
|
||||
endif (USE_PAM)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright (C) 2021 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "AuthServiceBase.hpp"
|
||||
|
||||
#include "database/Session.hpp"
|
||||
#include "database/User.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
Database::IdType
|
||||
AuthServiceBase::getOrCreateUser(Database::Session& session, std::string_view loginName)
|
||||
{
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
|
||||
Database::User::pointer user {Database::User::getByLoginName(session, loginName)};
|
||||
if (!user)
|
||||
{
|
||||
const Database::User::Type type {Database::User::getCount(session) == 0 ? Database::User::Type::ADMIN : Database::User::Type::REGULAR};
|
||||
|
||||
LMS_LOG(AUTH, DEBUG) << "Creating user '" << loginName << "', admin = " << (type == Database::User::Type::ADMIN);
|
||||
|
||||
user = Database::User::create(session, loginName);
|
||||
user.modify()->setType(type);
|
||||
}
|
||||
|
||||
return user.id();
|
||||
}
|
||||
|
||||
void
|
||||
AuthServiceBase::onUserAuthenticated(Database::Session& session, Database::IdType userId)
|
||||
{
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
Database::User::pointer user {Database::User::getById(session, userId)};
|
||||
if (user)
|
||||
user.modify()->setLastLogin(Wt::WDateTime::currentDateTime());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (C) 2021 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
#include "database/Types.hpp"
|
||||
|
||||
namespace Database
|
||||
{
|
||||
class Session;
|
||||
}
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
class AuthServiceBase
|
||||
{
|
||||
protected:
|
||||
Database::IdType getOrCreateUser(Database::Session& session, std::string_view loginName);
|
||||
void onUserAuthenticated(Database::Session& session, Database::IdType userId);
|
||||
};
|
||||
}
|
||||
@@ -23,103 +23,115 @@
|
||||
#include <Wt/Auth/PasswordStrengthValidator.h>
|
||||
#include <Wt/WRandom.h>
|
||||
|
||||
#include "auth/Types.hpp"
|
||||
#include "database/Session.hpp"
|
||||
#include "database/User.hpp"
|
||||
#include "utils/Exception.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
|
||||
namespace Auth {
|
||||
|
||||
std::unique_ptr<IAuthTokenService> createAuthTokenService(std::size_t maxThrottlerEntries)
|
||||
namespace Auth
|
||||
{
|
||||
return std::make_unique<AuthTokenService>(maxThrottlerEntries);
|
||||
}
|
||||
|
||||
static const Wt::Auth::SHA1HashFunction sha1Function;
|
||||
|
||||
AuthTokenService::AuthTokenService(std::size_t maxThrottlerEntries)
|
||||
: _loginThrottler {maxThrottlerEntries}
|
||||
{
|
||||
}
|
||||
|
||||
std::string
|
||||
AuthTokenService::createAuthToken(Database::Session& session, Database::IdType userId, const Wt::WDateTime& expiry)
|
||||
{
|
||||
const std::string secret {Wt::WRandom::generateId(32)};
|
||||
const std::string secretHash {sha1Function.compute(secret, {})};
|
||||
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
|
||||
Database::User::pointer user {Database::User::getById(session, userId)};
|
||||
if (!user)
|
||||
throw LmsException {"User deleted"};
|
||||
|
||||
Database::AuthToken::pointer authToken {Database::AuthToken::create(session, secretHash, expiry, user)};
|
||||
|
||||
LMS_LOG(UI, DEBUG) << "Created auth token for user '" << user->getLoginName() << "', expiry = " << expiry.toString();
|
||||
|
||||
if (user->getAuthTokensCount() >= 50)
|
||||
Database::AuthToken::removeExpiredTokens(session, Wt::WDateTime::currentDateTime());
|
||||
|
||||
return secret;
|
||||
}
|
||||
|
||||
static
|
||||
std::optional<AuthTokenService::AuthTokenProcessResult::AuthTokenInfo>
|
||||
processAuthToken(Database::Session& session, const std::string& secret)
|
||||
{
|
||||
const std::string secretHash {sha1Function.compute(secret, {})};
|
||||
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
|
||||
Database::AuthToken::pointer authToken {Database::AuthToken::getByValue(session, secretHash)};
|
||||
if (!authToken)
|
||||
return std::nullopt;
|
||||
|
||||
if (authToken->getExpiry() < Wt::WDateTime::currentDateTime())
|
||||
std::unique_ptr<IAuthTokenService> createAuthTokenService(std::size_t maxThrottlerEntries)
|
||||
{
|
||||
authToken.remove();
|
||||
return std::nullopt;
|
||||
return std::make_unique<AuthTokenService>(maxThrottlerEntries);
|
||||
}
|
||||
|
||||
LMS_LOG(UI, DEBUG) << "Found auth token for user '" << authToken->getUser()->getLoginName() << "'!";
|
||||
static const Wt::Auth::SHA1HashFunction sha1Function;
|
||||
|
||||
AuthTokenService::AuthTokenProcessResult::AuthTokenInfo res {authToken->getUser().id(), authToken->getExpiry()};
|
||||
authToken.remove();
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
AuthTokenService::AuthTokenProcessResult
|
||||
AuthTokenService::processAuthToken(Database::Session& session, const boost::asio::ip::address& clientAddress, const std::string& tokenValue)
|
||||
{
|
||||
// Do not waste too much resource on brute force attacks (optim)
|
||||
AuthTokenService::AuthTokenService(std::size_t maxThrottlerEntries)
|
||||
: _loginThrottler {maxThrottlerEntries}
|
||||
{
|
||||
std::shared_lock<std::shared_timed_mutex> lock {_mutex};
|
||||
|
||||
if (_loginThrottler.isClientThrottled(clientAddress))
|
||||
return AuthTokenProcessResult {AuthTokenProcessResult::State::Throttled};
|
||||
}
|
||||
|
||||
auto res {Auth::processAuthToken(session, tokenValue)};
|
||||
std::string
|
||||
AuthTokenService::createAuthToken(Database::Session& session, Database::IdType userId, const Wt::WDateTime& expiry)
|
||||
{
|
||||
std::unique_lock<std::shared_timed_mutex> lock {_mutex};
|
||||
const std::string secret {Wt::WRandom::generateId(32)};
|
||||
const std::string secretHash {sha1Function.compute(secret, {})};
|
||||
|
||||
if (_loginThrottler.isClientThrottled(clientAddress))
|
||||
return AuthTokenProcessResult {AuthTokenProcessResult::State::Throttled};
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
|
||||
if (!res)
|
||||
Database::User::pointer user {Database::User::getById(session, userId)};
|
||||
if (!user)
|
||||
throw Exception {"User deleted"};
|
||||
|
||||
Database::AuthToken::pointer authToken {Database::AuthToken::create(session, secretHash, expiry, user)};
|
||||
|
||||
LMS_LOG(UI, DEBUG) << "Created auth token for user '" << user->getLoginName() << "', expiry = " << expiry.toString();
|
||||
|
||||
if (user->getAuthTokensCount() >= 50)
|
||||
Database::AuthToken::removeExpiredTokens(session, Wt::WDateTime::currentDateTime());
|
||||
|
||||
return secret;
|
||||
}
|
||||
|
||||
static
|
||||
std::optional<AuthTokenService::AuthTokenProcessResult::AuthTokenInfo>
|
||||
processAuthToken(Database::Session& session, std::string_view secret)
|
||||
{
|
||||
const std::string secretHash {sha1Function.compute(std::string {secret}, {})};
|
||||
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
|
||||
Database::AuthToken::pointer authToken {Database::AuthToken::getByValue(session, secretHash)};
|
||||
if (!authToken)
|
||||
return std::nullopt;
|
||||
|
||||
if (authToken->getExpiry() < Wt::WDateTime::currentDateTime())
|
||||
{
|
||||
_loginThrottler.onBadClientAttempt(clientAddress);
|
||||
return AuthTokenProcessResult {AuthTokenProcessResult::State::NotFound};
|
||||
authToken.remove();
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
_loginThrottler.onGoodClientAttempt(clientAddress);
|
||||
return AuthTokenProcessResult {AuthTokenProcessResult::State::Found, std::move(*res)};
|
||||
}
|
||||
}
|
||||
LMS_LOG(UI, DEBUG) << "Found auth token for user '" << authToken->getUser()->getLoginName() << "'!";
|
||||
|
||||
AuthTokenService::AuthTokenProcessResult::AuthTokenInfo res {authToken->getUser().id(), authToken->getExpiry()};
|
||||
authToken.remove();
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
AuthTokenService::AuthTokenProcessResult
|
||||
AuthTokenService::processAuthToken(Database::Session& session, const boost::asio::ip::address& clientAddress, std::string_view tokenValue)
|
||||
{
|
||||
// Do not waste too much resource on brute force attacks (optim)
|
||||
{
|
||||
std::shared_lock lock {_mutex};
|
||||
|
||||
if (_loginThrottler.isClientThrottled(clientAddress))
|
||||
return AuthTokenProcessResult {AuthTokenProcessResult::State::Throttled};
|
||||
}
|
||||
|
||||
auto res {Auth::processAuthToken(session, tokenValue)};
|
||||
{
|
||||
std::unique_lock lock {_mutex};
|
||||
|
||||
if (_loginThrottler.isClientThrottled(clientAddress))
|
||||
return AuthTokenProcessResult {AuthTokenProcessResult::State::Throttled};
|
||||
|
||||
if (!res)
|
||||
{
|
||||
_loginThrottler.onBadClientAttempt(clientAddress);
|
||||
return AuthTokenProcessResult {AuthTokenProcessResult::State::Denied};
|
||||
}
|
||||
|
||||
_loginThrottler.onGoodClientAttempt(clientAddress);
|
||||
onUserAuthenticated(session, res->userId);
|
||||
return AuthTokenProcessResult {AuthTokenProcessResult::State::Granted, std::move(*res)};
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
AuthTokenService::clearAuthTokens(Database::Session& session, Database::IdType userId)
|
||||
{
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
|
||||
Database::User::pointer user {Database::User::getById(session, userId)};
|
||||
if (!user)
|
||||
throw Exception {"User deleted"};
|
||||
|
||||
user.modify()->clearAuthTokens();
|
||||
}
|
||||
|
||||
} // namespace Auth
|
||||
|
||||
|
||||
@@ -19,8 +19,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "auth/IAuthTokenService.hpp"
|
||||
#include <shared_mutex>
|
||||
|
||||
#include "auth/IAuthTokenService.hpp"
|
||||
#include "AuthServiceBase.hpp"
|
||||
#include "LoginThrottler.hpp"
|
||||
|
||||
namespace Database
|
||||
@@ -28,13 +30,11 @@ namespace Database
|
||||
class Session;
|
||||
}
|
||||
|
||||
|
||||
namespace Auth {
|
||||
|
||||
class AuthTokenService : public IAuthTokenService
|
||||
namespace Auth
|
||||
{
|
||||
class AuthTokenService : public IAuthTokenService, public AuthServiceBase
|
||||
{
|
||||
public:
|
||||
|
||||
AuthTokenService(std::size_t maxThrottlerEntries);
|
||||
|
||||
AuthTokenService(const AuthTokenService&) = delete;
|
||||
@@ -42,14 +42,12 @@ namespace Auth {
|
||||
AuthTokenService(AuthTokenService&&) = delete;
|
||||
AuthTokenService& operator=(AuthTokenService&&) = delete;
|
||||
|
||||
AuthTokenProcessResult processAuthToken(Database::Session& session, const boost::asio::ip::address& clientAddress, const std::string& tokenValue) override;
|
||||
std::string createAuthToken(Database::Session& session, Database::IdType userid, const Wt::WDateTime& expiry) override;
|
||||
|
||||
private:
|
||||
AuthTokenProcessResult processAuthToken(Database::Session& session, const boost::asio::ip::address& clientAddress, std::string_view tokenValue) override;
|
||||
std::string createAuthToken(Database::Session& session, Database::IdType userId, const Wt::WDateTime& expiry) override;
|
||||
void clearAuthTokens(Database::Session& session, Database::IdType userId) override;
|
||||
|
||||
std::shared_timed_mutex _mutex;
|
||||
LoginThrottler _loginThrottler;
|
||||
std::shared_mutex _mutex;
|
||||
LoginThrottler _loginThrottler;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright (C) 2021 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "auth/IEnvService.hpp"
|
||||
|
||||
#include "auth/Types.hpp"
|
||||
#include "http-headers/HttpHeadersEnvService.hpp"
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
std::unique_ptr<IEnvService>
|
||||
createEnvService(std::string_view backendName)
|
||||
{
|
||||
if (backendName == "http-headers")
|
||||
return std::make_unique<HttpHeadersEnvService>();
|
||||
|
||||
throw Exception {"Authentication backend '" + std::string {backendName} + "' is not supported!"};
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2019 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "PasswordService.hpp"
|
||||
|
||||
#include <Wt/Auth/HashFunction.h>
|
||||
#include <Wt/Auth/PasswordStrengthValidator.h>
|
||||
#include <Wt/WRandom.h>
|
||||
|
||||
#include "database/Session.hpp"
|
||||
#include "utils/Exception.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
#include "pam/PAM.hpp"
|
||||
#endif
|
||||
|
||||
namespace Auth {
|
||||
|
||||
std::unique_ptr<IPasswordService> createPasswordService(std::size_t maxThrottlerEntries)
|
||||
{
|
||||
return std::make_unique<PasswordService>(maxThrottlerEntries);
|
||||
}
|
||||
|
||||
PasswordService::PasswordService(std::size_t maxThrottlerEntries)
|
||||
: _loginThrottler{maxThrottlerEntries}
|
||||
{
|
||||
}
|
||||
|
||||
bool
|
||||
PasswordService::isAuthModeSupported(Database::User::AuthMode authMode) const
|
||||
{
|
||||
switch (authMode)
|
||||
{
|
||||
case Database::User::AuthMode::Internal:
|
||||
return true;
|
||||
|
||||
case Database::User::AuthMode::PAM:
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static
|
||||
bool
|
||||
checkUserPassword(Database::Session& session, const std::string& loginName, const std::string& password)
|
||||
{
|
||||
Database::User::AuthMode authMode;
|
||||
Database::User::PasswordHash passwordHash;
|
||||
{
|
||||
auto transaction {session.createSharedTransaction()};
|
||||
|
||||
const Database::User::pointer user {Database::User::getByLoginName(session, loginName)};
|
||||
if (!user)
|
||||
return false;
|
||||
|
||||
authMode = user->getAuthMode();
|
||||
passwordHash = user->getPasswordHash();
|
||||
}
|
||||
|
||||
switch (authMode)
|
||||
{
|
||||
case Database::User::AuthMode::Internal:
|
||||
{
|
||||
LMS_LOG(AUTH, DEBUG) << "Checking internal password for user '" << loginName << "'";
|
||||
const Wt::Auth::BCryptHashFunction hashFunc {7}; // TODO parametrize this
|
||||
return hashFunc.verify(password, passwordHash.salt, passwordHash.hash);
|
||||
}
|
||||
|
||||
case Database::User::AuthMode::PAM:
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
return PAM::checkUserPassword(loginName, password);
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
PasswordService::PasswordCheckResult
|
||||
PasswordService::checkUserPassword(Database::Session& session, const boost::asio::ip::address& clientAddress, const std::string& loginName, const std::string& password)
|
||||
{
|
||||
// Do not waste too much resource on brute force attacks (optim)
|
||||
{
|
||||
std::shared_lock<std::shared_timed_mutex> lock {_mutex};
|
||||
|
||||
if (_loginThrottler.isClientThrottled(clientAddress))
|
||||
return PasswordCheckResult::Throttled;
|
||||
}
|
||||
|
||||
const bool match {Auth::checkUserPassword(session, loginName, password)};
|
||||
{
|
||||
std::unique_lock<std::shared_timed_mutex> lock {_mutex};
|
||||
|
||||
if (_loginThrottler.isClientThrottled(clientAddress))
|
||||
return PasswordCheckResult::Throttled;
|
||||
|
||||
if (match)
|
||||
{
|
||||
_loginThrottler.onGoodClientAttempt(clientAddress);
|
||||
return PasswordCheckResult::Match;
|
||||
}
|
||||
else
|
||||
{
|
||||
_loginThrottler.onBadClientAttempt(clientAddress);
|
||||
return PasswordCheckResult::Mismatch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Database::User::PasswordHash
|
||||
PasswordService::hashPassword(const std::string& password) const
|
||||
{
|
||||
const std::string salt {Wt::WRandom::generateId(32)};
|
||||
|
||||
const Wt::Auth::BCryptHashFunction hashFunc {6};
|
||||
return {salt, hashFunc.compute(password, salt)};
|
||||
}
|
||||
|
||||
bool
|
||||
PasswordService::evaluatePasswordStrength(const std::string& loginName, const std::string& password) const
|
||||
{
|
||||
Wt::Auth::PasswordStrengthValidator validator;
|
||||
validator.setMinimumLength(Wt::Auth::PasswordStrengthType::OneCharClass, 4);
|
||||
validator.setMinimumLength(Wt::Auth::PasswordStrengthType::TwoCharClass, 4);
|
||||
validator.setMinimumLength(Wt::Auth::PasswordStrengthType::PassPhrase, 4);
|
||||
validator.setMinimumLength(Wt::Auth::PasswordStrengthType::ThreeCharClass, 4);
|
||||
validator.setMinimumLength(Wt::Auth::PasswordStrengthType::FourCharClass, 4);
|
||||
validator.setMinimumPassPhraseWords(1);
|
||||
validator.setMinimumMatchLength(3);
|
||||
|
||||
return validator.evaluateStrength(password, loginName, "").isValid();
|
||||
}
|
||||
|
||||
} // namespace Auth
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2019 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <shared_mutex>
|
||||
#include "auth/IPasswordService.hpp"
|
||||
|
||||
#include "LoginThrottler.hpp"
|
||||
|
||||
namespace Database
|
||||
{
|
||||
class Session;
|
||||
}
|
||||
|
||||
|
||||
namespace Auth {
|
||||
|
||||
class PasswordService : public IPasswordService
|
||||
{
|
||||
public:
|
||||
|
||||
PasswordService(std::size_t maxThrottlerEntries);
|
||||
|
||||
PasswordService(const PasswordService&) = delete;
|
||||
PasswordService& operator=(const PasswordService&) = delete;
|
||||
PasswordService(PasswordService&&) = delete;
|
||||
PasswordService& operator=(PasswordService&&) = delete;
|
||||
|
||||
private:
|
||||
|
||||
bool isAuthModeSupported(Database::User::AuthMode authMode) const override;
|
||||
PasswordCheckResult checkUserPassword(Database::Session& session, const boost::asio::ip::address& clientAddress, const std::string& loginName, const std::string& password) override;
|
||||
Database::User::PasswordHash hashPassword(const std::string& password) const override;
|
||||
bool evaluatePasswordStrength(const std::string& loginName, const std::string& password) const override;
|
||||
|
||||
std::shared_timed_mutex _mutex;
|
||||
LoginThrottler _loginThrottler;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Copyright (C) 2019 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "PasswordServiceBase.hpp"
|
||||
|
||||
#include <Wt/Auth/HashFunction.h>
|
||||
#include <Wt/WRandom.h>
|
||||
|
||||
#include "internal/InternalPasswordService.hpp"
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
#include "pam/PAMPasswordService.hpp"
|
||||
#endif // LMS_SUPPORT_PAM
|
||||
|
||||
#include "auth/Types.hpp"
|
||||
#include "database/Session.hpp"
|
||||
#include "database/User.hpp"
|
||||
#include "utils/Exception.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
|
||||
static const Wt::Auth::SHA1HashFunction sha1Function;
|
||||
|
||||
std::unique_ptr<IPasswordService>
|
||||
createPasswordService(std::string_view passwordAuthenticationBackend, std::size_t maxThrottlerEntries, IAuthTokenService& authTokenService)
|
||||
{
|
||||
if (passwordAuthenticationBackend == "internal")
|
||||
return std::make_unique<InternalPasswordService>(maxThrottlerEntries, authTokenService);
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
else if (passwordAuthenticationBackend == "pam")
|
||||
return std::make_unique<PAMPasswordService>(maxThrottlerEntries, authTokenService);
|
||||
#endif // LMS_SUPPORT_PAM
|
||||
|
||||
throw Exception {"Authentication backend '" + std::string {passwordAuthenticationBackend} + "' is not supported!"};
|
||||
}
|
||||
|
||||
PasswordServiceBase::PasswordServiceBase(std::size_t maxThrottlerEntries, IAuthTokenService& authTokenService)
|
||||
: _loginThrottler {maxThrottlerEntries}
|
||||
, _authTokenService {authTokenService}
|
||||
{
|
||||
}
|
||||
|
||||
PasswordServiceBase::CheckResult
|
||||
PasswordServiceBase::checkUserPassword(Database::Session& session,
|
||||
const boost::asio::ip::address& clientAddress,
|
||||
std::string_view loginName,
|
||||
std::string_view password)
|
||||
{
|
||||
LMS_LOG(AUTH, DEBUG) << "Checking password for user '" << loginName << "'";
|
||||
|
||||
// Do not waste too much resource on brute force attacks (optim)
|
||||
{
|
||||
std::shared_lock lock {_mutex};
|
||||
|
||||
if (_loginThrottler.isClientThrottled(clientAddress))
|
||||
return {CheckResult::State::Throttled};
|
||||
}
|
||||
|
||||
const bool match {checkUserPassword(session, loginName, password)};
|
||||
{
|
||||
std::unique_lock lock {_mutex};
|
||||
|
||||
if (_loginThrottler.isClientThrottled(clientAddress))
|
||||
return {CheckResult::State::Throttled};
|
||||
|
||||
if (match)
|
||||
{
|
||||
_loginThrottler.onGoodClientAttempt(clientAddress);
|
||||
|
||||
const Database::IdType userId {getOrCreateUser(session, loginName)};
|
||||
onUserAuthenticated(session, userId);
|
||||
return {CheckResult::State::Granted, userId};
|
||||
}
|
||||
else
|
||||
{
|
||||
_loginThrottler.onBadClientAttempt(clientAddress);
|
||||
return {CheckResult::State::Denied};
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace Auth
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (C) 2019 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <shared_mutex>
|
||||
|
||||
#include "auth/IPasswordService.hpp"
|
||||
#include "AuthServiceBase.hpp"
|
||||
#include "LoginThrottler.hpp"
|
||||
|
||||
namespace Database
|
||||
{
|
||||
class Session;
|
||||
}
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
|
||||
class PasswordServiceBase : public IPasswordService, public AuthServiceBase
|
||||
{
|
||||
public:
|
||||
PasswordServiceBase(std::size_t maxThrottlerEntries, IAuthTokenService& authTokenService);
|
||||
|
||||
PasswordServiceBase(const PasswordServiceBase&) = delete;
|
||||
PasswordServiceBase& operator=(const PasswordServiceBase&) = delete;
|
||||
PasswordServiceBase(PasswordServiceBase&&) = delete;
|
||||
PasswordServiceBase& operator=(PasswordServiceBase&&) = delete;
|
||||
|
||||
protected:
|
||||
IAuthTokenService& getAuthTokenService() { return _authTokenService; }
|
||||
|
||||
private:
|
||||
virtual bool checkUserPassword(Database::Session& session,
|
||||
std::string_view loginName,
|
||||
std::string_view password) = 0;
|
||||
|
||||
CheckResult checkUserPassword(Database::Session& session,
|
||||
const boost::asio::ip::address& clientAddress,
|
||||
std::string_view loginName,
|
||||
std::string_view password) override;
|
||||
|
||||
std::shared_mutex _mutex;
|
||||
LoginThrottler _loginThrottler;
|
||||
IAuthTokenService& _authTokenService;
|
||||
};
|
||||
|
||||
} // namespace Auth
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright (C) 2021 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "HttpHeadersEnvService.hpp"
|
||||
|
||||
#include <Wt/WEnvironment.h>
|
||||
|
||||
#include "utils/IConfig.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
#include "utils/Service.hpp"
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
|
||||
HttpHeadersEnvService::HttpHeadersEnvService()
|
||||
: _fieldName {Service<IConfig>::get()->getString("http-headers-field-name", "X-Forwarded-User")}
|
||||
{
|
||||
LMS_LOG(AUTH, INFO) << "Using http header field = '" << _fieldName << "'";
|
||||
}
|
||||
|
||||
HttpHeadersEnvService::CheckResult
|
||||
HttpHeadersEnvService::processEnv(Database::Session& session, const Wt::WEnvironment& env)
|
||||
{
|
||||
const std::string loginName { env.headerValue(_fieldName)};
|
||||
if (loginName.empty())
|
||||
return {CheckResult::State::Denied};
|
||||
|
||||
LMS_LOG(AUTH, DEBUG) << "Extracted login name = '" << loginName << "' from HTTP header";
|
||||
|
||||
const Database::IdType userId {getOrCreateUser(session, loginName)};
|
||||
onUserAuthenticated(session, userId);
|
||||
return {CheckResult::State::Granted, userId};
|
||||
}
|
||||
|
||||
} // namespace Auth
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright (C) 2021 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "auth/IEnvService.hpp"
|
||||
#include "AuthServiceBase.hpp"
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
class HttpHeadersEnvService : public IEnvService, public AuthServiceBase
|
||||
{
|
||||
public:
|
||||
HttpHeadersEnvService();
|
||||
|
||||
private:
|
||||
CheckResult processEnv(Database::Session& session, const Wt::WEnvironment& env) override;
|
||||
|
||||
std::string _fieldName;
|
||||
};
|
||||
|
||||
} // namespace Auth
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright (C) 2019 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "InternalPasswordService.hpp"
|
||||
#include <Wt/WRandom.h>
|
||||
|
||||
#include "auth/IAuthTokenService.hpp"
|
||||
#include "auth/Types.hpp"
|
||||
#include "database/Session.hpp"
|
||||
#include "database/User.hpp"
|
||||
#include "utils/Exception.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
InternalPasswordService::InternalPasswordService(std::size_t maxThrottlerEntries, IAuthTokenService& authTokenService)
|
||||
: PasswordServiceBase {maxThrottlerEntries, authTokenService}
|
||||
{
|
||||
_validator.setMinimumLength(Wt::Auth::PasswordStrengthType::OneCharClass, 4);
|
||||
_validator.setMinimumLength(Wt::Auth::PasswordStrengthType::TwoCharClass, 4);
|
||||
_validator.setMinimumLength(Wt::Auth::PasswordStrengthType::PassPhrase, 4);
|
||||
_validator.setMinimumLength(Wt::Auth::PasswordStrengthType::ThreeCharClass, 4);
|
||||
_validator.setMinimumLength(Wt::Auth::PasswordStrengthType::FourCharClass, 4);
|
||||
_validator.setMinimumPassPhraseWords(1);
|
||||
_validator.setMinimumMatchLength(3);
|
||||
}
|
||||
|
||||
bool
|
||||
InternalPasswordService::checkUserPassword(Database::Session& session,
|
||||
std::string_view loginName,
|
||||
std::string_view password)
|
||||
{
|
||||
LMS_LOG(AUTH, DEBUG) << "Checking internal password for user '" << loginName << "'";
|
||||
|
||||
Database::User::PasswordHash passwordHash;
|
||||
{
|
||||
auto transaction {session.createSharedTransaction()};
|
||||
|
||||
const Database::User::pointer user {Database::User::getByLoginName(session, loginName)};
|
||||
if (!user)
|
||||
{
|
||||
LMS_LOG(AUTH, DEBUG) << "hashing random stuff";
|
||||
// hash random stuff here to waste some time
|
||||
hashRandomPassword();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Don't allow users being created or coming from other backends
|
||||
passwordHash = user->getPasswordHash();
|
||||
if (passwordHash.salt.empty() || passwordHash.hash.empty())
|
||||
{
|
||||
// hash random stuff here to waste some time
|
||||
hashRandomPassword();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return _hashFunc.verify(std::string {password}, std::string {passwordHash.salt}, std::string {passwordHash.hash});
|
||||
}
|
||||
|
||||
bool
|
||||
InternalPasswordService::canSetPasswords() const
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
InternalPasswordService::isPasswordSecureEnough(std::string_view loginName, std::string_view password) const
|
||||
{
|
||||
return _validator.evaluateStrength(std::string {password}, std::string {loginName}, "").isValid();
|
||||
}
|
||||
|
||||
void
|
||||
InternalPasswordService::setPassword(Database::Session& session, Database::IdType userId, std::string_view newPassword)
|
||||
{
|
||||
const Database::User::PasswordHash passwordHash {hashPassword(newPassword)};
|
||||
|
||||
auto transaction {session.createUniqueTransaction()};
|
||||
|
||||
const Database::User::pointer user {Database::User::getById(session, userId)};
|
||||
if (!user)
|
||||
throw Exception {"User not found!"};
|
||||
|
||||
if (!isPasswordSecureEnough(user->getLoginName(), newPassword))
|
||||
throw PasswordTooWeakException {};
|
||||
|
||||
user.modify()->setPasswordHash(passwordHash);
|
||||
getAuthTokenService().clearAuthTokens(session, userId);
|
||||
}
|
||||
|
||||
Database::User::PasswordHash
|
||||
InternalPasswordService::hashPassword(std::string_view password) const
|
||||
{
|
||||
const std::string salt {Wt::WRandom::generateId(32)};
|
||||
|
||||
return {salt, _hashFunc.compute(std::string {password}, salt)};
|
||||
}
|
||||
|
||||
void
|
||||
InternalPasswordService::hashRandomPassword() const
|
||||
{
|
||||
hashPassword(Wt::WRandom::generateId(32));
|
||||
}
|
||||
|
||||
} // namespace Auth
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright (C) 2021 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Wt/Auth/HashFunction.h>
|
||||
#include <Wt/Auth/PasswordStrengthValidator.h>
|
||||
|
||||
#include "database/User.hpp"
|
||||
#include "PasswordServiceBase.hpp"
|
||||
#include "LoginThrottler.hpp"
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
class IAuthTokenService;
|
||||
|
||||
class InternalPasswordService : public PasswordServiceBase
|
||||
{
|
||||
public:
|
||||
InternalPasswordService(std::size_t maxThrottlerEntries, IAuthTokenService& authTokenService);
|
||||
|
||||
private:
|
||||
|
||||
bool checkUserPassword(Database::Session& session,
|
||||
std::string_view loginName,
|
||||
std::string_view password) override;
|
||||
|
||||
bool canSetPasswords() const override;
|
||||
bool isPasswordSecureEnough(std::string_view loginName, std::string_view password) const override;
|
||||
void setPassword(Database::Session& session, Database::IdType userId, std::string_view newPassword) override;
|
||||
|
||||
Database::User::PasswordHash hashPassword(std::string_view password) const;
|
||||
void hashRandomPassword() const;
|
||||
|
||||
const Wt::Auth::BCryptHashFunction _hashFunc {7}; // TODO parametrize this
|
||||
Wt::Auth::PasswordStrengthValidator _validator;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2020 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "PAM.hpp"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "utils/Exception.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
|
||||
#include <security/pam_appl.h>
|
||||
|
||||
namespace Auth::PAM
|
||||
{
|
||||
|
||||
class PAMError
|
||||
{
|
||||
public:
|
||||
PAMError(std::string_view msg, pam_handle_t *pamh, int err)
|
||||
{
|
||||
_errorMsg = std::string {msg} + ": " + pam_strerror(pamh, err);
|
||||
}
|
||||
|
||||
std::string_view message() const { return _errorMsg; }
|
||||
|
||||
private:
|
||||
std::string _errorMsg;
|
||||
};
|
||||
|
||||
class PAMContext
|
||||
{
|
||||
public:
|
||||
PAMContext(std::string_view loginName)
|
||||
{
|
||||
int err {pam_start("lms", std::string {loginName}.c_str(), &_conv, &_pamh)};
|
||||
if (err != PAM_SUCCESS)
|
||||
throw PAMError {"start failed", _pamh, err};
|
||||
}
|
||||
|
||||
~PAMContext()
|
||||
{
|
||||
int err {pam_end(_pamh, 0)};
|
||||
if (err != PAM_SUCCESS)
|
||||
LMS_LOG(AUTH, ERROR) << "end failed: " << pam_strerror(_pamh, err);
|
||||
}
|
||||
|
||||
void authenticate(std::string_view password)
|
||||
{
|
||||
AuthenticateConvContext authContext {password};
|
||||
ScopedConvContextSetter scopedContext {*this, authContext};
|
||||
|
||||
int err {pam_authenticate(_pamh, 0)};
|
||||
if (err != PAM_SUCCESS)
|
||||
throw PAMError {"authenticate failed", _pamh, err};
|
||||
}
|
||||
|
||||
void validateAccount()
|
||||
{
|
||||
int err {pam_acct_mgmt(_pamh, PAM_SILENT)};
|
||||
if (err != PAM_SUCCESS)
|
||||
throw PAMError {"acct_mgmt failed", _pamh, err};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
class ConvContext
|
||||
{
|
||||
public:
|
||||
virtual ~ConvContext() = default;
|
||||
};
|
||||
|
||||
class AuthenticateConvContext final : public ConvContext
|
||||
{
|
||||
public:
|
||||
AuthenticateConvContext(std::string_view password) : _password {password} {}
|
||||
|
||||
std::string_view getPassword() const { return _password; }
|
||||
|
||||
private:
|
||||
std::string_view _password;
|
||||
};
|
||||
|
||||
class ScopedConvContextSetter
|
||||
{
|
||||
public:
|
||||
ScopedConvContextSetter(PAMContext& pamContext, ConvContext& convContext)
|
||||
: _pamContext {pamContext}
|
||||
{
|
||||
_pamContext._convContext = &convContext;
|
||||
}
|
||||
|
||||
~ScopedConvContextSetter()
|
||||
{
|
||||
_pamContext._convContext = nullptr;
|
||||
}
|
||||
|
||||
ScopedConvContextSetter(const ScopedConvContextSetter&) = delete;
|
||||
ScopedConvContextSetter(ScopedConvContextSetter&&) = delete;
|
||||
ScopedConvContextSetter& operator=(const ScopedConvContextSetter&) = delete;
|
||||
ScopedConvContextSetter& operator=(ScopedConvContextSetter&&) = delete;
|
||||
|
||||
private:
|
||||
PAMContext& _pamContext;
|
||||
};
|
||||
|
||||
|
||||
static int conv(int msgCount, const pam_message** msgs, pam_response** resps, void* userData)
|
||||
{
|
||||
if (msgCount < 1)
|
||||
return PAM_CONV_ERR;
|
||||
if (!resps || !msgs || !userData)
|
||||
return PAM_CONV_ERR;
|
||||
|
||||
PAMContext& context {*static_cast<PAMContext*>(userData)};
|
||||
|
||||
AuthenticateConvContext* authenticateContext = dynamic_cast<AuthenticateConvContext*>(context._convContext);
|
||||
if (!authenticateContext)
|
||||
{
|
||||
LMS_LOG(AUTH, ERROR) << "Unexpected conv!";
|
||||
return PAM_CONV_ERR;
|
||||
}
|
||||
|
||||
// Only expect a PAM_PROMPT_ECHO_OFF msg
|
||||
if (msgCount != 1 || msgs[0]->msg_style != PAM_PROMPT_ECHO_OFF)
|
||||
{
|
||||
LMS_LOG(AUTH, ERROR) << "Unexpected conv message. Count = " << msgCount;
|
||||
return PAM_CONV_ERR;
|
||||
}
|
||||
|
||||
pam_response* response {static_cast<pam_response*>(malloc(sizeof(pam_response)))};
|
||||
if (!response)
|
||||
return PAM_CONV_ERR;
|
||||
|
||||
response->resp = strdup(std::string {authenticateContext->getPassword()}.c_str());
|
||||
|
||||
*resps = response;
|
||||
return PAM_SUCCESS;
|
||||
}
|
||||
|
||||
ConvContext* _convContext {};
|
||||
pam_conv _conv {&PAMContext::conv, this};
|
||||
pam_handle_t *_pamh {};
|
||||
|
||||
};
|
||||
|
||||
bool
|
||||
checkUserPassword(const std::string& loginName, const std::string& password)
|
||||
{
|
||||
try
|
||||
{
|
||||
LMS_LOG(AUTH, DEBUG) << "Checking PAM password for user '" << loginName << "'";
|
||||
PAMContext pamContext {loginName};
|
||||
|
||||
pamContext.authenticate(password);
|
||||
pamContext.validateAccount();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (const PAMError& error)
|
||||
{
|
||||
LMS_LOG(AUTH, ERROR) << "PAM error: " << error.message();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Auth::PAM
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
/*
|
||||
* Copyright (C) 2019 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "PAMPasswordService.hpp"
|
||||
|
||||
#ifndef LMS_SUPPORT_PAM
|
||||
#error "Should not compile this"
|
||||
#endif
|
||||
|
||||
#include <cstring>
|
||||
#include <security/pam_appl.h>
|
||||
|
||||
#include "auth/Types.hpp"
|
||||
#include "database/Session.hpp"
|
||||
#include "utils/Logger.hpp"
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
class PAMError
|
||||
{
|
||||
public:
|
||||
PAMError(std::string_view msg, pam_handle_t *pamh, int err)
|
||||
{
|
||||
_errorMsg = std::string {msg} + ": " + pam_strerror(pamh, err);
|
||||
}
|
||||
|
||||
std::string_view message() const { return _errorMsg; }
|
||||
|
||||
private:
|
||||
std::string _errorMsg;
|
||||
};
|
||||
|
||||
class PAMContext
|
||||
{
|
||||
public:
|
||||
PAMContext(std::string_view loginName)
|
||||
{
|
||||
int err {pam_start("lms", std::string {loginName}.c_str(), &_conv, &_pamh)};
|
||||
if (err != PAM_SUCCESS)
|
||||
throw PAMError {"start failed", _pamh, err};
|
||||
}
|
||||
|
||||
~PAMContext()
|
||||
{
|
||||
int err {pam_end(_pamh, 0)};
|
||||
if (err != PAM_SUCCESS)
|
||||
LMS_LOG(AUTH, ERROR) << "end failed: " << pam_strerror(_pamh, err);
|
||||
}
|
||||
|
||||
void authenticate(std::string_view password)
|
||||
{
|
||||
AuthenticateConvContext authContext {password};
|
||||
ScopedConvContextSetter scopedContext {*this, authContext};
|
||||
|
||||
int err {pam_authenticate(_pamh, 0)};
|
||||
if (err != PAM_SUCCESS)
|
||||
throw PAMError {"authenticate failed", _pamh, err};
|
||||
}
|
||||
|
||||
void validateAccount()
|
||||
{
|
||||
int err {pam_acct_mgmt(_pamh, PAM_SILENT)};
|
||||
if (err != PAM_SUCCESS)
|
||||
throw PAMError {"acct_mgmt failed", _pamh, err};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
class ConvContext
|
||||
{
|
||||
public:
|
||||
virtual ~ConvContext() = default;
|
||||
};
|
||||
|
||||
class AuthenticateConvContext final : public ConvContext
|
||||
{
|
||||
public:
|
||||
AuthenticateConvContext(std::string_view password) : _password {password} {}
|
||||
|
||||
std::string_view getPassword() const { return _password; }
|
||||
|
||||
private:
|
||||
std::string_view _password;
|
||||
};
|
||||
|
||||
class ScopedConvContextSetter
|
||||
{
|
||||
public:
|
||||
ScopedConvContextSetter(PAMContext& pamContext, ConvContext& convContext)
|
||||
: _pamContext {pamContext}
|
||||
{
|
||||
_pamContext._convContext = &convContext;
|
||||
}
|
||||
|
||||
~ScopedConvContextSetter()
|
||||
{
|
||||
_pamContext._convContext = nullptr;
|
||||
}
|
||||
|
||||
ScopedConvContextSetter(const ScopedConvContextSetter&) = delete;
|
||||
ScopedConvContextSetter(ScopedConvContextSetter&&) = delete;
|
||||
ScopedConvContextSetter& operator=(const ScopedConvContextSetter&) = delete;
|
||||
ScopedConvContextSetter& operator=(ScopedConvContextSetter&&) = delete;
|
||||
|
||||
private:
|
||||
PAMContext& _pamContext;
|
||||
};
|
||||
|
||||
|
||||
static int conv(int msgCount, const pam_message** msgs, pam_response** resps, void* userData)
|
||||
{
|
||||
if (msgCount < 1)
|
||||
return PAM_CONV_ERR;
|
||||
if (!resps || !msgs || !userData)
|
||||
return PAM_CONV_ERR;
|
||||
|
||||
PAMContext& context {*static_cast<PAMContext*>(userData)};
|
||||
|
||||
AuthenticateConvContext* authenticateContext = dynamic_cast<AuthenticateConvContext*>(context._convContext);
|
||||
if (!authenticateContext)
|
||||
{
|
||||
LMS_LOG(AUTH, ERROR) << "Unexpected conv!";
|
||||
return PAM_CONV_ERR;
|
||||
}
|
||||
|
||||
// Only expect a PAM_PROMPT_ECHO_OFF msg
|
||||
if (msgCount != 1 || msgs[0]->msg_style != PAM_PROMPT_ECHO_OFF)
|
||||
{
|
||||
LMS_LOG(AUTH, ERROR) << "Unexpected conv message. Count = " << msgCount;
|
||||
return PAM_CONV_ERR;
|
||||
}
|
||||
|
||||
pam_response* response {static_cast<pam_response*>(malloc(sizeof(pam_response)))};
|
||||
if (!response)
|
||||
return PAM_CONV_ERR;
|
||||
|
||||
response->resp = strdup(std::string {authenticateContext->getPassword()}.c_str());
|
||||
|
||||
*resps = response;
|
||||
return PAM_SUCCESS;
|
||||
}
|
||||
|
||||
ConvContext* _convContext {};
|
||||
pam_conv _conv {&PAMContext::conv, this};
|
||||
pam_handle_t *_pamh {};
|
||||
|
||||
};
|
||||
|
||||
bool
|
||||
PAMPasswordService::checkUserPassword(Database::Session& /*session*/, std::string_view loginName, std::string_view password)
|
||||
{
|
||||
try
|
||||
{
|
||||
LMS_LOG(AUTH, DEBUG) << "Checking PAM password for user '" << loginName << "'";
|
||||
PAMContext pamContext {loginName};
|
||||
|
||||
pamContext.authenticate(password);
|
||||
pamContext.validateAccount();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (const PAMError& error)
|
||||
{
|
||||
LMS_LOG(AUTH, ERROR) << "PAM error: " << error.message();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
PAMPasswordService::canSetPasswords() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool
|
||||
PAMPasswordService::isPasswordSecureEnough(std::string_view, std::string_view) const
|
||||
{
|
||||
throw NotImplementedException {};
|
||||
}
|
||||
|
||||
void
|
||||
PAMPasswordService::setPassword(Database::Session&, Database::IdType, std::string_view)
|
||||
{
|
||||
throw NotImplementedException {};
|
||||
}
|
||||
|
||||
} // namespace Auth
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright (C) 2019 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <shared_mutex>
|
||||
|
||||
#include "PasswordServiceBase.hpp"
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
class PAMPasswordService: public PasswordServiceBase
|
||||
{
|
||||
public:
|
||||
using PasswordServiceBase::PasswordServiceBase;
|
||||
|
||||
private:
|
||||
|
||||
bool checkUserPassword(Database::Session& session,
|
||||
std::string_view loginName,
|
||||
std::string_view password) override;
|
||||
|
||||
bool canSetPasswords() const override;
|
||||
bool isPasswordSecureEnough(std::string_view loginName,
|
||||
std::string_view password) const override;
|
||||
void setPassword(Database::Session& session,
|
||||
Database::IdType userId,
|
||||
std::string_view newPassword) override;
|
||||
};
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <boost/asio/ip/address.hpp>
|
||||
#include <Wt/WDateTime.h>
|
||||
|
||||
@@ -31,11 +32,11 @@
|
||||
namespace Database
|
||||
{
|
||||
class Session;
|
||||
class User;
|
||||
}
|
||||
|
||||
|
||||
namespace Auth {
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
class IAuthTokenService
|
||||
{
|
||||
public:
|
||||
@@ -46,9 +47,9 @@ namespace Auth {
|
||||
{
|
||||
enum class State
|
||||
{
|
||||
Found,
|
||||
Granted,
|
||||
Throttled,
|
||||
NotFound,
|
||||
Denied,
|
||||
};
|
||||
|
||||
struct AuthTokenInfo
|
||||
@@ -57,16 +58,17 @@ namespace Auth {
|
||||
Wt::WDateTime expiry;
|
||||
};
|
||||
|
||||
State state {State::NotFound};
|
||||
State state {State::Denied};
|
||||
std::optional<AuthTokenInfo> authTokenInfo {};
|
||||
};
|
||||
|
||||
// Removed if found
|
||||
virtual AuthTokenProcessResult processAuthToken(Database::Session& session, const boost::asio::ip::address& clientAddress, const std::string& tokenValue) = 0;
|
||||
virtual std::string createAuthToken(Database::Session& session, Database::IdType userid, const Wt::WDateTime& expiry) = 0;
|
||||
// Provided token is only accepted once
|
||||
virtual AuthTokenProcessResult processAuthToken(Database::Session& session, const boost::asio::ip::address& clientAddress, std::string_view tokenValue) = 0;
|
||||
|
||||
// Returns a one time token
|
||||
virtual std::string createAuthToken(Database::Session& session, Database::IdType userid, const Wt::WDateTime& expiry) = 0;
|
||||
virtual void clearAuthTokens(Database::Session& session, Database::IdType userid) = 0;
|
||||
};
|
||||
|
||||
std::unique_ptr<IAuthTokenService> createAuthTokenService(std::size_t maxThrottlerEntryCount);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright (C) 2019 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
* LMS is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* LMS is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
#include "database/Types.hpp"
|
||||
|
||||
namespace Database
|
||||
{
|
||||
class Session;
|
||||
}
|
||||
|
||||
namespace Wt
|
||||
{
|
||||
class WEnvironment;
|
||||
}
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
class IEnvService
|
||||
{
|
||||
public:
|
||||
virtual ~IEnvService() = default;
|
||||
|
||||
// Auth Token services
|
||||
struct CheckResult
|
||||
{
|
||||
enum class State
|
||||
{
|
||||
Granted,
|
||||
Denied,
|
||||
Throttled,
|
||||
};
|
||||
|
||||
State state {State::Denied};
|
||||
std::optional<Database::IdType> userId {};
|
||||
};
|
||||
|
||||
virtual CheckResult processEnv(Database::Session& session, const Wt::WEnvironment& env) = 0;
|
||||
};
|
||||
|
||||
std::unique_ptr<IEnvService> createEnvService(std::string_view backendName);
|
||||
} // namespace Auth
|
||||
@@ -19,44 +19,59 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include <Wt/WDateTime.h>
|
||||
#include <Wt/Dbo/ptr.h>
|
||||
|
||||
#include <boost/asio/ip/address.hpp>
|
||||
|
||||
#include "database/User.hpp"
|
||||
#include "auth/Types.hpp"
|
||||
#include "database/Types.hpp"
|
||||
|
||||
namespace Database
|
||||
{
|
||||
class Session;
|
||||
class User;
|
||||
}
|
||||
|
||||
namespace Auth
|
||||
{
|
||||
|
||||
namespace Auth {
|
||||
class IAuthTokenService;
|
||||
|
||||
class IPasswordService
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~IPasswordService() = default;
|
||||
|
||||
// Password services
|
||||
enum class PasswordCheckResult
|
||||
struct CheckResult
|
||||
{
|
||||
Match,
|
||||
Mismatch,
|
||||
Throttled,
|
||||
enum class State
|
||||
{
|
||||
Granted,
|
||||
Denied,
|
||||
Throttled,
|
||||
};
|
||||
State state {State::Denied};
|
||||
std::optional<Database::IdType> userId {};
|
||||
std::optional<Wt::WDateTime> expiry {};
|
||||
};
|
||||
virtual CheckResult checkUserPassword(Database::Session& session,
|
||||
const boost::asio::ip::address& clientAddress,
|
||||
std::string_view loginName,
|
||||
std::string_view password) = 0;
|
||||
|
||||
class PasswordTooWeakException : public Auth::Exception
|
||||
{
|
||||
public:
|
||||
PasswordTooWeakException() : Auth::Exception {"Password too weak"} {}
|
||||
};
|
||||
|
||||
virtual bool isAuthModeSupported(Database::User::AuthMode authMode) const = 0;
|
||||
|
||||
virtual PasswordCheckResult checkUserPassword(Database::Session& session, const boost::asio::ip::address& clientAddress, const std::string& loginName, const std::string& password) = 0;
|
||||
virtual Database::User::PasswordHash hashPassword(const std::string& password) const = 0;
|
||||
virtual bool evaluatePasswordStrength(const std::string& loginName, const std::string& password) const = 0;
|
||||
virtual bool canSetPasswords() const = 0;
|
||||
virtual bool isPasswordSecureEnough(std::string_view username, std::string_view password) const = 0;
|
||||
virtual void setPassword(Database::Session& session, Database::IdType userId, std::string_view newPassword) = 0;
|
||||
};
|
||||
|
||||
std::unique_ptr<IPasswordService> createPasswordService(std::size_t maxThrottlerEntryCount);
|
||||
|
||||
std::unique_ptr<IPasswordService> createPasswordService(std::string_view authPasswordBackend, std::size_t maxThrottlerEntryCount, IAuthTokenService& authTokenService);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2020 Emeric Poupon
|
||||
* Copyright (C) 2021 Emeric Poupon
|
||||
*
|
||||
* This file is part of LMS.
|
||||
*
|
||||
@@ -19,14 +19,19 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifdef LMS_SUPPORT_PAM
|
||||
#include "utils/Exception.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Auth::PAM
|
||||
namespace Auth
|
||||
{
|
||||
bool checkUserPassword(const std::string& loginName, const std::string& password);
|
||||
class Exception : public ::LmsException
|
||||
{
|
||||
using LmsException::LmsException;
|
||||
};
|
||||
|
||||
class NotImplementedException : public Exception
|
||||
{
|
||||
public:
|
||||
NotImplementedException() : Auth::Exception {"Not implemented"} {}
|
||||
};
|
||||
}
|
||||
|
||||
#endif // LMS_SUPPORT_PAM
|
||||
|
||||
Reference in New Issue
Block a user