htpasswdSecurity.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2013 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #pragma warning( disable : 4786 )
  14. #include "basesecurity.hpp"
  15. #include "authmap.ipp"
  16. #include <apr_md5.h>
  17. #include "htpasswdSecurity.hpp"
  18. class CHtpasswdSecurityManager : public CBaseSecurityManager
  19. {
  20. public:
  21. CHtpasswdSecurityManager(const char *serviceName, IPropertyTree *secMgrCfg, IPropertyTree *authConfig) : CBaseSecurityManager(serviceName, (IPropertyTree *)NULL)
  22. {
  23. if (secMgrCfg)
  24. pwFile.set(secMgrCfg->queryProp("@htpasswdFile"));
  25. if(pwFile.isEmpty())
  26. throw MakeStringException(-1, "htpasswdFile not found in configuration");
  27. apr_initialized = false;
  28. }
  29. ~CHtpasswdSecurityManager()
  30. {
  31. userMap.kill();
  32. }
  33. secManagerType querySecMgrType()
  34. {
  35. return SMT_HTPasswd;
  36. }
  37. inline virtual const char* querySecMgrTypeName() { return "htpasswd"; }
  38. IAuthMap * createAuthMap(IPropertyTree * authconfig)
  39. {
  40. CAuthMap* authmap = new CAuthMap(this);
  41. Owned<IPropertyTreeIterator> loc_iter;
  42. loc_iter.setown(authconfig->getElements(".//Location"));
  43. if (loc_iter)
  44. {
  45. IPropertyTree *location = NULL;
  46. loc_iter->first();
  47. while(loc_iter->isValid())
  48. {
  49. location = &loc_iter->query();
  50. if (location)
  51. {
  52. StringBuffer pathstr, rstr, required, description;
  53. location->getProp("@path", pathstr);
  54. location->getProp("@resource", rstr);
  55. location->getProp("@required", required);
  56. location->getProp("@description", description);
  57. if(pathstr.length() == 0)
  58. throw MakeStringException(-1, "path empty in Authenticate/Location");
  59. if(rstr.length() == 0)
  60. throw MakeStringException(-1, "resource empty in Authenticate/Location");
  61. ISecResourceList* rlist = authmap->queryResourceList(pathstr.str());
  62. if(rlist == NULL)
  63. {
  64. rlist = createResourceList("htpasswdsecurity");
  65. authmap->add(pathstr.str(), rlist);
  66. }
  67. ISecResource* rs = rlist->addResource(rstr.str());
  68. unsigned requiredaccess = str2perm(required.str());
  69. rs->setRequiredAccessFlags(requiredaccess);
  70. rs->setDescription(description.str());
  71. rs->setAccessFlags(SecAccess_Full);//grant full access to authenticated users
  72. }
  73. loc_iter->next();
  74. }
  75. }
  76. return authmap;
  77. }
  78. protected:
  79. //ISecManager
  80. bool IsPasswordValid(ISecUser& sec_user)
  81. {
  82. StringBuffer user;
  83. user.append(sec_user.getName());
  84. if (0 == user.length())
  85. throw MakeStringException(-1, "htpasswd User name is NULL");
  86. CriticalBlock block(crit);
  87. if (!apr_initialized)
  88. initAPR();
  89. loadPwds();//reload password file if modified
  90. StringBuffer *encPW = userMap.getValue(user.str());
  91. if (encPW && encPW->length())
  92. {
  93. apr_status_t rc = apr_password_validate(sec_user.credentials().getPassword(), encPW->str());
  94. if (rc != APR_SUCCESS)
  95. DBGLOG("htpasswd authentication for user %s failed - APR RC %d", user.str(), rc );
  96. return rc == APR_SUCCESS;
  97. }
  98. DBGLOG("User %s not in htpasswd file", user.str());
  99. return false;
  100. }
  101. const char * getDescription() override
  102. {
  103. return "HTPASSWD Security Manager";
  104. }
  105. bool authorize(ISecUser & user, ISecResourceList * resources, IEspSecureContext* secureContext) override
  106. {
  107. return IsPasswordValid(user);
  108. }
  109. unsigned getPasswordExpirationWarningDays() override
  110. {
  111. return -2;//never expires
  112. }
  113. int authorizeEx(SecResourceType rtype, ISecUser & user, const char * resourcename, IEspSecureContext* secureContext) override
  114. {
  115. return SecAccess_Full;//grant full access to authenticated users
  116. }
  117. int getAccessFlagsEx(SecResourceType rtype, ISecUser& sec_user, const char* resourcename) override
  118. {
  119. return SecAccess_Full;//grant full access to authenticated users
  120. }
  121. int authorizeFileScope(ISecUser & user, const char * filescope) override
  122. {
  123. return SecAccess_Full;//grant full access to authenticated users
  124. }
  125. bool authorizeViewScope(ISecUser & user, ISecResourceList * resources)
  126. {
  127. int nResources = resources->count();
  128. for (int ri = 0; ri < nResources; ri++)
  129. {
  130. ISecResource* res = resources->queryResource(ri);
  131. if(res != nullptr)
  132. {
  133. assertex(res->getResourceType() == RT_VIEW_SCOPE);
  134. res->setAccessFlags(SecAccess_Full);//grant full access to authenticated users
  135. }
  136. }
  137. return true;//success
  138. }
  139. int authorizeWorkunitScope(ISecUser & user, const char * filescope) override
  140. {
  141. return SecAccess_Full;//grant full access to authenticated users
  142. }
  143. private:
  144. void initAPR()
  145. {
  146. try
  147. {
  148. apr_status_t rc = apr_md5_init(&md5_ctx);
  149. if (rc != APR_SUCCESS)
  150. throw MakeStringException(-1, "htpasswd apr_md5_init returns error %d", rc );
  151. apr_initialized = true;
  152. }
  153. catch (...)
  154. {
  155. throw MakeStringException(-1, "htpasswd exception calling apr_md5_init");
  156. }
  157. }
  158. bool loadPwds()
  159. {
  160. try
  161. {
  162. if (!pwFile.length())
  163. throw MakeStringException(-1, "htpasswd Password file not specified");
  164. Owned<IFile> file = createIFile(pwFile.str());
  165. if (!file->exists())
  166. {
  167. userMap.kill();
  168. throw MakeStringException(-1, "htpasswd Password file does not exist");
  169. }
  170. bool isDir;
  171. offset_t size;
  172. CDateTime whenChanged;
  173. file->getInfo(isDir,size,whenChanged);
  174. if (isDir)
  175. {
  176. userMap.kill();
  177. throw MakeStringException(-1, "htpasswd Password file specifies a directory");
  178. }
  179. if (0 == whenChanged.compare(pwFileLastMod))
  180. return true;//Don't reload if file unchanged
  181. userMap.kill();
  182. OwnedIFileIO io = file->open(IFOread);
  183. if (!io)
  184. throw MakeStringException(-1, "htpasswd Unable to open Password file");
  185. MemoryBuffer mb;
  186. size32_t count = read(io, 0, (size32_t)-1, mb);
  187. if (0 == count)
  188. throw MakeStringException(-1, "htpasswd Password file is empty");
  189. mb.append((char)NULL);
  190. char * p = (char*)mb.toByteArray();
  191. char *saveptr;
  192. const char * seps = "\f\r\n";
  193. char * next = strtok_r(p, seps, &saveptr);
  194. if (next)
  195. {
  196. do
  197. {
  198. char * colon = strchr(next,':');
  199. if (NULL == colon)
  200. throw MakeStringException(-1, "htpasswd Password file appears malformed");
  201. *colon = (char)NULL;
  202. userMap.setValue(next, colon+1);//username, enctypted password
  203. next = strtok_r(NULL, seps, &saveptr);
  204. } while (next);
  205. }
  206. io->close();
  207. pwFileLastMod = whenChanged;//remember when last changed
  208. }
  209. catch(IException*)
  210. {
  211. throw MakeStringException(-1, "htpasswd Exception accessing Password file");
  212. }
  213. return true;
  214. }
  215. private:
  216. mutable CriticalSection crit;
  217. StringBuffer pwFile;
  218. CDateTime pwFileLastMod;
  219. bool apr_initialized;
  220. MapStringTo<StringBuffer> userMap;
  221. apr_md5_ctx_t md5_ctx;
  222. };
  223. extern "C"
  224. {
  225. HTPASSWDSECURITY_API ISecManager * createInstance(const char *serviceName, IPropertyTree &secMgrCfg, IPropertyTree &authCfg)
  226. {
  227. return new CHtpasswdSecurityManager(serviceName, &secMgrCfg, &authCfg);
  228. }
  229. }