htpasswd.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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-2025 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. _htpasswd_cache: bool
  62. _has_bcrypt: bool
  63. _lock: threading.Lock
  64. def __init__(self, configuration: config.Configuration) -> None:
  65. super().__init__(configuration)
  66. self._filename = configuration.get("auth", "htpasswd_filename")
  67. logger.info("auth htpasswd file: %r", self._filename)
  68. self._encoding = configuration.get("encoding", "stock")
  69. logger.info("auth htpasswd file encoding: %r", self._encoding)
  70. self._htpasswd_cache = configuration.get("auth", "htpasswd_cache")
  71. logger.info("auth htpasswd cache: %s", self._htpasswd_cache)
  72. encryption: str = configuration.get("auth", "htpasswd_encryption")
  73. logger.info("auth htpasswd encryption is 'radicale.auth.htpasswd_encryption.%s'", encryption)
  74. self._has_bcrypt = False
  75. self._htpasswd_ok = False
  76. self._htpasswd_not_ok_reminder_seconds = 60 # currently hardcoded
  77. (self._htpasswd_ok, self._htpasswd_bcrypt_use, self._htpasswd, self._htpasswd_size, self._htpasswd_mtime_ns) = self._read_htpasswd(True, False)
  78. self._lock = threading.Lock()
  79. if encryption == "plain":
  80. self._verify = self._plain
  81. elif encryption == "md5":
  82. self._verify = self._md5apr1
  83. elif encryption == "sha256":
  84. self._verify = self._sha256
  85. elif encryption == "sha512":
  86. self._verify = self._sha512
  87. elif encryption == "bcrypt" or encryption == "autodetect":
  88. try:
  89. import bcrypt
  90. except ImportError as e:
  91. if (encryption == "autodetect") and (self._htpasswd_bcrypt_use == 0):
  92. logger.warning("auth htpasswd encryption is 'radicale.auth.htpasswd_encryption.%s' which can require bycrypt module, but currently no entries found", encryption)
  93. else:
  94. raise RuntimeError(
  95. "The htpasswd encryption method 'bcrypt' or 'autodetect' requires "
  96. "the bcrypt module (entries found: %d)." % self._htpasswd_bcrypt_use) from e
  97. else:
  98. if encryption == "autodetect":
  99. if self._htpasswd_bcrypt_use == 0:
  100. logger.info("auth htpasswd encryption is 'radicale.auth.htpasswd_encryption.%s' and bycrypt module found, but currently not required", encryption)
  101. else:
  102. logger.info("auth htpasswd encryption is 'radicale.auth.htpasswd_encryption.%s' and bycrypt module found (bcrypt entries found: %d)", encryption, self._htpasswd_bcrypt_use)
  103. if encryption == "bcrypt":
  104. self._verify = functools.partial(self._bcrypt, bcrypt)
  105. else:
  106. self._verify = self._autodetect
  107. self._verify_bcrypt = functools.partial(self._bcrypt, bcrypt)
  108. self._has_bcrypt = True
  109. else:
  110. raise RuntimeError("The htpasswd encryption method %r is not "
  111. "supported." % encryption)
  112. def _plain(self, hash_value: str, password: str) -> tuple[str, bool]:
  113. """Check if ``hash_value`` and ``password`` match, plain method."""
  114. return ("PLAIN", hmac.compare_digest(hash_value.encode(), password.encode()))
  115. def _bcrypt(self, bcrypt: Any, hash_value: str, password: str) -> tuple[str, bool]:
  116. return ("BCRYPT", bcrypt.checkpw(password=password.encode('utf-8'), hashed_password=hash_value.encode()))
  117. def _md5apr1(self, hash_value: str, password: str) -> tuple[str, bool]:
  118. return ("MD5-APR1", apr_md5_crypt.verify(password, hash_value.strip()))
  119. def _sha256(self, hash_value: str, password: str) -> tuple[str, bool]:
  120. return ("SHA-256", sha256_crypt.verify(password, hash_value.strip()))
  121. def _sha512(self, hash_value: str, password: str) -> tuple[str, bool]:
  122. return ("SHA-512", sha512_crypt.verify(password, hash_value.strip()))
  123. def _autodetect(self, hash_value: str, password: str) -> tuple[str, bool]:
  124. if hash_value.startswith("$apr1$", 0, 6) and len(hash_value) == 37:
  125. # MD5-APR1
  126. return self._md5apr1(hash_value, password)
  127. elif hash_value.startswith("$2y$", 0, 4) and len(hash_value) == 60:
  128. # BCRYPT
  129. return self._verify_bcrypt(hash_value, password)
  130. elif hash_value.startswith("$5$", 0, 3) and len(hash_value) == 63:
  131. # SHA-256
  132. return self._sha256(hash_value, password)
  133. elif hash_value.startswith("$6$", 0, 3) and len(hash_value) == 106:
  134. # SHA-512
  135. return self._sha512(hash_value, password)
  136. else:
  137. # assumed plaintext
  138. return self._plain(hash_value, password)
  139. def _read_htpasswd(self, init: bool, suppress: bool) -> Tuple[bool, int, dict, int, int]:
  140. """Read htpasswd file
  141. init == True: stop on error
  142. init == False: warn/skip on error and set mark to log reminder every interval
  143. suppress == True: suppress warnings, change info to debug (used in non-caching mode)
  144. suppress == False: do not suppress warnings (used in caching mode)
  145. """
  146. htpasswd_ok = True
  147. bcrypt_use = 0
  148. if (init is True) or (suppress is True):
  149. info = "Read"
  150. else:
  151. info = "Re-read"
  152. if suppress is False:
  153. logger.info("%s content of htpasswd file start: %r", info, self._filename)
  154. else:
  155. logger.debug("%s content of htpasswd file start: %r", info, self._filename)
  156. htpasswd: dict[str, str] = dict()
  157. entries = 0
  158. duplicates = 0
  159. errors = 0
  160. try:
  161. with open(self._filename, encoding=self._encoding) as f:
  162. line_num = 0
  163. for line in f:
  164. line_num += 1
  165. line = line.rstrip("\n")
  166. if line.lstrip() and not line.lstrip().startswith("#"):
  167. try:
  168. login, digest = line.split(":", maxsplit=1)
  169. skip = False
  170. if login == "" or digest == "":
  171. if init is True:
  172. raise ValueError("htpasswd file contains problematic line not matching <login>:<digest> in line: %d" % line_num)
  173. else:
  174. errors += 1
  175. logger.warning("htpasswd file contains problematic line not matching <login>:<digest> in line: %d (ignored)", line_num)
  176. htpasswd_ok = False
  177. skip = True
  178. else:
  179. if htpasswd.get(login):
  180. duplicates += 1
  181. if init is True:
  182. raise ValueError("htpasswd file contains duplicate login: '%s'", login, line_num)
  183. else:
  184. logger.warning("htpasswd file contains duplicate login: '%s' (line: %d / ignored)", login, line_num)
  185. htpasswd_ok = False
  186. skip = True
  187. else:
  188. if digest.startswith("$2y$", 0, 4) and len(digest) == 60:
  189. if init is True:
  190. bcrypt_use += 1
  191. else:
  192. if self._has_bcrypt is False:
  193. logger.warning("htpasswd file contains bcrypt digest login: '%s' (line: %d / ignored because module is not loaded)", login, line_num)
  194. skip = True
  195. htpasswd_ok = False
  196. if skip is False:
  197. htpasswd[login] = digest
  198. entries += 1
  199. except ValueError as e:
  200. if init is True:
  201. raise RuntimeError("Invalid htpasswd file %r: %s" % (self._filename, e)) from e
  202. except OSError as e:
  203. if init is True:
  204. raise RuntimeError("Failed to load htpasswd file %r: %s" % (self._filename, e)) from e
  205. else:
  206. logger.warning("Failed to load htpasswd file on re-read: %r" % self._filename)
  207. htpasswd_ok = False
  208. htpasswd_size = os.stat(self._filename).st_size
  209. htpasswd_mtime_ns = os.stat(self._filename).st_mtime_ns
  210. if suppress is False:
  211. logger.info("%s content of htpasswd file done: %r (entries: %d, duplicates: %d, errors: %d)", info, self._filename, entries, duplicates, errors)
  212. else:
  213. logger.debug("%s content of htpasswd file done: %r (entries: %d, duplicates: %d, errors: %d)", info, self._filename, entries, duplicates, errors)
  214. if htpasswd_ok is True:
  215. self._htpasswd_not_ok_time = 0
  216. else:
  217. self._htpasswd_not_ok_time = time.time()
  218. return (htpasswd_ok, bcrypt_use, htpasswd, htpasswd_size, htpasswd_mtime_ns)
  219. def _login(self, login: str, password: str) -> str:
  220. """Validate credentials.
  221. Iterate through htpasswd credential file until login matches, extract
  222. hash (encrypted password) and check hash against password,
  223. using the method specified in the Radicale config.
  224. Optional: the content of the file is cached and live updates will be detected by
  225. comparing mtime_ns and size
  226. """
  227. login_ok = False
  228. digest: str
  229. if self._htpasswd_cache is True:
  230. # check and re-read file if required
  231. with self._lock:
  232. htpasswd_size = os.stat(self._filename).st_size
  233. htpasswd_mtime_ns = os.stat(self._filename).st_mtime_ns
  234. if (htpasswd_size != self._htpasswd_size) or (htpasswd_mtime_ns != self._htpasswd_mtime_ns):
  235. (self._htpasswd_ok, self._htpasswd_bcrypt_use, self._htpasswd, self._htpasswd_size, self._htpasswd_mtime_ns) = self._read_htpasswd(False, False)
  236. self._htpasswd_not_ok_time = 0
  237. # log reminder of problemantic file every interval
  238. current_time = time.time()
  239. if (self._htpasswd_ok is False):
  240. if (self._htpasswd_not_ok_time > 0):
  241. if (current_time - self._htpasswd_not_ok_time) > self._htpasswd_not_ok_reminder_seconds:
  242. logger.warning("htpasswd file still contains issues (REMINDER, check warnings in the past): %r" % self._filename)
  243. self._htpasswd_not_ok_time = current_time
  244. else:
  245. self._htpasswd_not_ok_time = current_time
  246. if self._htpasswd.get(login):
  247. digest = self._htpasswd[login]
  248. login_ok = True
  249. else:
  250. # read file on every request
  251. (htpasswd_ok, htpasswd_bcrypt_use, htpasswd, htpasswd_size, htpasswd_mtime_ns) = self._read_htpasswd(False, True)
  252. if htpasswd.get(login):
  253. digest = htpasswd[login]
  254. login_ok = True
  255. if login_ok is True:
  256. (method, password_ok) = self._verify(digest, password)
  257. logger.debug("Login verification successful for user: '%s' (method '%s')", login, method)
  258. if password_ok:
  259. return login
  260. else:
  261. logger.debug("Login verification failed for user: '%s' ( method '%s')", login, method)
  262. else:
  263. logger.debug("Login verification user not found: '%s'", login)
  264. return ""