2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 * Author : Maxim Mamontov <faust@stargazer.dp.ua>
22 * This file contains a realization of radius data access plugin for Stargazer
25 * $Date: 2009/12/13 14:17:13 $
33 #include "stg/store.h"
34 #include "stg/common.h"
35 #include "stg/user_conf.h"
36 #include "stg/user_property.h"
37 #include "stg/plugin_creator.h"
40 extern volatile const time_t stgTime;
42 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
43 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
44 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
46 //-----------------------------------------------------------------------------
47 //-----------------------------------------------------------------------------
48 //-----------------------------------------------------------------------------
49 PLUGIN_CREATOR<RADIUS> radc;
50 //-----------------------------------------------------------------------------
51 //-----------------------------------------------------------------------------
52 //-----------------------------------------------------------------------------
55 return radc.GetPlugin();
57 //-----------------------------------------------------------------------------
58 //-----------------------------------------------------------------------------
59 //-----------------------------------------------------------------------------
60 int RAD_SETTINGS::ParseServices(const std::vector<std::string> & str, std::list<std::string> * lst)
62 std::copy(str.begin(), str.end(), std::back_inserter(*lst));
63 std::list<std::string>::iterator it(std::find(lst->begin(),
71 //-----------------------------------------------------------------------------
72 int RAD_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
76 std::vector<PARAM_VALUE>::const_iterator pvi;
77 ///////////////////////////
79 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
80 if (pvi == s.moduleParams.end())
82 errorStr = "Parameter \'Port\' not found.";
83 printfd(__FILE__, "Parameter 'Port' not found\n");
86 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
88 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
89 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
93 ///////////////////////////
94 pv.param = "Password";
95 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
96 if (pvi == s.moduleParams.end())
98 errorStr = "Parameter \'Password\' not found.";
99 printfd(__FILE__, "Parameter 'Password' not found\n");
102 password = pvi->value[0];
103 ///////////////////////////
104 pv.param = "AuthServices";
105 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
106 if (pvi != s.moduleParams.end())
108 ParseServices(pvi->value, &authServices);
110 ///////////////////////////
111 pv.param = "AcctServices";
112 pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
113 if (pvi != s.moduleParams.end())
115 ParseServices(pvi->value, &acctServices);
120 //-----------------------------------------------------------------------------
121 //-----------------------------------------------------------------------------
122 //-----------------------------------------------------------------------------
140 logger(GetPluginLogger(GetStgLogger(), "radius"))
142 InitEncrypt(&ctx, "");
144 //-----------------------------------------------------------------------------
145 int RADIUS::ParseSettings()
147 int ret = radSettings.ParseSettings(settings);
149 errorStr = radSettings.GetStrError();
152 //-----------------------------------------------------------------------------
153 int RADIUS::PrepareNet()
155 sock = socket(AF_INET, SOCK_DGRAM, 0);
159 errorStr = "Cannot create socket.";
160 logger("Cannot create a socket: %s", strerror(errno));
161 printfd(__FILE__, "Cannot create socket\n");
165 struct sockaddr_in inAddr;
166 inAddr.sin_family = AF_INET;
167 inAddr.sin_port = htons(radSettings.GetPort());
168 inAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
170 if (bind(sock, (struct sockaddr*)&inAddr, sizeof(inAddr)) < 0)
172 errorStr = "RADIUS: Bind failed.";
173 logger("Cannot bind the socket: %s", strerror(errno));
174 printfd(__FILE__, "Cannot bind socket\n");
180 //-----------------------------------------------------------------------------
181 int RADIUS::FinalizeNet()
186 //-----------------------------------------------------------------------------
189 std::string password(radSettings.GetPassword());
191 authServices = radSettings.GetAuthServices();
192 acctServices = radSettings.GetAcctServices();
194 InitEncrypt(&ctx, password);
205 if (pthread_create(&thread, NULL, Run, this))
207 errorStr = "Cannot create thread.";
208 logger("Cannot create thread.");
209 printfd(__FILE__, "Cannot create thread\n");
217 //-----------------------------------------------------------------------------
225 std::map<std::string, RAD_SESSION>::iterator it;
226 for (it = sessions.begin(); it != sessions.end(); ++it)
229 if (users->FindByName(it->second.userName, &ui))
231 users->Unauthorize(ui->GetLogin(), this);
234 sessions.erase(sessions.begin(), sessions.end());
240 //5 seconds to thread stops itself
241 for (int i = 0; i < 25 && isRunning; i++)
243 struct timespec ts = {0, 200000000};
244 nanosleep(&ts, NULL);
253 //-----------------------------------------------------------------------------
254 void * RADIUS::Run(void * d)
257 sigfillset(&signalSet);
258 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
260 RADIUS * rad = (RADIUS *)d;
263 rad->isRunning = true;
267 if (!WaitPackets(rad->sock))
271 struct sockaddr_in outerAddr;
272 if (rad->RecvData(&packet, &outerAddr))
274 printfd(__FILE__, "RADIUS::Run Error on RecvData\n");
278 if (rad->ProcessData(&packet))
280 packet.packetType = RAD_REJECT_PACKET;
282 rad->Send(packet, &outerAddr);
286 rad->isRunning = false;
290 //-----------------------------------------------------------------------------
291 int RADIUS::RecvData(RAD_PACKET * packet, struct sockaddr_in * outerAddr)
293 int8_t buf[RAD_MAX_PACKET_LEN];
294 socklen_t outerAddrLen = sizeof(struct sockaddr_in);
295 int dataLen = recvfrom(sock, buf, RAD_MAX_PACKET_LEN, 0, reinterpret_cast<struct sockaddr *>(outerAddr), &outerAddrLen);
298 logger("recvfrom error: %s", strerror(errno));
304 Decrypt(&ctx, (char *)packet, (const char *)buf, dataLen / 8);
306 if (strncmp((char *)packet->magic, RAD_ID, RAD_MAGIC_LEN))
308 printfd(__FILE__, "RADIUS::RecvData Error magic. Wanted: '%s', got: '%s'\n", RAD_ID, packet->magic);
314 //-----------------------------------------------------------------------------
315 int RADIUS::Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr)
317 size_t len = sizeof(RAD_PACKET);
320 Encrypt(&ctx, buf, (char *)&packet, len / 8);
321 int res = sendto(sock, buf, len, 0, reinterpret_cast<struct sockaddr *>(outerAddr), sizeof(struct sockaddr_in));
323 logger("sendto error: %s", strerror(errno));
326 //-----------------------------------------------------------------------------
327 int RADIUS::ProcessData(RAD_PACKET * packet)
329 if (strncmp((const char *)packet->protoVer, "01", 2))
331 printfd(__FILE__, "RADIUS::ProcessData packet.protoVer incorrect\n");
334 switch (packet->packetType)
336 case RAD_AUTZ_PACKET:
337 return ProcessAutzPacket(packet);
338 case RAD_AUTH_PACKET:
339 return ProcessAuthPacket(packet);
340 case RAD_POST_AUTH_PACKET:
341 return ProcessPostAuthPacket(packet);
342 case RAD_ACCT_START_PACKET:
343 return ProcessAcctStartPacket(packet);
344 case RAD_ACCT_STOP_PACKET:
345 return ProcessAcctStopPacket(packet);
346 case RAD_ACCT_UPDATE_PACKET:
347 return ProcessAcctUpdatePacket(packet);
348 case RAD_ACCT_OTHER_PACKET:
349 return ProcessAcctOtherPacket(packet);
351 printfd(__FILE__, "RADIUS::ProcessData Unsupported packet type: %d\n", packet->packetType);
356 //-----------------------------------------------------------------------------
357 int RADIUS::ProcessAutzPacket(RAD_PACKET * packet)
361 if (!IsAllowedService((char *)packet->service))
363 printfd(__FILE__, "RADIUS::ProcessAutzPacket service '%s' is not allowed to authorize\n", packet->service);
364 packet->packetType = RAD_REJECT_PACKET;
368 if (store->RestoreUserConf(&conf, (char *)packet->login))
370 packet->packetType = RAD_REJECT_PACKET;
371 printfd(__FILE__, "RADIUS::ProcessAutzPacket cannot restore conf for user '%s'\n", packet->login);
375 // At this point service can be authorized at least
376 // So we send a plain-text password
378 packet->packetType = RAD_ACCEPT_PACKET;
379 strncpy((char *)packet->password, conf.password.c_str(), RAD_PASSWORD_LEN);
383 //-----------------------------------------------------------------------------
384 int RADIUS::ProcessAuthPacket(RAD_PACKET * packet)
388 if (!CanAcctService((char *)packet->service))
391 // There are no sense to check for allowed service
392 // It has allready checked at previous stage (authorization)
394 printfd(__FILE__, "RADIUS::ProcessAuthPacket service '%s' neednot stargazer authentication\n", (char *)packet->service);
395 packet->packetType = RAD_ACCEPT_PACKET;
399 // At this point we have an accountable service
400 // All other services got a password if allowed or rejected
402 if (!FindUser(&ui, (char *)packet->login))
404 packet->packetType = RAD_REJECT_PACKET;
405 printfd(__FILE__, "RADIUS::ProcessAuthPacket user '%s' not found\n", (char *)packet->login);
409 if (ui->IsInetable())
411 packet->packetType = RAD_ACCEPT_PACKET;
415 packet->packetType = RAD_REJECT_PACKET;
418 packet->packetType = RAD_ACCEPT_PACKET;
421 //-----------------------------------------------------------------------------
422 int RADIUS::ProcessPostAuthPacket(RAD_PACKET * packet)
426 if (!CanAcctService((char *)packet->service))
429 // There are no sense to check for allowed service
430 // It has allready checked at previous stage (authorization)
432 packet->packetType = RAD_ACCEPT_PACKET;
436 if (!FindUser(&ui, (char *)packet->login))
438 packet->packetType = RAD_REJECT_PACKET;
439 printfd(__FILE__, "RADIUS::ProcessPostAuthPacket user '%s' not found\n", (char *)packet->login);
443 // I think that only Framed-User services has sense to be accountable
444 // So we have to supply a Framed-IP
446 USER_IPS ips = ui->GetProperty().ips;
447 packet->packetType = RAD_ACCEPT_PACKET;
449 // Additional checking for Framed-User service
451 if (!strncmp((char *)packet->service, "Framed-User", RAD_SERVICE_LEN))
452 packet->ip = ips[0].ip;
458 //-----------------------------------------------------------------------------
459 int RADIUS::ProcessAcctStartPacket(RAD_PACKET * packet)
463 if (!FindUser(&ui, (char *)packet->login))
465 packet->packetType = RAD_REJECT_PACKET;
466 printfd(__FILE__, "RADIUS::ProcessAcctStartPacket user '%s' not found\n", (char *)packet->login);
470 // At this point we have to unauthorize user only if it is an accountable service
472 if (CanAcctService((char *)packet->service))
474 if (sessions.find((const char *)packet->sessid) != sessions.end())
476 printfd(__FILE__, "RADIUS::ProcessAcctStartPacket session already started!\n");
477 packet->packetType = RAD_REJECT_PACKET;
480 USER_IPS ips = ui->GetProperty().ips;
481 if (!users->Authorize(ui->GetLogin(), ips[0].ip, 0xffFFffFF, this))
483 printfd(__FILE__, "RADIUS::ProcessAcctStartPacket cannot authorize user '%s'\n", packet->login);
484 packet->packetType = RAD_REJECT_PACKET;
487 sessions[(const char *)packet->sessid].userName = (const char *)packet->login;
488 sessions[(const char *)packet->sessid].serviceType = (const char *)packet->service;
489 for_each(sessions.begin(), sessions.end(), SPrinter());
493 printfd(__FILE__, "RADIUS::ProcessAcctStartPacket service '%s' can not be accounted\n", (char *)packet->service);
496 packet->packetType = RAD_ACCEPT_PACKET;
499 //-----------------------------------------------------------------------------
500 int RADIUS::ProcessAcctStopPacket(RAD_PACKET * packet)
502 std::map<std::string, RAD_SESSION>::iterator sid;
504 if ((sid = sessions.find((const char *)packet->sessid)) == sessions.end())
506 printfd(__FILE__, "RADIUS::ProcessAcctStopPacket session had not started yet\n");
507 packet->packetType = RAD_REJECT_PACKET;
513 if (!FindUser(&ui, sid->second.userName))
515 packet->packetType = RAD_REJECT_PACKET;
516 printfd(__FILE__, "RADIUS::ProcessPostAuthPacket user '%s' not found\n", sid->second.userName.c_str());
522 users->Unauthorize(ui->GetLogin(), this);
524 packet->packetType = RAD_ACCEPT_PACKET;
527 //-----------------------------------------------------------------------------
528 int RADIUS::ProcessAcctUpdatePacket(RAD_PACKET * packet)
530 // Fake. May be use it later
531 packet->packetType = RAD_ACCEPT_PACKET;
534 //-----------------------------------------------------------------------------
535 int RADIUS::ProcessAcctOtherPacket(RAD_PACKET * packet)
537 // Fake. May be use it later
538 packet->packetType = RAD_ACCEPT_PACKET;
541 //-----------------------------------------------------------------------------
542 void RADIUS::PrintServices(const std::list<std::string> & svcs)
544 for_each(svcs.begin(), svcs.end(), Printer());
546 //-----------------------------------------------------------------------------
547 bool RADIUS::FindUser(USER_PTR * ui, const std::string & login) const
549 if (users->FindByName(login, ui))
555 //-----------------------------------------------------------------------------
556 bool RADIUS::CanAuthService(const std::string & svc) const
558 return find(authServices.begin(), authServices.end(), svc) != authServices.end();
560 //-----------------------------------------------------------------------------
561 bool RADIUS::CanAcctService(const std::string & svc) const
563 return find(acctServices.begin(), acctServices.end(), svc) != acctServices.end();
565 //-----------------------------------------------------------------------------
566 bool RADIUS::IsAllowedService(const std::string & svc) const
568 return CanAuthService(svc) || CanAcctService(svc);
570 //-----------------------------------------------------------------------------
572 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
574 unsigned char keyL[RAD_PASSWORD_LEN]; // Пароль для шифровки
575 memset(keyL, 0, RAD_PASSWORD_LEN);
576 strncpy((char *)keyL, password.c_str(), RAD_PASSWORD_LEN);
577 Blowfish_Init(ctx, keyL, RAD_PASSWORD_LEN);
579 //-----------------------------------------------------------------------------
581 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
583 // len8 - длина в 8-ми байтовых блоках
585 memcpy(dst, src, len8 * 8);
587 for (int i = 0; i < len8; i++)
588 Blowfish_Encrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4));
590 //-----------------------------------------------------------------------------
592 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
594 // len8 - длина в 8-ми байтовых блоках
596 memcpy(dst, src, len8 * 8);
598 for (int i = 0; i < len8; i++)
599 Blowfish_Decrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4));