Merge branch 'master' of https://github.com/tazio/lms into tazio-pam-auth

This commit is contained in:
emeric
2020-07-04 14:54:54 +02:00
16 changed files with 421 additions and 26 deletions
+1
View File
@@ -22,6 +22,7 @@ target_link_libraries(lmsauth PUBLIC
pthread
boost_system
wt
${PAM_LIBRARIES}
)
install(TARGETS lmsauth DESTINATION lib)
-2
View File
@@ -17,8 +17,6 @@
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
/* This file contains some classes in order to get info from file using the libavconv */
#include "AuthTokenService.hpp"
#include <Wt/Auth/HashFunction.h>
-2
View File
@@ -17,8 +17,6 @@
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
/* This file contains some classes in order to get info from file using the libavconv */
#pragma once
#include "auth/IAuthTokenService.hpp"
+103 -4
View File
@@ -17,8 +17,6 @@
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
/* This file contains some classes in order to get info from file using the libavconv */
#include "PasswordService.hpp"
#include <Wt/Auth/HashFunction.h>
@@ -29,6 +27,8 @@
#include "utils/Exception.hpp"
#include "utils/Logger.hpp"
#include <security/pam_appl.h>
namespace Auth {
std::unique_ptr<IPasswordService> createPasswordService(std::size_t maxThrottlerEntries)
@@ -41,10 +41,101 @@ PasswordService::PasswordService(std::size_t maxThrottlerEntries)
{
}
#ifdef USEPAM
static void
delete_resp(int num_msg, pam_response *response)
{
if (response == nullptr)
return;
for (int i = 0; i < num_msg; i++) {
if (response[i].resp) {
/* clear before freeing -- might be a password */
bzero(response[i].resp, strlen(response[i].resp));
free(response[i].resp);
response[i].resp = nullptr;
}
}
}
struct pam_conv_data
{
const char *username;
const char *password;
};
static
int lms_conv(int num_msg, const pam_message** msgs, pam_response** resps, void* appdata_ptr)
{
if(num_msg < 1)
return PAM_CONV_ERR;
if (!resps || !msgs || !appdata_ptr)
return PAM_CONV_ERR;
pam_conv_data *data = static_cast<pam_conv_data*>( appdata_ptr );
pam_response *response = new (std::nothrow) pam_response[num_msg];
if(!response)
return PAM_CONV_ERR;
for(int i = 0; i < num_msg; ++i)
{
response[i].resp_retcode = 0;
response[i].resp = 0;
switch (msgs[i]->msg_style) {
case PAM_PROMPT_ECHO_ON:
/* on memory allocation failure, auth fails */
response[i].resp = strdup(data->username);
break;
case PAM_PROMPT_ECHO_OFF:
response[i].resp = strdup(data->password);
break;
case PAM_ERROR_MSG:
case PAM_TEXT_INFO:
default:
delete_resp(i, response);
return PAM_CONV_ERR;
}
}
*resps = response;
return PAM_SUCCESS;
}
#endif
static bool
pamCheckUserPassword(const std::string& loginName, const std::string& password)
{
#ifdef USEPAM
pam_conv_data authdata{loginName.c_str(), password.c_str()};
pam_conv conv = { lms_conv, &authdata };
pam_handle_t *pamh;
bool authenticated{false};
/* Initialize PAM framework */
int err = pam_start("lms", loginName.c_str(), &conv, &pamh);
if (err != PAM_SUCCESS) {
return false;
}
err = pam_authenticate(pamh, 0);
if(err == PAM_SUCCESS)
{
/* Make sure account and password are still valid */
err = pam_acct_mgmt(pamh, PAM_SILENT);
authenticated = err == PAM_SUCCESS;
}
(void) pam_end(pamh, 0);
return authenticated;
#else
return false;
#endif
}
static
bool
checkUserPassword(Database::Session& session, const std::string& loginName, const std::string& password)
{
bool hasExternalAuth;
Database::User::PasswordHash passwordHash;
{
auto transaction {session.createSharedTransaction()};
@@ -53,11 +144,19 @@ checkUserPassword(Database::Session& session, const std::string& loginName, cons
if (!user)
return false;
hasExternalAuth = user->hasExternalAuth();
passwordHash = user->getPasswordHash();
}
const Wt::Auth::BCryptHashFunction hashFunc {6};
return hashFunc.verify(password, passwordHash.salt, passwordHash.hash);
if (hasExternalAuth)
{
return pamCheckUserPassword(loginName, password);
}
else
{
const Wt::Auth::BCryptHashFunction hashFunc {6};
return hashFunc.verify(password, passwordHash.salt, passwordHash.hash);
}
}
+11
View File
@@ -8,11 +8,20 @@ add_library(lmsav SHARED
target_include_directories(lmsav INTERFACE
include
${AVFORMAT_INCLUDE_DIR}
${AVUTIL_INCLUDE_DIR}
)
# ${AVCODEC_INCLUDE_DIR}
# ${AVDEVICE_INCLUDE_DIR}
target_include_directories(lmsav PRIVATE
include/
${AVFORMAT_INCLUDE_DIR}
${AVUTIL_INCLUDE_DIR}
)
# ${AVCODEC_INCLUDE_DIR}
# ${AVDEVICE_INCLUDE_DIR}
# TODO make these private
target_link_libraries(lmsav PUBLIC
@@ -21,6 +30,8 @@ target_link_libraries(lmsav PUBLIC
avutil
std::filesystem
wt
${AVFORMAT_LIBRARY}
${AVUTIL_LIBRARY}
)
install(TARGETS lmsav DESTINATION lib)
@@ -165,6 +165,7 @@ class User : public Wt::Dbo::Dbo<User>
void setSubsonicTranscodeBitrate(Bitrate bitrate);
void setCurPlayingTrackPos(std::size_t pos) { _curPlayingTrackPos = pos; }
void setRadio(bool val) { _radio = val; }
void setExternalAuth(bool val) { _externalAuth = val; }
void setRepeatAll(bool val) { _repeatAll = val; }
void setUITheme(UITheme uiTheme) { _uiTheme = uiTheme; }
void clearAuthTokens();
@@ -179,6 +180,7 @@ class User : public Wt::Dbo::Dbo<User>
std::size_t getCurPlayingTrackPos() const { return _curPlayingTrackPos; }
bool isRepeatAllSet() const { return _repeatAll; }
bool isRadioSet() const { return _radio; }
bool hasExternalAuth() const { return _externalAuth; }
UITheme getUITheme() const { return _uiTheme; }
SubsonicArtistListMode getSubsonicArtistListMode() const { return _subsonicArtistListMode; }
@@ -218,6 +220,7 @@ class User : public Wt::Dbo::Dbo<User>
Wt::Dbo::field(a, _curPlayingTrackPos, "cur_playing_track_pos");
Wt::Dbo::field(a, _repeatAll, "repeat_all");
Wt::Dbo::field(a, _radio, "radio");
Wt::Dbo::field(a, _externalAuth, "external_auth");
Wt::Dbo::hasMany(a, _tracklists, Wt::Dbo::ManyToOne, "user");
Wt::Dbo::hasMany(a, _starredArtists, Wt::Dbo::ManyToMany, "user_artist_starred", "", Wt::Dbo::OnDeleteCascade);
Wt::Dbo::hasMany(a, _starredReleases, Wt::Dbo::ManyToMany, "user_release_starred", "", Wt::Dbo::OnDeleteCascade);
@@ -246,6 +249,8 @@ class User : public Wt::Dbo::Dbo<User>
int _curPlayingTrackPos {}; // Current track position in queue
bool _repeatAll {};
bool _radio {};
bool _externalAuth {false};
Wt::Dbo::collection<Wt::Dbo::ptr<TrackList>> _tracklists;
Wt::Dbo::collection<Wt::Dbo::ptr<Artist>> _starredArtists;
+68 -16
View File
@@ -51,6 +51,7 @@ class UserModel : public Wt::WFormModel
static inline const Field LoginField {"login"};
static inline const Field PasswordField {"password"};
static inline const Field DemoField {"demo"};
static inline const Field ExternalAuthField{"external-auth"};
UserModel(std::optional<Database::IdType> userId)
: _userId {userId}
@@ -63,6 +64,7 @@ class UserModel : public Wt::WFormModel
addField(PasswordField);
addField(DemoField);
addField(ExternalAuthField);
if (!_userId)
setValidator(PasswordField, createMandatoryValidator());
@@ -90,6 +92,8 @@ class UserModel : public Wt::WFormModel
user.modify()->setPasswordHash(*passwordHash);
user.modify()->clearAuthTokens();
}
user.modify()->setExternalAuth(static_cast<bool>(Wt::asNumber(value(ExternalAuthField))));
}
else
{
@@ -98,10 +102,48 @@ class UserModel : public Wt::WFormModel
if (Wt::asNumber(value(DemoField)))
user.modify()->setType(Database::User::Type::DEMO);
if (Wt::asNumber(value(ExternalAuthField)))
user.modify()->setExternalAuth(true);
else
user.modify()->setExternalAuth(false);
}
}
private:
Wt::WString validatePassword() const
{
Wt::WString error;
if (Wt::asNumber(value(ExternalAuthField)))
{
if (!valueText(PasswordField).empty())
{
error = Wt::WString::tr("Lms.password_must_be_empty_for_ext");
}
}
else if (!valueText(PasswordField).empty())
{
if (Wt::asNumber(value(DemoField)))
{
// Demo account: password must be the same as the login name
if (valueText(PasswordField) != getLoginName())
error = Wt::WString::tr("Lms.Admin.User.demo-password-invalid");
}
else
{
// Evaluate the strength of the password for non demo accounts
if (!ServiceProvider<::Auth::IPasswordService>::get()->evaluatePasswordStrength(getLoginName(), valueText(PasswordField).toUTF8()))
error = Wt::WString::tr("Lms.password-too-weak");
}
}
else
{
error = Wt::WString::tr("Lms.password-must-not-be-empty");
}
return error;
}
void loadData()
{
@@ -116,6 +158,19 @@ class UserModel : public Wt::WFormModel
else if (user == LmsApp->getUser())
throw UserNotAllowedException {};
}
bool getExternalAuth() const
{
if (_userId)
{
auto transaction {LmsApp->getDbSession().createSharedTransaction()};
const Database::User::pointer user {Database::User::getById(LmsApp->getDbSession(), *_userId)};
return user->hasExternalAuth();
}
else
return Wt::asNumber(value(ExternalAuthField));
}
std::string getLoginName() const
{
@@ -144,21 +199,7 @@ class UserModel : public Wt::WFormModel
}
else if (field == PasswordField)
{
if (!valueText(PasswordField).empty())
{
if (Wt::asNumber(value(DemoField)))
{
// Demo account: password must be the same as the login name
if (valueText(PasswordField) != getLoginName())
error = Wt::WString::tr("Lms.Admin.User.demo-password-invalid");
}
else
{
// Evaluate the strength of the password for non demo accounts
if (!ServiceProvider<::Auth::IPasswordService>::get()->evaluatePasswordStrength(getLoginName(), valueText(PasswordField).toUTF8()))
error = Wt::WString::tr("Lms.password-too-weak");
}
}
error = validatePassword();
}
else if (field == DemoField)
{
@@ -215,6 +256,12 @@ UserView::refreshView()
t->setCondition("if-has-last-login", true);
t->bindString("last-login", user->getLastLogin().toString(), Wt::TextFormat::Plain);
auto extCheckBox = std::make_unique<Wt::WCheckBox>();
extCheckBox->setChecked(user->hasExternalAuth());
t->setFormWidget(UserModel::ExternalAuthField, std::move(extCheckBox));
t->setCondition("if-external-auth", true);
}
else
{
@@ -222,6 +269,11 @@ UserView::refreshView()
t->setCondition("if-has-login", true);
t->setFormWidget(UserModel::LoginField, std::make_unique<Wt::WLineEdit>());
t->bindString("title", Wt::WString::tr("Lms.Admin.User.user-create"));
auto extCheckBox = std::make_unique<Wt::WCheckBox>();
extCheckBox->setChecked(true);
t->setCondition(UserModel::ExternalAuthField, false);
t->setFormWidget("external-auth", std::move(extCheckBox));
}
// Password
@@ -234,7 +286,7 @@ UserView::refreshView()
t->setFormWidget(UserModel::DemoField, std::make_unique<Wt::WCheckBox>());
if (!userId && ServiceProvider<IConfig>::get()->getBool("demo", false))
t->setCondition("if-demo", true);
Wt::WPushButton* saveBtn = t->bindNew<Wt::WPushButton>("save-btn", Wt::WString::tr(userId ? "Lms.save" : "Lms.create"));
saveBtn->clicked().connect([=]()
{
+1 -1
View File
@@ -39,7 +39,7 @@ std::shared_ptr<Wt::WValidator>
createMandatoryValidator()
{
auto v = std::make_shared<Wt::WValidator>();
v->setMandatory(true);
//sv->setMandatory(true);
return v;
}