htpasswd.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 Guillaume Ayoub
  5. # Copyright © 2017-2019 Unrud <unrud@outlook.com>
  6. # Copyright © 2024 Peter Bieringer <pb@bieringer.de>
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Authentication backend that checks credentials with a htpasswd file.
  22. Apache's htpasswd command (httpd.apache.org/docs/programs/htpasswd.html)
  23. manages a file for storing user credentials. It can encrypt passwords using
  24. different the methods BCRYPT/SHA256/SHA512 or MD5-APR1 (a version of MD5 modified for
  25. Apache). MD5-APR1 provides medium security as of 2015. Only BCRYPT/SHA256/SHA512 can be
  26. considered secure by current standards.
  27. MD5-APR1-encrypted credentials can be written by all versions of htpasswd (it
  28. is the default, in fact), whereas BCRYPT/SHA256/SHA512 requires htpasswd 2.4.x or newer.
  29. The `is_authenticated(user, password)` function provided by this module
  30. verifies the user-given credentials by parsing the htpasswd credential file
  31. pointed to by the ``htpasswd_filename`` configuration value while assuming
  32. the password encryption method specified via the ``htpasswd_encryption``
  33. configuration value.
  34. The following htpasswd password encryption methods are supported by Radicale
  35. out-of-the-box:
  36. - plain-text (created by htpasswd -p ...) -- INSECURE
  37. - MD5-APR1 (htpasswd -m ...) -- htpasswd's default method, INSECURE
  38. - SHA256 (htpasswd -2 ...)
  39. - SHA512 (htpasswd -5 ...)
  40. When bcrypt is installed:
  41. - BCRYPT (htpasswd -B ...) -- Requires htpasswd 2.4.x
  42. """
  43. import functools
  44. import hmac
  45. import os
  46. import threading
  47. import time
  48. from typing import Any, Tuple
  49. from passlib.hash import apr_md5_crypt, sha256_crypt, sha512_crypt
  50. from radicale import auth, config, logger
  51. class Auth(auth.BaseAuth):
  52. _filename: str
  53. _encoding: str
  54. _htpasswd: dict # login -> digest
  55. _htpasswd_mtime_ns: int
  56. _htpasswd_size: int
  57. _htpasswd_ok: bool
  58. _htpasswd_not_ok_time: float
  59. _htpasswd_not_ok_reminder_seconds: int
  60. _htpasswd_bcrypt_use: int
  61. _has_bcrypt: bool
  62. _lock: threading.Lock
  63. def __init__(self, configuration: config.Configuration) -> None:
  64. super().__init__(configuration)
  65. self._filename = configuration.get("auth", "htpasswd_filename")
  66. self._encoding = configuration.get("encoding", "stock")
  67. encryption: str = configuration.get("auth", "htpasswd_encryption")
  68. logger.info("auth htpasswd encryption is 'radicale.auth.htpasswd_encryption.%s'", encryption)
  69. self._has_bcrypt = False
  70. self._htpasswd_ok = False
  71. self._htpasswd_not_ok_reminder_seconds = 60 # currently hardcoded
  72. (self._htpasswd_ok, self._htpasswd_bcrypt_use) = self._read_htpasswd(True)
  73. self._lock = threading.Lock()
  74. if encryption == "plain":
  75. self._verify = self._plain
  76. elif encryption == "md5":
  77. self._verify = self._md5apr1
  78. elif encryption == "sha256":
  79. self._verify = self._sha256
  80. elif encryption == "sha512":
  81. self._verify = self._sha512
  82. elif encryption == "bcrypt" or encryption == "autodetect":
  83. try:
  84. import bcrypt
  85. except ImportError as e:
  86. if (encryption == "autodetect") and (self._htpasswd_bcrypt_use == 0):
  87. logger.warning("auth htpasswd encryption is 'radicale.auth.htpasswd_encryption.%s' which can require bycrypt module, but currently no entries found", encryption)
  88. else:
  89. raise RuntimeError(
  90. "The htpasswd encryption method 'bcrypt' or 'autodetect' requires "
  91. "the bcrypt module (entries found: %d)." % self._htpasswd_bcrypt_use) from e
  92. else:
  93. if encryption == "autodetect":
  94. if self._htpasswd_bcrypt_use == 0:
  95. logger.info("auth htpasswd encryption is 'radicale.auth.htpasswd_encryption.%s' and bycrypt module found, but currently not required", encryption)
  96. else:
  97. logger.info("auth htpasswd encryption is 'radicale.auth.htpasswd_encryption.%s' and bycrypt module found (entries found: %d)", encryption, self._htpasswd_bcrypt_use)
  98. if encryption == "bcrypt":
  99. self._verify = functools.partial(self._bcrypt, bcrypt)
  100. else:
  101. self._verify = self._autodetect
  102. self._verify_bcrypt = functools.partial(self._bcrypt, bcrypt)
  103. self._has_bcrypt = True
  104. else:
  105. raise RuntimeError("The htpasswd encryption method %r is not "
  106. "supported." % encryption)
  107. def _plain(self, hash_value: str, password: str) -> tuple[str, bool]:
  108. """Check if ``hash_value`` and ``password`` match, plain method."""
  109. return ("PLAIN", hmac.compare_digest(hash_value.encode(), password.encode()))
  110. def _bcrypt(self, bcrypt: Any, hash_value: str, password: str) -> tuple[str, bool]:
  111. return ("BCRYPT", bcrypt.checkpw(password=password.encode('utf-8'), hashed_password=hash_value.encode()))
  112. def _md5apr1(self, hash_value: str, password: str) -> tuple[str, bool]:
  113. return ("MD5-APR1", apr_md5_crypt.verify(password, hash_value.strip()))
  114. def _sha256(self, hash_value: str, password: str) -> tuple[str, bool]:
  115. return ("SHA-256", sha256_crypt.verify(password, hash_value.strip()))
  116. def _sha512(self, hash_value: str, password: str) -> tuple[str, bool]:
  117. return ("SHA-512", sha512_crypt.verify(password, hash_value.strip()))
  118. def _autodetect(self, hash_value: str, password: str) -> tuple[str, bool]:
  119. if hash_value.startswith("$apr1$", 0, 6) and len(hash_value) == 37:
  120. # MD5-APR1
  121. return self._md5apr1(hash_value, password)
  122. elif hash_value.startswith("$2y$", 0, 4) and len(hash_value) == 60:
  123. # BCRYPT
  124. return self._verify_bcrypt(hash_value, password)
  125. elif hash_value.startswith("$5$", 0, 3) and len(hash_value) == 63:
  126. # SHA-256
  127. return self._sha256(hash_value, password)
  128. elif hash_value.startswith("$6$", 0, 3) and len(hash_value) == 106:
  129. # SHA-512
  130. return self._sha512(hash_value, password)
  131. else:
  132. # assumed plaintext
  133. return self._plain(hash_value, password)
  134. def _read_htpasswd(self, init: bool) -> Tuple[bool, int]:
  135. """Read htpasswd file
  136. init == True: stop on error
  137. init == False: warn/skip on error and set mark to log reminder every interval
  138. """
  139. htpasswd_ok = True
  140. bcrypt_use = 0
  141. if init is True:
  142. info = "Read"
  143. else:
  144. info = "Re-read"
  145. logger.info("%s content of htpasswd file start: %r", info, self._filename)
  146. htpasswd: dict[str, str]
  147. htpasswd = dict()
  148. try:
  149. with open(self._filename, encoding=self._encoding) as f:
  150. line_num = 0
  151. entries = 0
  152. duplicates = 0
  153. for line in f:
  154. line_num += 1
  155. line = line.rstrip("\n")
  156. if line.lstrip() and not line.lstrip().startswith("#"):
  157. try:
  158. login, digest = line.split(":", maxsplit=1)
  159. skip = False
  160. if login == "" or digest == "":
  161. if init is True:
  162. raise ValueError("htpasswd file contains problematic line not matching <login>:<digest> in line: %d" % line_num)
  163. else:
  164. logger.warning("htpasswd file contains problematic line not matching <login>:<digest> in line: %d (ignored)", line_num)
  165. htpasswd_ok = False
  166. skip = True
  167. else:
  168. if htpasswd.get(login):
  169. duplicates += 1
  170. if init is True:
  171. raise ValueError("htpasswd file contains duplicate login: '%s'", login, line_num)
  172. else:
  173. logger.warning("htpasswd file contains duplicate login: '%s' (line: %d / ignored)", login, line_num)
  174. htpasswd_ok = False
  175. skip = True
  176. else:
  177. if digest.startswith("$2y$", 0, 4) and len(digest) == 60:
  178. if init is True:
  179. bcrypt_use += 1
  180. else:
  181. if self._has_bcrypt is False:
  182. logger.warning("htpasswd file contains bcrypt digest login: '%s' (line: %d / ignored because module is not loaded)", login, line_num)
  183. skip = True
  184. htpasswd_ok = False
  185. if skip is False:
  186. htpasswd[login] = digest
  187. entries += 1
  188. except ValueError as e:
  189. if init is True:
  190. raise RuntimeError("Invalid htpasswd file %r: %s" % (self._filename, e)) from e
  191. except OSError as e:
  192. if init is True:
  193. raise RuntimeError("Failed to load htpasswd file %r: %s" % (self._filename, e)) from e
  194. else:
  195. logger.warning("Failed to load htpasswd file on re-read: %r" % self._filename)
  196. htpasswd_ok = False
  197. else:
  198. self._htpasswd_size = os.stat(self._filename).st_size
  199. self._htpasswd_time_ns = os.stat(self._filename).st_mtime_ns
  200. self._htpasswd = htpasswd
  201. logger.info("%s content of htpasswd file done: %r (entries: %d, duplicates: %d)", info, self._filename, entries, duplicates)
  202. if htpasswd_ok is True:
  203. self._htpasswd_not_ok_time = 0
  204. else:
  205. self._htpasswd_not_ok_time = time.time()
  206. return (htpasswd_ok, bcrypt_use)
  207. def _login(self, login: str, password: str) -> str:
  208. """Validate credentials.
  209. Iterate through htpasswd credential file until login matches, extract
  210. hash (encrypted password) and check hash against password,
  211. using the method specified in the Radicale config.
  212. The content of the file is cached and live updates will be detected by
  213. comparing mtime_ns and size
  214. """
  215. # check and re-read file if required
  216. htpasswd_size = os.stat(self._filename).st_size
  217. htpasswd_time_ns = os.stat(self._filename).st_mtime_ns
  218. if (htpasswd_size != self._htpasswd_size) or (htpasswd_time_ns != self._htpasswd_time_ns):
  219. with self._lock:
  220. (self._htpasswd_ok, self._htpasswd_bcrypt_use) = self._read_htpasswd(False)
  221. else:
  222. # log reminder of problemantic file every interval
  223. if (self._htpasswd_ok is False) and (self._htpasswd_not_ok_time > 0):
  224. current_time = time.time()
  225. if (current_time - self._htpasswd_not_ok_time) > self._htpasswd_not_ok_reminder_seconds:
  226. logger.warning("htpasswd file still contains issues (REMINDER, check warnings in the past): %r" % self._filename)
  227. self._htpasswd_not_ok_time = current_time
  228. if self._htpasswd.get(login):
  229. digest = self._htpasswd[login]
  230. (method, password_ok) = self._verify(digest, password)
  231. logger.debug("Login verification successful for user: '%s' (method '%s')", login, method)
  232. if password_ok:
  233. return login
  234. else:
  235. logger.debug("Login verification failed for user: '%s' ( method '%s')", login, method)
  236. else:
  237. logger.debug("Login verification user not found: '%s'", login)
  238. return ""