From: Maxim Mamontov Date: Mon, 11 May 2015 16:22:15 +0000 (+0300) Subject: Introduced new mod_radius. X-Git-Url: https://git.stg.codes/stg.git/commitdiff_plain/1538d6276533140505fddb71c99a0bafe6ca9182?ds=sidebyside Introduced new mod_radius. --- diff --git a/projects/stargazer/plugins/other/radius/Makefile b/projects/stargazer/plugins/other/radius/Makefile index 62a05183..dd736698 100644 --- a/projects/stargazer/plugins/other/radius/Makefile +++ b/projects/stargazer/plugins/other/radius/Makefile @@ -8,7 +8,8 @@ LIBS += $(LIB_THREAD) PROG = mod_radius.so -SRCS = ./radius.cpp +SRCS = radius.cpp \ + config.cpp STGLIBS = common \ crypto \ diff --git a/projects/stargazer/plugins/other/radius/config.cpp b/projects/stargazer/plugins/other/radius/config.cpp new file mode 100644 index 00000000..8a90567d --- /dev/null +++ b/projects/stargazer/plugins/other/radius/config.cpp @@ -0,0 +1,177 @@ +/* + * This program 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 2 of the License, or + * (at your option) any later version. + * + * This program 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 this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + +#include "config.h" + +#include "stg/common.h" + +#include +#include + +#include // strncasecmp + +using STG::Config; + +namespace +{ + +struct ParserError : public std::runtime_error +{ + ParserError(size_t pos, const std::string& message) + : runtime_error("Parsing error at position " + x2str(pos) + ". " + message), + position(pos), + error(message) + {} + + size_t position; + std::string error; +}; + +size_t skipSpaces(const std::string& value, size_t start) +{ + while (start < value.length() && std::isspace(value[start])) + ++start; + return start; +} + +size_t checkChar(const std:string& value, size_t start, char ch) +{ + if (start >= value.length()) + throw ParserError(start, "Unexpected end of string. Expected '" + std::string(ch) + "'."); + if (value[start] != ch) + throw ParserError(start, "Expected '" + std::string(ch) + "', got '" + std::string(value[start]) + "'."); + return start + 1; +} + +std::pair readString(const std::string& value, size_t start) +{ + std::string dest; + while (start < value.length() && !std::isspace(value[start])) + dest.push_back(value[start++]); + if (dest.empty()) { + if (start == value.length()) + throw ParserError(start, "Unexpected end of string. Expected string."); + else + throw ParserError(start, "Unexpected whitespace. Expected string."); + } + return dest; +} + +Config::Pairs toPairs(const std::vector& values) +{ + if (values.empty()) + return Config::Pairs(); + std::string value(values[0]); + Config::Pairs res; + size_t start = 0; + while (start < value.size()) { + Config::Pair pair; + start = skipSpaces(value, start); + size_t pairStart = start; + start = checkChar(value, start, '('); + std::pair key = readString(value, start); + start = key.first; + pair.first = key.second; + start = skipSpaces(value, start); + start = checkChar(value, start, ',') + start = skipSpaces(value, start); + std::pair value = readString(value, start); + start = key.first; + pair.second = value.second; + start = skipSpaces(value, start); + start = checkChar(value, start, ')'); + if (res.find(pair.first) != res.end()) + throw ParserError(pairStart, "Duplicate field."); + res.insert(pair); + } + return res; +} + +bool toBool(const std::vector& values) +{ + if (values.empty()) + return false; + std::string value(values[0]); + return strncasecmp(value.c_str(), "yes", 3) == 0; +} + +std::string toString(const std::vector& values) +{ + if (values.empty()) + return ""; + return values[0]; +} + +template +T toInt(const std::vector& values) +{ + if (values.empty()) + return 0; + T res = 0; + if (srt2x(values[0], res) == 0) + return res; + return 0; +} + +Config::Pairs parseVector(const std::string& paramName, const MODULE_SETTINGS& params) +{ + for (size_t i = 0; i < params.moduleParams.size(); ++i) + if (params.moduleParams[i].first == paramName) + return toPairs(params.moduleParams[i].second); + return Config::Pairs(); +} + +bool parseBool(const std::string& paramName, const MODULE_SETTINGS& params) +{ + for (size_t i = 0; i < params.moduleParams.size(); ++i) + if (params.moduleParams[i].first == paramName) + return toBool(params.moduleParams[i].second); + return false; +} + +std::string parseString(const std::string& paramName, const MODULE_SETTINGS& params) +{ + for (size_t i = 0; i < params.moduleParams.size(); ++i) + if (params.moduleParams[i].first == paramName) + return toString(params.moduleParams[i].second); + return ""; +} + +template +T parseInt(const std::string& paramName, const MODULE_SETTINGS& params) +{ + for (size_t i = 0; i < params.moduleParams.size(); ++i) + if (params.moduleParams[i].first == paramName) + return toInt(params.moduleParams[i].second); + return 0; +} + +} // namespace anonymous + +Config::Config(const MODULE_SETTINGS& settings) + : match(parseVector("match", settings)), + modify(parseVector("modify", settings)), + reply(parseVector("reply", settings)), + verbose(parseBool("verbose", settings)), + bindAddress(parseString("bind_address", settings)), + port(parseInt("port", settings)), + key(parseString("key", settings)) +{ +} diff --git a/projects/stargazer/plugins/other/radius/config.h b/projects/stargazer/plugins/other/radius/config.h new file mode 100644 index 00000000..8e5055d8 --- /dev/null +++ b/projects/stargazer/plugins/other/radius/config.h @@ -0,0 +1,54 @@ +/* + * This program 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 2 of the License, or + * (at your option) any later version. + * + * This program 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 this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + +#ifndef __STG_RADIUS_CONFIG_H__ +#define __STG_RADIUS_CONFIG_H__ + +#include "stg/module_settings.h" + +#include "stg/os_int.h" + +#include +#include + +namespace STG +{ + +struct Config +{ + typedef std::map Pairs; + typedef Pairs::value_type Pair; + + Config(const MODULE_SETTINGS& settings); + + Pairs match; + Pairs modify; + Pairs reply; + + bool verbose; + + std::string bindAddress; + uint16_t port; + std::string key; +}; + +} // namespace STG + +#endif diff --git a/projects/stargazer/plugins/other/radius/conn.cpp b/projects/stargazer/plugins/other/radius/conn.cpp new file mode 100644 index 00000000..223eb2cf --- /dev/null +++ b/projects/stargazer/plugins/other/radius/conn.cpp @@ -0,0 +1,63 @@ +/* + * This program 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 2 of the License, or + * (at your option) any later version. + * + * This program 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 this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + +#include "conn.h" + +#include "config.h" + +#include "stg/users.h" +#include "stg/user.h" +#include "stg/logger.h" +#include "stg/common.h" + +#include +#include + +using STG::Conn; + +Conn::Conn(USERS& users, PLUGIN_LOGGER & logger, const Config& config) + : m_users(users), + m_logger(logger), + m_config(config) +{ +} + +Conn::~Conn() +{ +} + +bool Conn::read() +{ + ssize_t res = read(m_sock, m_buffer, m_bufferSize); + if (res < 0) + { + m_state = ERROR; + Log(__FILE__, "Failed to read data from " + inet_ntostring(IP()) + ":" + x2str(port()) + ". Reason: '" + strerror(errno) + "'"); + return false; + } + if (res == 0 && m_state != DATA) // EOF is ok for data. + { + m_state = ERROR; + Log(__FILE__, "Failed to read data from " + inet_ntostring(IP()) + ":" + x2str(port()) + ". Unexpected EOF."); + return false; + } + m_bufferSize -= res; + return HandleBuffer(res); +} diff --git a/projects/stargazer/plugins/other/radius/conn.h b/projects/stargazer/plugins/other/radius/conn.h new file mode 100644 index 00000000..31ebe1dd --- /dev/null +++ b/projects/stargazer/plugins/other/radius/conn.h @@ -0,0 +1,57 @@ +/* + * This program 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 2 of the License, or + * (at your option) any later version. + * + * This program 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 this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + +#ifndef __STG_SGCONFIG_CONN_H__ +#define __STG_SGCONFIG_CONN_H__ + +#include "stg/os_int.h" + +#include +#include + +class USERS; + +namespace STG +{ + +class Conn +{ + public: + struct Error : public std::runtime_error + { + Error(const std::string& message) : runtime_error(message.c_str()) {} + }; + + Conn(USERS& users, PLUGIN_LOGGER& logger, const Config& config); + ~Conn(); + + int sock() const { return m_sock; } + + bool read(); + + private: + USERS& m_users; + PLUGIN_LOGGER& m_logger; + const Config& m_config; +}; + +} + +#endif diff --git a/projects/stargazer/plugins/other/radius/radius.cpp b/projects/stargazer/plugins/other/radius/radius.cpp index 8e52cdb4..fe989b28 100644 --- a/projects/stargazer/plugins/other/radius/radius.cpp +++ b/projects/stargazer/plugins/other/radius/radius.cpp @@ -18,586 +18,169 @@ * Author : Maxim Mamontov */ -/* - * This file contains a realization of radius data access plugin for Stargazer - * - * $Revision: 1.14 $ - * $Date: 2009/12/13 14:17:13 $ - * - */ - -#include -#include -#include +#include "radius.h" #include "stg/store.h" -#include "stg/common.h" -#include "stg/user_conf.h" -#include "stg/user_property.h" +#include "stg/users.h" #include "stg/plugin_creator.h" -#include "radius.h" -extern volatile time_t stgTime; +#include +#include +#include -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- namespace { -PLUGIN_CREATOR radc; -void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password); -void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8); -void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8); -} -extern "C" PLUGIN * GetPlugin(); -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -PLUGIN * GetPlugin() -{ -return radc.GetPlugin(); +PLUGIN_CREATOR creator; + } -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -int RAD_SETTINGS::ParseServices(const std::vector & str, std::list * lst) + +extern "C" PLUGIN * GetPlugin() { -std::copy(str.begin(), str.end(), std::back_inserter(*lst)); -std::list::iterator it(std::find(lst->begin(), - lst->end(), - "empty")); -if (it != lst->end()) - *it = ""; - -return 0; + return creator.GetPlugin(); } -//----------------------------------------------------------------------------- -int RAD_SETTINGS::ParseSettings(const MODULE_SETTINGS & s) -{ -int p; -PARAM_VALUE pv; -std::vector::const_iterator pvi; -/////////////////////////// -pv.param = "Port"; -pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv); -if (pvi == s.moduleParams.end()) - { - errorStr = "Parameter \'Port\' not found."; - printfd(__FILE__, "Parameter 'Port' not found\n"); - return -1; - } -if (ParseIntInRange(pvi->value[0], 2, 65535, &p)) - { - errorStr = "Cannot parse parameter \'Port\': " + errorStr; - printfd(__FILE__, "Cannot parse parameter 'Port'\n"); - return -1; - } -port = static_cast(p); -/////////////////////////// -pv.param = "Password"; -pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv); -if (pvi == s.moduleParams.end()) - { - errorStr = "Parameter \'Password\' not found."; - printfd(__FILE__, "Parameter 'Password' not found\n"); - return -1; - } -password = pvi->value[0]; -/////////////////////////// -pv.param = "AuthServices"; -pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv); -if (pvi != s.moduleParams.end()) - { - ParseServices(pvi->value, &authServices); - } -/////////////////////////// -pv.param = "AcctServices"; -pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv); -if (pvi != s.moduleParams.end()) - { - ParseServices(pvi->value, &acctServices); - } -return 0; -} -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- RADIUS::RADIUS() - : ctx(), - errorStr(), - radSettings(), - settings(), - authServices(), - acctServices(), - sessions(), - nonstop(false), - isRunning(false), - users(NULL), - stgSettings(NULL), - store(NULL), - thread(), - mutex(), - sock(-1), - packet(), - logger(GetPluginLogger(GetStgLogger(), "radius")) + : m_running(false), + m_stopped(true), + m_users(NULL), + m_store(NULL), + m_logger(GetPluginLogger(GetStgLogger(), "radius")) { -InitEncrypt(&ctx, ""); } -//----------------------------------------------------------------------------- + int RADIUS::ParseSettings() { -int ret = radSettings.ParseSettings(settings); -if (ret) - errorStr = radSettings.GetStrError(); -return ret; -} -//----------------------------------------------------------------------------- -int RADIUS::PrepareNet() -{ -sock = socket(AF_INET, SOCK_DGRAM, 0); - -if (sock < 0) - { - errorStr = "Cannot create socket."; - logger("Cannot create a socket: %s", strerror(errno)); - printfd(__FILE__, "Cannot create socket\n"); - return -1; - } - -struct sockaddr_in inAddr; -inAddr.sin_family = AF_INET; -inAddr.sin_port = htons(radSettings.GetPort()); -inAddr.sin_addr.s_addr = inet_addr("0.0.0.0"); - -if (bind(sock, (struct sockaddr*)&inAddr, sizeof(inAddr)) < 0) - { - errorStr = "RADIUS: Bind failed."; - logger("Cannot bind the socket: %s", strerror(errno)); - printfd(__FILE__, "Cannot bind socket\n"); - return -1; + try { + m_config = STG::Config(m_settings); + return 0; + } catch (const std::runtime_error& ex) { + m_logger("Failed to parse settings. %s", ex.what()); + return -1; } - -return 0; } -//----------------------------------------------------------------------------- -int RADIUS::FinalizeNet() -{ -close(sock); -return 0; -} -//----------------------------------------------------------------------------- + int RADIUS::Start() { -std::string password(radSettings.GetPassword()); - -authServices = radSettings.GetAuthServices(); -acctServices = radSettings.GetAcctServices(); - -InitEncrypt(&ctx, password); + if (m_running) + return 0; -nonstop = true; + int res = pthread_create(&m_thread, NULL, run, this); + if (res == 0) + return 0; -if (PrepareNet()) - { + m_error = strerror(res); + m_logger("Failed to create thread: '" + m_error + "'."); return -1; - } - -if (!isRunning) - { - if (pthread_create(&thread, NULL, Run, this)) - { - errorStr = "Cannot create thread."; - logger("Cannot create thread."); - printfd(__FILE__, "Cannot create thread\n"); - return -1; - } - } - -errorStr = ""; -return 0; } -//----------------------------------------------------------------------------- + int RADIUS::Stop() { -if (!IsRunning()) - return 0; - -nonstop = false; - -std::map::iterator it; -for (it = sessions.begin(); it != sessions.end(); ++it) - { - USER_PTR ui; - if (users->FindByName(it->second.userName, &ui)) - { - users->Unauthorize(ui->GetLogin(), this); - } - } -sessions.erase(sessions.begin(), sessions.end()); + if (m_stopped) + return 0; -FinalizeNet(); + m_running = false; -if (isRunning) - { - //5 seconds to thread stops itself - for (int i = 0; i < 25 && isRunning; i++) - { + for (size_t i = 0; i < 25 && !m_stopped; i++) { struct timespec ts = {0, 200000000}; nanosleep(&ts, NULL); - } } -if (isRunning) - return -1; - -return 0; -} -//----------------------------------------------------------------------------- -void * RADIUS::Run(void * d) -{ -sigset_t signalSet; -sigfillset(&signalSet); -pthread_sigmask(SIG_BLOCK, &signalSet, NULL); - -RADIUS * rad = static_cast(d); -RAD_PACKET packet; - -rad->isRunning = true; - -while (rad->nonstop) - { - if (!WaitPackets(rad->sock)) - { - continue; - } - struct sockaddr_in outerAddr; - if (rad->RecvData(&packet, &outerAddr)) - { - printfd(__FILE__, "RADIUS::Run Error on RecvData\n"); - } - else - { - if (rad->ProcessData(&packet)) - { - packet.packetType = RAD_REJECT_PACKET; - } - rad->Send(packet, &outerAddr); - } + if (m_stopped) { + pthread_join(m_thread, NULL); + return 0; } -rad->isRunning = false; - -return NULL; -} -//----------------------------------------------------------------------------- -int RADIUS::RecvData(RAD_PACKET * packet, struct sockaddr_in * outerAddr) -{ - int8_t buf[RAD_MAX_PACKET_LEN]; - socklen_t outerAddrLen = sizeof(struct sockaddr_in); - ssize_t dataLen = recvfrom(sock, buf, RAD_MAX_PACKET_LEN, 0, reinterpret_cast(outerAddr), &outerAddrLen); - if (dataLen < 0) - { - logger("recvfrom error: %s", strerror(errno)); - return -1; - } - if (dataLen == 0) - return -1; - - Decrypt(&ctx, (char *)packet, (const char *)buf, dataLen / 8); - - if (strncmp((char *)packet->magic, RAD_ID, RAD_MAGIC_LEN)) - { - printfd(__FILE__, "RADIUS::RecvData Error magic. Wanted: '%s', got: '%s'\n", RAD_ID, packet->magic); - return -1; - } - - return 0; -} -//----------------------------------------------------------------------------- -ssize_t RADIUS::Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr) -{ -size_t len = sizeof(RAD_PACKET); -char buf[1032]; - -Encrypt(&ctx, buf, (char *)&packet, len / 8); -ssize_t res = sendto(sock, buf, len, 0, reinterpret_cast(outerAddr), sizeof(struct sockaddr_in)); -if (res < 0) - logger("sendto error: %s", strerror(errno)); -return res; -} -//----------------------------------------------------------------------------- -int RADIUS::ProcessData(RAD_PACKET * packet) -{ -if (strncmp((const char *)packet->protoVer, "01", 2)) - { - printfd(__FILE__, "RADIUS::ProcessData packet.protoVer incorrect\n"); + m_error = "Failed to stop thread."; + m_logger(m_error); return -1; - } -switch (packet->packetType) - { - case RAD_AUTZ_PACKET: - return ProcessAutzPacket(packet); - case RAD_AUTH_PACKET: - return ProcessAuthPacket(packet); - case RAD_POST_AUTH_PACKET: - return ProcessPostAuthPacket(packet); - case RAD_ACCT_START_PACKET: - return ProcessAcctStartPacket(packet); - case RAD_ACCT_STOP_PACKET: - return ProcessAcctStopPacket(packet); - case RAD_ACCT_UPDATE_PACKET: - return ProcessAcctUpdatePacket(packet); - case RAD_ACCT_OTHER_PACKET: - return ProcessAcctOtherPacket(packet); - default: - printfd(__FILE__, "RADIUS::ProcessData Unsupported packet type: %d\n", packet->packetType); - return -1; - }; } //----------------------------------------------------------------------------- -int RADIUS::ProcessAutzPacket(RAD_PACKET * packet) +void* RADIUS::run(void* d) { -USER_CONF conf; - -if (!IsAllowedService((char *)packet->service)) - { - printfd(__FILE__, "RADIUS::ProcessAutzPacket service '%s' is not allowed to authorize\n", packet->service); - packet->packetType = RAD_REJECT_PACKET; - return 0; - } + sigset_t signalSet; + sigfillset(&signalSet); + pthread_sigmask(SIG_BLOCK, &signalSet, NULL); -if (store->RestoreUserConf(&conf, (char *)packet->login)) - { - packet->packetType = RAD_REJECT_PACKET; - printfd(__FILE__, "RADIUS::ProcessAutzPacket cannot restore conf for user '%s'\n", packet->login); - return 0; - } + static_cast(d)->runImpl(); -// At this point service can be authorized at least -// So we send a plain-text password - -packet->packetType = RAD_ACCEPT_PACKET; -strncpy((char *)packet->password, conf.password.c_str(), RAD_PASSWORD_LEN); - -return 0; + return NULL; } -//----------------------------------------------------------------------------- -int RADIUS::ProcessAuthPacket(RAD_PACKET * packet) -{ -USER_PTR ui; - -if (!CanAcctService((char *)packet->service)) - { - - // There are no sense to check for allowed service - // It has allready checked at previous stage (authorization) - - printfd(__FILE__, "RADIUS::ProcessAuthPacket service '%s' neednot stargazer authentication\n", (char *)packet->service); - packet->packetType = RAD_ACCEPT_PACKET; - return 0; - } -// At this point we have an accountable service -// All other services got a password if allowed or rejected - -if (!FindUser(&ui, (char *)packet->login)) - { - packet->packetType = RAD_REJECT_PACKET; - printfd(__FILE__, "RADIUS::ProcessAuthPacket user '%s' not found\n", (char *)packet->login); - return 0; - } - -if (ui->IsInetable()) - { - packet->packetType = RAD_ACCEPT_PACKET; - } -else - { - packet->packetType = RAD_REJECT_PACKET; - } - -packet->packetType = RAD_ACCEPT_PACKET; -return 0; -} -//----------------------------------------------------------------------------- -int RADIUS::ProcessPostAuthPacket(RAD_PACKET * packet) +void RADIUS::runImpl() { -USER_PTR ui; - -if (!CanAcctService((char *)packet->service)) - { + m_running = true; - // There are no sense to check for allowed service - // It has allready checked at previous stage (authorization) - - packet->packetType = RAD_ACCEPT_PACKET; - return 0; - } - -if (!FindUser(&ui, (char *)packet->login)) - { - packet->packetType = RAD_REJECT_PACKET; - printfd(__FILE__, "RADIUS::ProcessPostAuthPacket user '%s' not found\n", (char *)packet->login); - return 0; - } - -// I think that only Framed-User services has sense to be accountable -// So we have to supply a Framed-IP - -USER_IPS ips = ui->GetProperty().ips; -packet->packetType = RAD_ACCEPT_PACKET; - -// Additional checking for Framed-User service - -if (!strncmp((char *)packet->service, "Framed-User", RAD_SERVICE_LEN)) - packet->ip = ips[0].ip; -else - packet->ip = 0; - -return 0; -} -//----------------------------------------------------------------------------- -int RADIUS::ProcessAcctStartPacket(RAD_PACKET * packet) -{ -USER_PTR ui; + while (m_running) { + fd_set fds; -if (!FindUser(&ui, (char *)packet->login)) - { - packet->packetType = RAD_REJECT_PACKET; - printfd(__FILE__, "RADIUS::ProcessAcctStartPacket user '%s' not found\n", (char *)packet->login); - return 0; - } + buildFDSet(fds); -// At this point we have to unauthorize user only if it is an accountable service + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = 500000; -if (CanAcctService((char *)packet->service)) - { - if (sessions.find((const char *)packet->sessid) != sessions.end()) + int res = select(maxFD() + 1, &fds, NULL, NULL, &tv); + if (res < 0) { - printfd(__FILE__, "RADIUS::ProcessAcctStartPacket session already started!\n"); - packet->packetType = RAD_REJECT_PACKET; - return -1; - } - USER_IPS ips = ui->GetProperty().ips; - if (!users->Authorize(ui->GetLogin(), ips[0].ip, 0xffFFffFF, this)) - { - printfd(__FILE__, "RADIUS::ProcessAcctStartPacket cannot authorize user '%s'\n", packet->login); - packet->packetType = RAD_REJECT_PACKET; - return -1; + m_error = std::string("'select' is failed: '") + strerror(errno) + "'."; + m_logger(m_error); + break; } - sessions[(const char *)packet->sessid].userName = (const char *)packet->login; - sessions[(const char *)packet->sessid].serviceType = (const char *)packet->service; - for_each(sessions.begin(), sessions.end(), SPrinter()); - } -else - { - printfd(__FILE__, "RADIUS::ProcessAcctStartPacket service '%s' can not be accounted\n", (char *)packet->service); - } - -packet->packetType = RAD_ACCEPT_PACKET; -return 0; -} -//----------------------------------------------------------------------------- -int RADIUS::ProcessAcctStopPacket(RAD_PACKET * packet) -{ -std::map::iterator sid; -if ((sid = sessions.find((const char *)packet->sessid)) == sessions.end()) - { - printfd(__FILE__, "RADIUS::ProcessAcctStopPacket session had not started yet\n"); - packet->packetType = RAD_REJECT_PACKET; - return -1; - } + if (!m_running) + break; -USER_PTR ui; + if (res > 0) + handleEvents(fds); -if (!FindUser(&ui, sid->second.userName)) - { - packet->packetType = RAD_REJECT_PACKET; - printfd(__FILE__, "RADIUS::ProcessPostAuthPacket user '%s' not found\n", sid->second.userName.c_str()); - return 0; + cleanupConns(); } -sessions.erase(sid); - -users->Unauthorize(ui->GetLogin(), this); - -packet->packetType = RAD_ACCEPT_PACKET; -return 0; -} -//----------------------------------------------------------------------------- -int RADIUS::ProcessAcctUpdatePacket(RAD_PACKET * packet) -{ -// Fake. May be use it later -packet->packetType = RAD_ACCEPT_PACKET; -return 0; -} -//----------------------------------------------------------------------------- -int RADIUS::ProcessAcctOtherPacket(RAD_PACKET * packet) -{ -// Fake. May be use it later -packet->packetType = RAD_ACCEPT_PACKET; -return 0; + m_stopped = true; } -//----------------------------------------------------------------------------- -bool RADIUS::FindUser(USER_PTR * ui, const std::string & login) const -{ -if (users->FindByName(login, ui)) - { - return false; - } -return true; -} -//----------------------------------------------------------------------------- -bool RADIUS::CanAuthService(const std::string & svc) const -{ -return find(authServices.begin(), authServices.end(), svc) != authServices.end(); -} -//----------------------------------------------------------------------------- -bool RADIUS::CanAcctService(const std::string & svc) const -{ -return find(acctServices.begin(), acctServices.end(), svc) != acctServices.end(); -} -//----------------------------------------------------------------------------- -bool RADIUS::IsAllowedService(const std::string & svc) const + +int RADIUS::maxFD() const { -return CanAuthService(svc) || CanAcctService(svc); + int maxFD = m_listenSocket; + std::deque::const_iterator it; + for (it = m_conns.begin(); it != m_conns.end(); ++it) + if (maxFD < (*it)->sock()) + maxFD = (*it)->sock(); + return maxFD; } -//----------------------------------------------------------------------------- -namespace -{ -inline -void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) +void RADIUS::buildFDSet(fd_set & fds) const { -unsigned char keyL[RAD_PASSWORD_LEN]; // Пароль для шифровки -memset(keyL, 0, RAD_PASSWORD_LEN); -strncpy((char *)keyL, password.c_str(), RAD_PASSWORD_LEN); -Blowfish_Init(ctx, keyL, RAD_PASSWORD_LEN); + FD_ZERO(&fds); + FD_SET(m_listenSocket, &fds); + std::deque::const_iterator it; + for (it = m_conns.begin(); it != m_conns.end(); ++it) + FD_SET((*it)->sock(), &fds); } -//----------------------------------------------------------------------------- -inline -void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8) -{ -// len8 - длина в 8-ми байтовых блоках -if (dst != src) - memcpy(dst, src, len8 * 8); -for (size_t i = 0; i < len8; i++) - Blowfish_Encrypt(ctx, static_cast(dst) + i * 2, static_cast(dst) + i * 2 + 1); -} -//----------------------------------------------------------------------------- -inline -void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8) +void RADIUS::cleanupConns() { -// len8 - длина в 8-ми байтовых блоках -if (dst != src) - memcpy(dst, src, len8 * 8); + std::deque::iterator pos; + for (pos = m_conns.begin(); pos != m_conns.end(); ++pos) + if (((*pos)->isDone() && !(*pos)->isKeepAlive()) || !(*pos)->isOk()) { + delete *pos; + *pos = NULL; + } -for (size_t i = 0; i < len8; i++) - Blowfish_Decrypt(ctx, static_cast(dst) + i * 2, static_cast(dst) + i * 2 + 1); + pos = std::remove(m_conns.begin(), m_conns.end(), static_cast(NULL)); + m_conns.erase(pos, m_conns.end()); } -} // namespace anonymous +void RADIUS::handleEvents(const fd_set & fds) +{ + if (FD_ISSET(m_listenSocket, &fds)) + acceptConnection(); + else + { + std::deque::iterator it; + for (it = m_conns.begin(); it != m_conns.end(); ++it) + if (FD_ISSET((*it)->sock(), &fds)) + (*it)->read(); + } +} diff --git a/projects/stargazer/plugins/other/radius/radius.h b/projects/stargazer/plugins/other/radius/radius.h index 8f5ba2a4..ff8ecf5e 100644 --- a/projects/stargazer/plugins/other/radius/radius.h +++ b/projects/stargazer/plugins/other/radius/radius.h @@ -18,154 +18,77 @@ * Author : Maxim Mamontov */ -/* - * Radius data access plugin for Stargazer - * - * $Revision: 1.10 $ - * $Date: 2009/12/13 14:17:13 $ - * - */ - -#ifndef RADIUS_H -#define RADIUS_H - -#include - -#include -#include -#include -#include -#include -#include +#ifndef __STG_RADIUS_H__ +#define __STG_RADIUS_H__ #include "stg/os_int.h" #include "stg/auth.h" #include "stg/module_settings.h" -#include "stg/notifer.h" -#include "stg/user_ips.h" -#include "stg/user.h" -#include "stg/users.h" -#include "stg/blowfish.h" -#include "stg/rad_packets.h" #include "stg/logger.h" -extern "C" PLUGIN * GetPlugin(); +#include -#define RAD_DEBUG (1) +#include +#include +#include +#include -class RADIUS; -//----------------------------------------------------------------------------- -class RAD_SETTINGS { -public: - RAD_SETTINGS() - : port(0), errorStr(), password(), - authServices(), acctServices() - {} - virtual ~RAD_SETTINGS() {} - const std::string & GetStrError() const { return errorStr; } - int ParseSettings(const MODULE_SETTINGS & s); - uint16_t GetPort() const { return port; } - const std::string & GetPassword() const { return password; } - const std::list & GetAuthServices() const { return authServices; } - const std::list & GetAcctServices() const { return acctServices; } +extern "C" PLUGIN * GetPlugin(); -private: - int ParseServices(const std::vector & str, std::list * lst); +class STORE; +class USERS; - uint16_t port; - std::string errorStr; - std::string password; - std::list authServices; - std::list acctServices; -}; -//----------------------------------------------------------------------------- -struct RAD_SESSION { - RAD_SESSION() : userName(), serviceType() {} - std::string userName; - std::string serviceType; -}; -//----------------------------------------------------------------------------- -class RADIUS :public AUTH { +class RADIUS : public AUTH { public: - RADIUS(); - virtual ~RADIUS() {} + RADIUS(); + virtual ~RADIUS() {} - void SetUsers(USERS * u) { users = u; } - void SetStore(STORE * s) { store = s; } - void SetStgSettings(const SETTINGS *) {} - void SetSettings(const MODULE_SETTINGS & s) { settings = s; } - int ParseSettings(); + void SetUsers(USERS* u) { users = u; } + void SetStore(STORE* s) { store = s; } + void SetStgSettings(const SETTINGS*) {} + void SetSettings(const MODULE_SETTINGS& s) { settings = s; } + int ParseSettings(); - int Start(); - int Stop(); - int Reload() { return 0; } - bool IsRunning() { return isRunning; } + int Start(); + int Stop(); + int Reload() { return 0; } + bool IsRunning() { return m_running; } - const std::string & GetStrError() const { return errorStr; } - std::string GetVersion() const { return "RADIUS data access plugin v 0.6"; } - uint16_t GetStartPosition() const { return 30; } - uint16_t GetStopPosition() const { return 30; } + const std::string& GetStrError() const { return m_error; } + std::string GetVersion() const { return "RADIUS data access plugin v 1.0"; } + uint16_t GetStartPosition() const { return 30; } + uint16_t GetStopPosition() const { return 30; } - int SendMessage(const STG_MSG &, uint32_t) const { return 0; } + int SendMessage(const STG_MSG&, uint32_t) const { return 0; } private: RADIUS(const RADIUS & rvalue); RADIUS & operator=(const RADIUS & rvalue); - static void * Run(void *); - int PrepareNet(); - int FinalizeNet(); - - ssize_t Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr); - int RecvData(RAD_PACKET * packet, struct sockaddr_in * outerAddr); - int ProcessData(RAD_PACKET * packet); - - int ProcessAutzPacket(RAD_PACKET * packet); - int ProcessAuthPacket(RAD_PACKET * packet); - int ProcessPostAuthPacket(RAD_PACKET * packet); - int ProcessAcctStartPacket(RAD_PACKET * packet); - int ProcessAcctStopPacket(RAD_PACKET * packet); - int ProcessAcctUpdatePacket(RAD_PACKET * packet); - int ProcessAcctOtherPacket(RAD_PACKET * packet); - - bool FindUser(USER_PTR * ui, const std::string & login) const; - bool CanAuthService(const std::string & svc) const; - bool CanAcctService(const std::string & svc) const; - bool IsAllowedService(const std::string & svc) const; - - struct SPrinter : public std::unary_function, void> - { - void operator()(const std::pair & it) - { - printfd("radius.cpp", "%s - ('%s', '%s')\n", it.first.c_str(), it.second.userName.c_str(), it.second.serviceType.c_str()); - } - }; - - BLOWFISH_CTX ctx; + static void* run(void*); - mutable std::string errorStr; - RAD_SETTINGS radSettings; - MODULE_SETTINGS settings; - std::list authServices; - std::list acctServices; - std::map sessions; + void rumImpl(); + int maxFD() const; + void buildFDSet(fd_set & fds) const; + void cleanupConns(); + void handleEvents(const fd_set & fds); + void acceptConnection(); - bool nonstop; - bool isRunning; + mutable std::string m_error; + STG::Config m_config; - USERS * users; - const SETTINGS * stgSettings; - const STORE * store; + MODULE_SETTINGS m_settings; - pthread_t thread; - pthread_mutex_t mutex; + bool m_running; + bool m_stopped; - int sock; + USERS* m_users; + const STORE* m_store; - RAD_PACKET packet; + pthread_t m_thread; + pthread_mutex_t m_mutex; - PLUGIN_LOGGER logger; + PLUGIN_LOGGER m_logger; }; -//----------------------------------------------------------------------------- #endif diff --git a/projects/stargazer/plugins/other/radius/reader.cpp b/projects/stargazer/plugins/other/radius/reader.cpp new file mode 100644 index 00000000..e7d3e2fa --- /dev/null +++ b/projects/stargazer/plugins/other/radius/reader.cpp @@ -0,0 +1,7 @@ +#include "reader.h" + +using STG::Reader; + +Reader::Reader() +{ +} diff --git a/projects/stargazer/plugins/other/radius/reader.h b/projects/stargazer/plugins/other/radius/reader.h new file mode 100644 index 00000000..3bc1f9e6 --- /dev/null +++ b/projects/stargazer/plugins/other/radius/reader.h @@ -0,0 +1,170 @@ +/* + * This program 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 2 of the License, or + * (at your option) any later version. + * + * This program 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 this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + +#ifndef __STG_SGCONFIG_READER_H__ +#define __STG_SGCONFIG_READER_H__ + +#include +#include +#include + +namespace STG +{ + +struct BaseReader +{ + virtual ~BaseReader() {} + + virtual ssize_t read(TransportProto& proto) = 0; + virtual bool done() const = 0; +}; + +template +class Reader : public BaseReader +{ + public: + Reader(size_t size = sizeof(T)) : m_size(size), m_done(0) {} + + virtual ssize_t read(TransportProto& proto) + { + char* pos = static_cast(&m_dest); + pos += m_done; + ssize_t res = proto.read(pos, m_size - m_done); + if (res < 0) + return res; + if (res == 0) { + m_done = m_size; + return 0; + } + m_done += res; + return res; + } + + virtual bool done() const { return m_done == m_size; } + + T get() const { return ntoh(m_dest); } + + private: + T m_dest; + size_t m_size; + size_t m_done; + +}; + +template <> +class Reader > : public BaseReader +{ + public: + Reader(const std::vector& readers) : m_size(readers.size()), m_done(0) {} + + virtual ssize_t read(TransportProto& proto) + { + if (m_size == 0) + return 0; + size_t res = m_dest[m_done]->read(proto); + if (res < 0) + return res; + if (res == 0) { + m_done = m_size; + return 0; + } + if (m_dest[m_done].done()) + ++m_dest; + return res; + } + + virtual bool done() const { return m_done == m_size; } + + const T& get() const { return m_dest; } + + private: + T m_dest; + size_t m_size; + size_t m_done; + +}; + +template <> +class Reader > : public BaseReader +{ + public: + Reader(size_t size ) : m_dest(size), m_size(size), m_done(0) {} + + virtual ssize_t read(TransportProto& proto) + { + char* pos = static_cast(m_dest.data()); + pos += m_done; + ssize_t res = proto.read(pos, m_size - m_done); + if (res < 0) + return res; + if (res == 0) { + m_done = m_size; + return 0; + } + m_done += res; + return res; + } + + virtual bool done() const { return m_done == m_size; } + + const std::vector& get() const { return m_dest; } + + private: + std::vector m_dest; + size_t m_size; + size_t m_done; + +}; + +template <> +class Reader +{ + public: + Reader() : m_dest(Reader::initDest()) {} + + virtual ssize_t read(TransportProto& proto) + { + if (m_size == 0) + return 0; + size_t res = m_dest[m_done]->read(proto); + if (res < 0) + return res; + if (res == 0) { + m_done = m_size; + return 0; + } + if (m_dest[m_done].done()) + ++m_dest; + return res; + } + + virtual bool done() const { return m_done == m_size; } + + const T& get() const { return m_dest; } + + private: + T m_dest; + size_t m_size; + size_t m_done; +}; + +} // namespace STG + +#endif