basesecurity.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (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 Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #pragma warning (disable : 4786)
  15. #pragma warning (disable : 4018)
  16. #pragma warning (disable : 4146)
  17. #pragma warning (disable : 4275)
  18. #ifdef _WIN32
  19. #define AXA_API __declspec(dllexport)
  20. #endif
  21. //#include "ctconnection.h"
  22. #include "basesecurity.hpp"
  23. #include "jmd5.hpp"
  24. #define cacheTimeout 30000
  25. //#ifdef _WIN32
  26. CBaseSecurityManager::CBaseSecurityManager(const char *serviceName, const char *config)
  27. {
  28. Owned<IPropertyTree> cfg = createPTreeFromXMLString(config, ipt_caseInsensitive);
  29. if(cfg.get() == NULL)
  30. throw MakeStringException(-1, "createPTreeFromXMLString() failed for %s", config);
  31. init(serviceName,cfg);
  32. cfg->Release();
  33. }
  34. CBaseSecurityManager::CBaseSecurityManager(const char *serviceName, IPropertyTree *config)
  35. {
  36. m_dbpasswordEncoding = SecPwEnc_unknown;
  37. init(serviceName,config);
  38. }
  39. void CBaseSecurityManager::init(const char *serviceName, IPropertyTree *config)
  40. {
  41. if(config == NULL)
  42. return;
  43. m_config.set(config);
  44. m_permissionsCache.setCacheTimeout( 60 * config->getPropInt("@cacheTimeout", 5) );
  45. m_dbserver.appendf("%s",config->queryProp("@serverName"));
  46. m_dbuser.appendf("%s",config->queryProp("@systemUser"));
  47. if(config->hasProp("@ConnectionPoolSize"))
  48. m_poolsize = atoi(config->queryProp("@connectionPoolSize"));
  49. else
  50. m_poolsize = 2;
  51. StringBuffer encodedPass,encryptedPass;
  52. encodedPass.appendf("%s",config->queryProp("@systemPassword"));
  53. decrypt(m_dbpassword, encodedPass.str());
  54. m_dbpasswordEncoding = SecPwEnc_plain_text;
  55. StringBuffer strPasswordEncoding;
  56. const char* encodingType = config->queryProp("@encodePassword");
  57. if(encodingType && strcmp(encodingType,"MD5") == 0)
  58. m_dbpasswordEncoding=SecPwEnc_salt_md5;
  59. else if (encodingType && strcmp(encodingType,"Rijndael") == 0)
  60. m_dbpasswordEncoding=SecPwEnc_Rijndael;
  61. else if (encodingType && strcmp(encodingType,"Accurint MD5") == 0)
  62. m_dbpasswordEncoding = SecPwEnc_salt_accurint_md5;
  63. if(m_dbserver.length() == 0 || m_dbuser.length() == 0)
  64. throw MakeStringException(-1, "CBaseSecurityManager() - db server or user is missing");
  65. IPropertyTree* pNonRestrictedIPTree = config->queryBranch("SafeIPList");
  66. if(pNonRestrictedIPTree)
  67. {
  68. Owned<IPropertyTreeIterator> Itr = pNonRestrictedIPTree->getElements("ip");
  69. for(Itr->first();Itr->isValid();Itr->next())
  70. {
  71. IPropertyTree& tree = Itr->query();
  72. m_safeIPList[tree.queryProp("")]=true;
  73. }
  74. }
  75. m_enableIPRoaming = config->getPropBool("@enableIPRoaming");
  76. m_enableOTP = config->getPropBool("@enableOTP",false);
  77. m_passwordExpirationWarningDays = config->getPropInt(".//@passwordExpirationWarningDays", 10); //Default to 10 days
  78. }
  79. CBaseSecurityManager::~CBaseSecurityManager()
  80. {
  81. MapStrToUsers::iterator pos;
  82. for(pos=m_userList.begin();pos!=m_userList.end();){
  83. pos->second->Release();
  84. pos++;
  85. }
  86. dbDisconnect();
  87. }
  88. //interface ISecManager : extends IInterface
  89. ISecUser * CBaseSecurityManager::createUser(const char * user_name)
  90. {
  91. return (new CSecureUser(user_name, NULL));
  92. }
  93. ISecResourceList * CBaseSecurityManager::createResourceList(const char * rlname)
  94. {
  95. return (new CSecurityResourceList(rlname));
  96. }
  97. bool CBaseSecurityManager::subscribe(ISecAuthenticEvents & events)
  98. {
  99. m_subscriber.set(&events);
  100. return true;
  101. }
  102. bool CBaseSecurityManager::unsubscribe(ISecAuthenticEvents & events)
  103. {
  104. if (&events == m_subscriber.get())
  105. {
  106. m_subscriber.set(NULL);
  107. }
  108. return true;
  109. }
  110. bool CBaseSecurityManager::authorize(ISecUser & sec_user, ISecResourceList * Resources)
  111. {
  112. if(!sec_user.isAuthenticated())
  113. {
  114. bool bOk = ValidateUser(sec_user);
  115. if(bOk == false)
  116. return false;
  117. }
  118. return ValidateResources(sec_user,Resources);
  119. }
  120. bool CBaseSecurityManager::updateSettings(ISecUser &sec_user, ISecPropertyList* resources)
  121. {
  122. CSecurityResourceList * reslist = (CSecurityResourceList*)resources;
  123. if(!reslist)
  124. return true;
  125. IArrayOf<ISecResource>& rlist = reslist->getResourceList();
  126. int nResources = rlist.length();
  127. if (nResources <= 0)
  128. return true;
  129. bool rc = false;
  130. if (m_permissionsCache.isCacheEnabled()==false)
  131. return updateSettings(sec_user, rlist);
  132. bool* cached_found = (bool*)alloca(nResources*sizeof(bool));
  133. int nFound = m_permissionsCache.lookup(sec_user, rlist, cached_found);
  134. if (nFound >= nResources)
  135. return true;
  136. IArrayOf<ISecResource> rlist2;
  137. for (int i=0; i < nResources; i++)
  138. {
  139. if (*(cached_found+i) == false)
  140. {
  141. ISecResource& secRes = rlist.item(i);
  142. secRes.Link();
  143. rlist2.append(secRes);
  144. }
  145. }
  146. rc = updateSettings(sec_user, rlist2);
  147. if (rc)
  148. m_permissionsCache.add(sec_user, rlist2);
  149. return rc;
  150. }
  151. bool CBaseSecurityManager::updateSettings(ISecUser & sec_user,IArrayOf<ISecResource>& rlist)
  152. {
  153. CSecureUser* user = (CSecureUser*)&sec_user;
  154. if(user == NULL)
  155. return false;
  156. int usernum = findUser(user->getName(),user->getRealm());
  157. if(usernum < 0)
  158. {
  159. PrintLog("User number of %s can't be found", user->getName());
  160. return false;
  161. }
  162. bool sqchecked = false, sqverified = false, otpchecked = false;
  163. int otpok = -1;
  164. ForEachItemIn(x, rlist)
  165. {
  166. ISecResource* secRes = (ISecResource*)(&(rlist.item(x)));
  167. if(secRes == NULL)
  168. continue;
  169. //AccessFlags default value is -1. Set it to 0 so that the settings can be cached. AccessFlags is not being used for settings.
  170. secRes->setAccessFlags(0);
  171. if(secRes->getParameter("userprop") && *secRes->getParameter("userprop")!='\0')
  172. {
  173. //if we have a parameter in the user or company table it will have been added as a parameter to the ISecUser when
  174. // the authentication query was run. We should keep this messiness here so that the the end user is insulated....
  175. dbValidateSetting(*secRes,sec_user);
  176. continue;
  177. }
  178. const char* resource_name = secRes->getParameter("resource");
  179. if(resource_name && *resource_name &&
  180. (stricmp(resource_name, "SSN Masking") == 0 || stricmp(resource_name, "Driver License Masking") == 0))
  181. {
  182. //If OTP Enabled and OTP2FACTOR cookie not valid, mask
  183. if(m_enableOTP)
  184. {
  185. if(!otpchecked)
  186. {
  187. const char* otpcookie = sec_user.getProperty("OTP2FACTOR");
  188. // -1 means OTP is not enabled for the user. 0: failed verfication, 1: passed verification.
  189. otpok = validateOTP(&sec_user, otpcookie);
  190. otpchecked = true;
  191. }
  192. if(otpok == 0)
  193. {
  194. CSecurityResource* cres = dynamic_cast<CSecurityResource*>(secRes);
  195. if(resource_name && *resource_name && cres)
  196. {
  197. if(stricmp(resource_name, "SSN Masking") == 0)
  198. {
  199. cres->setValue("All");
  200. continue;
  201. }
  202. else if(stricmp(resource_name, "Driver License Masking") == 0)
  203. {
  204. cres->setValue("1");
  205. continue;
  206. }
  207. }
  208. }
  209. else if(otpok == 1)
  210. {
  211. CSecurityResource* cres = dynamic_cast<CSecurityResource*>(secRes);
  212. if(resource_name && *resource_name && cres)
  213. {
  214. if(stricmp(resource_name, "SSN Masking") == 0)
  215. {
  216. cres->setValue("None");
  217. continue;
  218. }
  219. else if(stricmp(resource_name, "Driver License Masking") == 0)
  220. {
  221. cres->setValue("0");
  222. continue;
  223. }
  224. }
  225. }
  226. }
  227. if(m_enableIPRoaming && sec_user.getPropertyInt("IPRoaming") == 1)
  228. {
  229. if(!sqchecked)
  230. {
  231. const char* sequest = sec_user.getProperty("SEQUEST");
  232. if(sequest && *sequest)
  233. {
  234. sqverified = validateSecurityQuestion(&sec_user, sequest);
  235. }
  236. sqchecked = true;
  237. }
  238. if(!sqverified)
  239. {
  240. CSecurityResource* cres = dynamic_cast<CSecurityResource*>(secRes);
  241. if(resource_name && *resource_name && cres)
  242. {
  243. if(stricmp(resource_name, "SSN Masking") == 0)
  244. {
  245. cres->setValue("All");
  246. continue;
  247. }
  248. else if(stricmp(resource_name, "Driver License Masking") == 0)
  249. {
  250. cres->setValue("1");
  251. continue;
  252. }
  253. }
  254. }
  255. }
  256. }
  257. dbValidateSetting(*secRes,usernum,user->getRealm());
  258. }
  259. return true;
  260. }
  261. bool CBaseSecurityManager::ValidateResources(ISecUser & sec_user, ISecResourceList * resources)
  262. {
  263. CSecurityResourceList * reslist = (CSecurityResourceList*)resources;
  264. if(!reslist)
  265. return true;
  266. IArrayOf<ISecResource>& rlist = reslist->getResourceList();
  267. int nResources = rlist.length();
  268. if (nResources <= 0)
  269. return true;
  270. bool rc = false;
  271. if (m_permissionsCache.isCacheEnabled()==false)
  272. return ValidateResources(sec_user, rlist);
  273. bool* cached_found = (bool*)alloca(nResources*sizeof(bool));
  274. int nFound = m_permissionsCache.lookup(sec_user, rlist, cached_found);
  275. if (nFound >= nResources)
  276. {
  277. return true;
  278. }
  279. IArrayOf<ISecResource> rlist2;
  280. for (int i=0; i < nResources; i++)
  281. {
  282. if (*(cached_found+i) == false)
  283. {
  284. ISecResource& secRes = rlist.item(i);
  285. secRes.Link();
  286. rlist2.append(secRes);
  287. }
  288. }
  289. rc = ValidateResources(sec_user, rlist2);
  290. if (rc)
  291. {
  292. IArrayOf<ISecResource> rlistValid;
  293. for (int i=0; i < rlist2.ordinality(); i++)
  294. {
  295. ISecResource& secRes = rlist2.item(i);
  296. if(secRes.getAccessFlags() >= secRes.getRequiredAccessFlags() || secRes.getAccessFlags() == SecAccess_Unknown)
  297. {
  298. secRes.Link();
  299. rlistValid.append(secRes);
  300. }
  301. }
  302. m_permissionsCache.add(sec_user, rlistValid);
  303. }
  304. return rc;
  305. }
  306. static bool stringDiff(const char* str1, const char* str2)
  307. {
  308. if(!str1 || !*str1)
  309. {
  310. if(!str2 || !*str2)
  311. return false;
  312. else
  313. return true;
  314. }
  315. else
  316. {
  317. if(!str2 || !*str2)
  318. return true;
  319. else
  320. return (strcmp(str1, str2) != 0);
  321. }
  322. }
  323. bool CBaseSecurityManager::ValidateUser(ISecUser & sec_user)
  324. {
  325. StringBuffer clientip(sec_user.getPeer());
  326. StringBuffer otpbuf, sqbuf;
  327. if(m_enableOTP)
  328. {
  329. otpbuf.append(sec_user.getProperty("OTP2FACTOR"));
  330. }
  331. if(m_enableIPRoaming)
  332. {
  333. sqbuf.append(sec_user.getProperty("SEQUEST"));
  334. }
  335. if(m_permissionsCache.isCacheEnabled() && m_permissionsCache.lookup(sec_user))
  336. {
  337. bool bReturn = true;
  338. if(IsIPRestricted(sec_user))
  339. {
  340. const char* cachedclientip = sec_user.getPeer();
  341. if(clientip.length() > 0 && cachedclientip && strncmp(clientip.str(), cachedclientip , clientip.length()) != 0)
  342. {
  343. //we seem to be coming from a different peer... this is not good
  344. WARNLOG("Found user %d in cache, but have to re-validate IP, because it was coming from %s but is now coming from %s",sec_user.getUserID(), cachedclientip, clientip.str());
  345. sec_user.setAuthenticated(false);
  346. sec_user.setPeer(clientip.str());
  347. m_permissionsCache.removeFromUserCache(sec_user);
  348. bReturn = false;
  349. }
  350. }
  351. if(m_enableOTP)
  352. {
  353. const char* old_otp = sec_user.getProperty("OTP2FACTOR");
  354. if(stringDiff(old_otp, otpbuf.str()))
  355. bReturn = false;
  356. }
  357. if(m_enableIPRoaming)
  358. {
  359. const char* old_sq = sec_user.getProperty("SEQUEST");
  360. if(stringDiff(old_sq, sqbuf.str()))
  361. bReturn = false;
  362. }
  363. if(bReturn)
  364. {
  365. sec_user.setAuthenticated(true);
  366. return true;
  367. }
  368. }
  369. if(!IsPasswordValid(sec_user))
  370. {
  371. ERRLOG("Password validation failed for user: %s",sec_user.getName());
  372. return false;
  373. }
  374. else
  375. {
  376. if(IsIPRestricted(sec_user)==true)
  377. {
  378. if(ValidateSourceIP(sec_user,m_safeIPList)==false)
  379. {
  380. ERRLOG("IP check failed for user:%s coming from %s",sec_user.getName(),sec_user.getPeer());
  381. sec_user.setAuthenticated(false);
  382. return false;
  383. }
  384. }
  385. if(m_permissionsCache.isCacheEnabled())
  386. m_permissionsCache.add(sec_user);
  387. sec_user.setAuthenticated(true);
  388. }
  389. return true;
  390. }
  391. bool CBaseSecurityManager::IsPasswordValid(ISecUser& sec_user)
  392. {
  393. StringBuffer password(sec_user.credentials().getPassword());
  394. EncodePassword(password);
  395. StringBuffer SQLQuery;
  396. buildAuthenticateQuery(sec_user.getName(),password.str(),sec_user.getRealm(),SQLQuery);
  397. return dbauthenticate(sec_user , SQLQuery);
  398. }
  399. bool CBaseSecurityManager::IsIPRestricted(ISecUser& sec_user)
  400. {
  401. const char* iprestricted = sec_user.getProperty("iprestricted");
  402. if(iprestricted!=NULL && strncmp(iprestricted,"1",1)==0)
  403. return true;
  404. return false;
  405. }
  406. void CBaseSecurityManager::EncodePassword(StringBuffer& password)
  407. {
  408. StringBuffer encodedPassword;
  409. switch (m_dbpasswordEncoding)
  410. {
  411. case SecPwEnc_salt_md5:
  412. md5_string(password,encodedPassword);
  413. password.clear().append(encodedPassword.str());
  414. break;
  415. case SecPwEnc_Rijndael:
  416. encrypt(encodedPassword,password.str());
  417. password.clear().append(encodedPassword.str());
  418. break;
  419. case SecPwEnc_salt_accurint_md5:
  420. password.toUpperCase();
  421. md5_string(password,encodedPassword);
  422. password.clear().append(encodedPassword.str());
  423. break;
  424. }
  425. }
  426. bool CBaseSecurityManager::addResources(ISecUser & sec_user, ISecResourceList * Resources)
  427. {
  428. return false;
  429. }
  430. bool CBaseSecurityManager::addUser(ISecUser & user)
  431. {
  432. return false;
  433. }
  434. int CBaseSecurityManager::getUserID(ISecUser& user)
  435. {
  436. return findUser(user.getName(),user.getRealm());
  437. }
  438. bool CBaseSecurityManager::ValidateResources(ISecUser & sec_user,IArrayOf<ISecResource>& rlist)
  439. {
  440. CSecureUser* user = (CSecureUser*)&sec_user;
  441. if(user == NULL)
  442. return false;
  443. int usernum = findUser(user->getName(),user->getRealm());
  444. if(usernum < 0)
  445. {
  446. PrintLog("User number of %s can't be found", user->getName());
  447. return false;
  448. }
  449. ForEachItemIn(x, rlist)
  450. {
  451. ISecResource* res = (ISecResource*)(&(rlist.item(x)));
  452. if(res == NULL)
  453. continue;
  454. dbValidateResource(*res,usernum,user->getRealm());
  455. }
  456. return true;
  457. }
  458. bool CBaseSecurityManager::updateResources(ISecUser & user, ISecResourceList * resources)
  459. {
  460. //("CBaseSecurityManager::updateResources");
  461. if(!resources)
  462. return false;
  463. const char* username = user.getName();
  464. //const char* realm = user.getRealm();
  465. const char* realm = NULL;
  466. int usernum = findUser(username,realm);
  467. if(usernum <= 0)
  468. {
  469. PrintLog("User number of %s can't be found", username);
  470. return false;
  471. }
  472. CSecurityResourceList * reslist = (CSecurityResourceList*)resources;
  473. if (reslist)
  474. {
  475. IArrayOf<ISecResource>& rlist = reslist->getResourceList();
  476. ForEachItemIn(x, rlist)
  477. {
  478. ISecResource* res = (ISecResource*)(&(rlist.item(x)));
  479. if(res == NULL)
  480. continue;
  481. dbUpdateResource(*res,usernum,realm);
  482. }
  483. }
  484. return true;
  485. }
  486. bool CBaseSecurityManager::updateUser(ISecUser& user, const char* newPassword)
  487. {
  488. //("CBaseSecurityManager::updateUser");
  489. if(!newPassword)
  490. return false;
  491. StringBuffer password(newPassword);
  492. EncodePassword(password);
  493. const char* realm = NULL;
  494. bool bReturn = dbUpdatePasswrd(user.getName(),realm,password.str());
  495. if(bReturn == true)
  496. user.credentials().setPassword(password.str());
  497. //need to flush the users info from the cache....
  498. if(m_permissionsCache.isCacheEnabled())
  499. m_permissionsCache.removeFromUserCache(user);
  500. return bReturn;
  501. }
  502. void CBaseSecurityManager::logon_failed(const char* user, const char* msg)
  503. {
  504. PrintLog("%s: %s", user, msg);
  505. }
  506. int CBaseSecurityManager::findUser(const char* user,const char* realm)
  507. {
  508. if(user == NULL)
  509. return -1;
  510. synchronized block(m_usermap_mutex);
  511. int* uidptr = m_usermap.getValue(user);
  512. if(uidptr != NULL)
  513. {
  514. return *uidptr;
  515. }
  516. else
  517. {
  518. int uid = dbLookupUser(user,realm);
  519. if(uid >= 0)
  520. {
  521. m_usermap.setValue(user, uid);
  522. }
  523. return uid;
  524. }
  525. }
  526. //#endif //_WIN32