htpasswd.py 16 KB

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