utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  5. # Copyright © 2024-2025 Peter Bieringer <pb@bieringer.de>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. import datetime
  20. import os
  21. import ssl
  22. import sys
  23. from importlib import import_module, metadata
  24. from typing import Callable, Sequence, Tuple, Type, TypeVar, Union
  25. from radicale import config
  26. from radicale.log import logger
  27. if sys.platform != "win32":
  28. import grp
  29. import pwd
  30. _T_co = TypeVar("_T_co", covariant=True)
  31. RADICALE_MODULES: Sequence[str] = ("radicale", "vobject", "passlib", "defusedxml",
  32. "bcrypt",
  33. "argon2-cffi",
  34. "pika",
  35. "ldap",
  36. "ldap3",
  37. "pam")
  38. # IPv4 (host, port) and IPv6 (host, port, flowinfo, scopeid)
  39. ADDRESS_TYPE = Union[Tuple[Union[str, bytes, bytearray], int],
  40. Tuple[str, int, int, int]]
  41. # Max YEAR in datetime in unixtime
  42. DATETIME_MAX_UNIXTIME: int = (datetime.MAXYEAR - 1970) * 365 * 24 * 60 * 60
  43. def load_plugin(internal_types: Sequence[str], module_name: str,
  44. class_name: str, base_class: Type[_T_co],
  45. configuration: "config.Configuration") -> _T_co:
  46. type_: Union[str, Callable] = configuration.get(module_name, "type")
  47. if callable(type_):
  48. logger.info("%s type is %r", module_name, type_)
  49. return type_(configuration)
  50. if type_ in internal_types:
  51. module = "radicale.%s.%s" % (module_name, type_)
  52. else:
  53. module = type_
  54. try:
  55. class_ = getattr(import_module(module), class_name)
  56. except Exception as e:
  57. raise RuntimeError("Failed to load %s module %r: %s" %
  58. (module_name, module, e)) from e
  59. logger.info("%s type is %r", module_name, module)
  60. return class_(configuration)
  61. def package_version(name):
  62. return metadata.version(name)
  63. def packages_version():
  64. versions = []
  65. versions.append("python=%s.%s.%s" % (sys.version_info[0], sys.version_info[1], sys.version_info[2]))
  66. for pkg in RADICALE_MODULES:
  67. try:
  68. versions.append("%s=%s" % (pkg, package_version(pkg)))
  69. except Exception:
  70. try:
  71. versions.append("%s=%s" % (pkg, package_version("python-" + pkg)))
  72. except Exception:
  73. versions.append("%s=%s" % (pkg, "n/a"))
  74. return " ".join(versions)
  75. def format_address(address: ADDRESS_TYPE) -> str:
  76. host, port, *_ = address
  77. if not isinstance(host, str):
  78. raise NotImplementedError("Unsupported address format: %r" %
  79. (address,))
  80. if host.find(":") == -1:
  81. return "%s:%d" % (host, port)
  82. else:
  83. return "[%s]:%d" % (host, port)
  84. def ssl_context_options_by_protocol(protocol: str, ssl_context_options):
  85. logger.debug("SSL protocol string: '%s' and current SSL context options: '0x%x'", protocol, ssl_context_options)
  86. # disable any protocol by default
  87. logger.debug("SSL context options, disable ALL by default")
  88. ssl_context_options |= ssl.OP_NO_SSLv2
  89. ssl_context_options |= ssl.OP_NO_SSLv3
  90. ssl_context_options |= ssl.OP_NO_TLSv1
  91. ssl_context_options |= ssl.OP_NO_TLSv1_1
  92. ssl_context_options |= ssl.OP_NO_TLSv1_2
  93. ssl_context_options |= ssl.OP_NO_TLSv1_3
  94. logger.debug("SSL cleared SSL context options: '0x%x'", ssl_context_options)
  95. for entry in protocol.split():
  96. entry = entry.strip('+') # remove trailing '+'
  97. if entry == "ALL":
  98. logger.debug("SSL context options, enable ALL (some maybe not supported by underlying OpenSSL, SSLv2 not enabled at all)")
  99. ssl_context_options &= ~ssl.OP_NO_SSLv3
  100. ssl_context_options &= ~ssl.OP_NO_TLSv1
  101. ssl_context_options &= ~ssl.OP_NO_TLSv1_1
  102. ssl_context_options &= ~ssl.OP_NO_TLSv1_2
  103. ssl_context_options &= ~ssl.OP_NO_TLSv1_3
  104. elif entry == "SSLv2":
  105. logger.warning("SSL context options, ignore SSLv2 (totally insecure)")
  106. elif entry == "SSLv3":
  107. ssl_context_options &= ~ssl.OP_NO_SSLv3
  108. logger.debug("SSL context options, enable SSLv3 (maybe not supported by underlying OpenSSL)")
  109. elif entry == "TLSv1":
  110. ssl_context_options &= ~ssl.OP_NO_TLSv1
  111. logger.debug("SSL context options, enable TLSv1 (maybe not supported by underlying OpenSSL)")
  112. elif entry == "TLSv1.1":
  113. logger.debug("SSL context options, enable TLSv1.1 (maybe not supported by underlying OpenSSL)")
  114. ssl_context_options &= ~ssl.OP_NO_TLSv1_1
  115. elif entry == "TLSv1.2":
  116. logger.debug("SSL context options, enable TLSv1.2")
  117. ssl_context_options &= ~ssl.OP_NO_TLSv1_2
  118. elif entry == "TLSv1.3":
  119. logger.debug("SSL context options, enable TLSv1.3")
  120. ssl_context_options &= ~ssl.OP_NO_TLSv1_3
  121. elif entry == "-ALL":
  122. logger.debug("SSL context options, disable ALL")
  123. ssl_context_options |= ssl.OP_NO_SSLv2
  124. ssl_context_options |= ssl.OP_NO_SSLv3
  125. ssl_context_options |= ssl.OP_NO_TLSv1
  126. ssl_context_options |= ssl.OP_NO_TLSv1_1
  127. ssl_context_options |= ssl.OP_NO_TLSv1_2
  128. ssl_context_options |= ssl.OP_NO_TLSv1_3
  129. elif entry == "-SSLv2":
  130. ssl_context_options |= ssl.OP_NO_SSLv2
  131. logger.debug("SSL context options, disable SSLv2")
  132. elif entry == "-SSLv3":
  133. ssl_context_options |= ssl.OP_NO_SSLv3
  134. logger.debug("SSL context options, disable SSLv3")
  135. elif entry == "-TLSv1":
  136. logger.debug("SSL context options, disable TLSv1")
  137. ssl_context_options |= ssl.OP_NO_TLSv1
  138. elif entry == "-TLSv1.1":
  139. logger.debug("SSL context options, disable TLSv1.1")
  140. ssl_context_options |= ssl.OP_NO_TLSv1_1
  141. elif entry == "-TLSv1.2":
  142. logger.debug("SSL context options, disable TLSv1.2")
  143. ssl_context_options |= ssl.OP_NO_TLSv1_2
  144. elif entry == "-TLSv1.3":
  145. logger.debug("SSL context options, disable TLSv1.3")
  146. ssl_context_options |= ssl.OP_NO_TLSv1_3
  147. else:
  148. raise RuntimeError("SSL protocol config contains unsupported entry '%s'" % (entry))
  149. logger.debug("SSL resulting context options: '0x%x'", ssl_context_options)
  150. return ssl_context_options
  151. def ssl_context_minimum_version_by_options(ssl_context_options):
  152. logger.debug("SSL calculate minimum version by context options: '0x%x'", ssl_context_options)
  153. ssl_context_minimum_version = ssl.TLSVersion.SSLv3 # default
  154. if ((ssl_context_options & ssl.OP_NO_SSLv3) and (ssl_context_minimum_version == ssl.TLSVersion.SSLv3)):
  155. ssl_context_minimum_version = ssl.TLSVersion.TLSv1
  156. if ((ssl_context_options & ssl.OP_NO_TLSv1) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1)):
  157. ssl_context_minimum_version = ssl.TLSVersion.TLSv1_1
  158. if ((ssl_context_options & ssl.OP_NO_TLSv1_1) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1_1)):
  159. ssl_context_minimum_version = ssl.TLSVersion.TLSv1_2
  160. if ((ssl_context_options & ssl.OP_NO_TLSv1_2) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1_2)):
  161. ssl_context_minimum_version = ssl.TLSVersion.TLSv1_3
  162. if ((ssl_context_options & ssl.OP_NO_TLSv1_3) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1_3)):
  163. ssl_context_minimum_version = 0 # all disabled
  164. logger.debug("SSL context options: '0x%x' results in minimum version: %s", ssl_context_options, ssl_context_minimum_version)
  165. return ssl_context_minimum_version
  166. def ssl_context_maximum_version_by_options(ssl_context_options):
  167. logger.debug("SSL calculate maximum version by context options: '0x%x'", ssl_context_options)
  168. ssl_context_maximum_version = ssl.TLSVersion.TLSv1_3 # default
  169. if ((ssl_context_options & ssl.OP_NO_TLSv1_3) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1_3)):
  170. ssl_context_maximum_version = ssl.TLSVersion.TLSv1_2
  171. if ((ssl_context_options & ssl.OP_NO_TLSv1_2) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1_2)):
  172. ssl_context_maximum_version = ssl.TLSVersion.TLSv1_1
  173. if ((ssl_context_options & ssl.OP_NO_TLSv1_1) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1_1)):
  174. ssl_context_maximum_version = ssl.TLSVersion.TLSv1
  175. if ((ssl_context_options & ssl.OP_NO_TLSv1) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1)):
  176. ssl_context_maximum_version = ssl.TLSVersion.SSLv3
  177. if ((ssl_context_options & ssl.OP_NO_SSLv3) and (ssl_context_maximum_version == ssl.TLSVersion.SSLv3)):
  178. ssl_context_maximum_version = 0
  179. logger.debug("SSL context options: '0x%x' results in maximum version: %s", ssl_context_options, ssl_context_maximum_version)
  180. return ssl_context_maximum_version
  181. def ssl_get_protocols(context):
  182. protocols = []
  183. if not (context.options & ssl.OP_NO_SSLv3):
  184. if (context.minimum_version < ssl.TLSVersion.TLSv1):
  185. protocols.append("SSLv3")
  186. if not (context.options & ssl.OP_NO_TLSv1):
  187. if (context.minimum_version < ssl.TLSVersion.TLSv1_1) and (context.maximum_version >= ssl.TLSVersion.TLSv1):
  188. protocols.append("TLSv1")
  189. if not (context.options & ssl.OP_NO_TLSv1_1):
  190. if (context.minimum_version < ssl.TLSVersion.TLSv1_2) and (context.maximum_version >= ssl.TLSVersion.TLSv1_1):
  191. protocols.append("TLSv1.1")
  192. if not (context.options & ssl.OP_NO_TLSv1_2):
  193. if (context.minimum_version <= ssl.TLSVersion.TLSv1_2) and (context.maximum_version >= ssl.TLSVersion.TLSv1_2):
  194. protocols.append("TLSv1.2")
  195. if not (context.options & ssl.OP_NO_TLSv1_3):
  196. if (context.minimum_version <= ssl.TLSVersion.TLSv1_3) and (context.maximum_version >= ssl.TLSVersion.TLSv1_3):
  197. protocols.append("TLSv1.3")
  198. return protocols
  199. def unknown_if_empty(value):
  200. if value == "":
  201. return "UNKNOWN"
  202. else:
  203. return value
  204. def user_groups_as_string():
  205. if sys.platform != "win32":
  206. euid = os.geteuid()
  207. try:
  208. username = pwd.getpwuid(euid)[0]
  209. user = "%s(%d)" % (unknown_if_empty(username), euid)
  210. except Exception:
  211. # name of user not found
  212. user = "UNKNOWN(%d)" % euid
  213. egid = os.getegid()
  214. groups = []
  215. try:
  216. gids = os.getgrouplist(username, egid)
  217. for gid in gids:
  218. try:
  219. gi = grp.getgrgid(gid)
  220. groups.append("%s(%d)" % (unknown_if_empty(gi.gr_name), gid))
  221. except Exception:
  222. groups.append("UNKNOWN(%d)" % gid)
  223. except Exception:
  224. try:
  225. groups.append("%s(%d)" % (grp.getgrnam(egid)[0], egid))
  226. except Exception:
  227. # workaround to get groupid by name
  228. groups_all = grp.getgrall()
  229. found = False
  230. for entry in groups_all:
  231. if entry[2] == egid:
  232. groups.append("%s(%d)" % (unknown_if_empty(entry[0]), egid))
  233. found = True
  234. break
  235. if not found:
  236. groups.append("UNKNOWN(%d)" % egid)
  237. s = "user=%s groups=%s" % (user, ','.join(groups))
  238. else:
  239. username = os.getlogin()
  240. s = "user=%s" % (username)
  241. return s
  242. def format_ut(unixtime: int) -> str:
  243. if sys.platform == "win32":
  244. # TODO check how to support this better
  245. return str(unixtime)
  246. if unixtime < DATETIME_MAX_UNIXTIME:
  247. if sys.version_info < (3, 11):
  248. dt = datetime.datetime.utcfromtimestamp(unixtime)
  249. else:
  250. dt = datetime.datetime.fromtimestamp(unixtime, datetime.UTC)
  251. r = str(unixtime) + "(" + dt.strftime('%Y-%m-%dT%H:%M:%SZ') + ")"
  252. else:
  253. r = str(unixtime) + "(>MAX:" + str(DATETIME_MAX_UNIXTIME) + ")"
  254. return r