htpasswd.py 19 KB

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