htpasswd.py 14 KB

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