htpasswdSecurity.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 *bindConfig) : 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. {
  28. Owned<IPropertyTree> authcfg = bindConfig->getPropTree("Authenticate");
  29. if(authcfg != nullptr)
  30. {
  31. StringBuffer authxml;
  32. toXML(authcfg, authxml);
  33. DBGLOG("HTPASS Authenticate Config: %s", authxml.str());
  34. }
  35. }
  36. {
  37. Owned<IPropertyTree> custombindingconfig = bindConfig->getPropTree("CustomBindingParameters");
  38. if(custombindingconfig != nullptr)
  39. {
  40. StringBuffer custconfigxml;
  41. toXML(custombindingconfig, custconfigxml);
  42. DBGLOG("HTPASS Custom Binding Config: %s", custconfigxml.str());
  43. }
  44. }
  45. apr_initialized = false;
  46. }
  47. ~CHtpasswdSecurityManager()
  48. {
  49. userMap.kill();
  50. }
  51. secManagerType querySecMgrType()
  52. {
  53. return SMT_HTPasswd;
  54. }
  55. inline virtual const char* querySecMgrTypeName() { return "htpasswd"; }
  56. IAuthMap * createAuthMap(IPropertyTree * authconfig)
  57. {
  58. CAuthMap* authmap = new CAuthMap(this);
  59. Owned<IPropertyTreeIterator> loc_iter;
  60. loc_iter.setown(authconfig->getElements(".//Location"));
  61. if (loc_iter)
  62. {
  63. IPropertyTree *location = NULL;
  64. loc_iter->first();
  65. while(loc_iter->isValid())
  66. {
  67. location = &loc_iter->query();
  68. if (location)
  69. {
  70. StringBuffer pathstr, rstr, required, description;
  71. location->getProp("@path", pathstr);
  72. location->getProp("@resource", rstr);
  73. location->getProp("@required", required);
  74. location->getProp("@description", description);
  75. if(pathstr.length() == 0)
  76. throw MakeStringException(-1, "path empty in Authenticate/Location");
  77. if(rstr.length() == 0)
  78. throw MakeStringException(-1, "resource empty in Authenticate/Location");
  79. ISecResourceList* rlist = authmap->queryResourceList(pathstr.str());
  80. if(rlist == NULL)
  81. {
  82. rlist = createResourceList("htpasswdsecurity");
  83. authmap->add(pathstr.str(), rlist);
  84. }
  85. ISecResource* rs = rlist->addResource(rstr.str());
  86. unsigned requiredaccess = str2perm(required.str());
  87. rs->setRequiredAccessFlags(requiredaccess);
  88. rs->setDescription(description.str());
  89. rs->setAccessFlags(SecAccess_Full);//grant full access to authenticated users
  90. }
  91. loc_iter->next();
  92. }
  93. }
  94. return authmap;
  95. }
  96. protected:
  97. //ISecManager
  98. bool IsPasswordValid(ISecUser& sec_user)
  99. {
  100. StringBuffer user;
  101. user.append(sec_user.getName());
  102. if (0 == user.length())
  103. throw MakeStringException(-1, "htpasswd User name is NULL");
  104. CriticalBlock block(crit);
  105. if (!apr_initialized)
  106. initAPR();
  107. loadPwds();//reload password file if modified
  108. StringBuffer *encPW = userMap.getValue(user.str());
  109. if (encPW && encPW->length())
  110. {
  111. apr_status_t rc = apr_password_validate(sec_user.credentials().getPassword(), encPW->str());
  112. if (rc != APR_SUCCESS)
  113. DBGLOG("htpasswd authentication for user %s failed - APR RC %d", user.str(), rc );
  114. return rc == APR_SUCCESS;
  115. }
  116. DBGLOG("User %s not in htpasswd file", user.str());
  117. return false;
  118. }
  119. const char * getDescription() override
  120. {
  121. return "HTPASSWD Security Manager";
  122. }
  123. bool authorize(ISecUser & user, ISecResourceList * resources, IEspSecureContext* secureContext) override
  124. {
  125. return IsPasswordValid(user);
  126. }
  127. unsigned getPasswordExpirationWarningDays() override
  128. {
  129. return -2;//never expires
  130. }
  131. int authorizeEx(SecResourceType rtype, ISecUser & user, const char * resourcename, IEspSecureContext* secureContext) override
  132. {
  133. return SecAccess_Full;//grant full access to authenticated users
  134. }
  135. int getAccessFlagsEx(SecResourceType rtype, ISecUser& sec_user, const char* resourcename) override
  136. {
  137. return SecAccess_Full;//grant full access to authenticated users
  138. }
  139. int authorizeFileScope(ISecUser & user, const char * filescope) override
  140. {
  141. return SecAccess_Full;//grant full access to authenticated users
  142. }
  143. bool authorizeViewScope(ISecUser & user, ISecResourceList * resources)
  144. {
  145. int nResources = resources->count();
  146. for (int ri = 0; ri < nResources; ri++)
  147. {
  148. ISecResource* res = resources->queryResource(ri);
  149. if(res != nullptr)
  150. {
  151. assertex(res->getResourceType() == RT_VIEW_SCOPE);
  152. res->setAccessFlags(SecAccess_Full);//grant full access to authenticated users
  153. }
  154. }
  155. return true;//success
  156. }
  157. int authorizeWorkunitScope(ISecUser & user, const char * filescope) override
  158. {
  159. return SecAccess_Full;//grant full access to authenticated users
  160. }
  161. private:
  162. void initAPR()
  163. {
  164. try
  165. {
  166. apr_status_t rc = apr_md5_init(&md5_ctx);
  167. if (rc != APR_SUCCESS)
  168. throw MakeStringException(-1, "htpasswd apr_md5_init returns error %d", rc );
  169. apr_initialized = true;
  170. }
  171. catch (...)
  172. {
  173. throw MakeStringException(-1, "htpasswd exception calling apr_md5_init");
  174. }
  175. }
  176. bool loadPwds()
  177. {
  178. try
  179. {
  180. if (!pwFile.length())
  181. throw MakeStringException(-1, "htpasswd Password file not specified");
  182. Owned<IFile> file = createIFile(pwFile.str());
  183. if (!file->exists())
  184. {
  185. userMap.kill();
  186. throw MakeStringException(-1, "htpasswd Password file does not exist");
  187. }
  188. bool isDir;
  189. offset_t size;
  190. CDateTime whenChanged;
  191. file->getInfo(isDir,size,whenChanged);
  192. if (isDir)
  193. {
  194. userMap.kill();
  195. throw MakeStringException(-1, "htpasswd Password file specifies a directory");
  196. }
  197. if (0 == whenChanged.compare(pwFileLastMod))
  198. return true;//Don't reload if file unchanged
  199. userMap.kill();
  200. OwnedIFileIO io = file->open(IFOread);
  201. if (!io)
  202. throw MakeStringException(-1, "htpasswd Unable to open Password file");
  203. MemoryBuffer mb;
  204. size32_t count = read(io, 0, (size32_t)-1, mb);
  205. if (0 == count)
  206. throw MakeStringException(-1, "htpasswd Password file is empty");
  207. mb.append((char)NULL);
  208. char * p = (char*)mb.toByteArray();
  209. char *saveptr;
  210. const char * seps = "\f\r\n";
  211. char * next = strtok_r(p, seps, &saveptr);
  212. if (next)
  213. {
  214. do
  215. {
  216. char * colon = strchr(next,':');
  217. if (NULL == colon)
  218. throw MakeStringException(-1, "htpasswd Password file appears malformed");
  219. *colon = (char)NULL;
  220. userMap.setValue(next, colon+1);//username, enctypted password
  221. next = strtok_r(NULL, seps, &saveptr);
  222. } while (next);
  223. }
  224. io->close();
  225. pwFileLastMod = whenChanged;//remember when last changed
  226. }
  227. catch(IException*)
  228. {
  229. throw MakeStringException(-1, "htpasswd Exception accessing Password file");
  230. }
  231. return true;
  232. }
  233. private:
  234. mutable CriticalSection crit;
  235. StringBuffer pwFile;
  236. CDateTime pwFileLastMod;
  237. bool apr_initialized;
  238. MapStringTo<StringBuffer> userMap;
  239. apr_md5_ctx_t md5_ctx;
  240. };
  241. extern "C"
  242. {
  243. HTPASSWDSECURITY_API ISecManager * createInstance(const char *serviceName, IPropertyTree &secMgrCfg, IPropertyTree &bndCfg)
  244. {
  245. return new CHtpasswdSecurityManager(serviceName, &secMgrCfg, &bndCfg);
  246. }
  247. }