1
0

utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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/Min YEAR in datetime in unixtime
  42. DATETIME_MAX_UNIXTIME: int = (datetime.MAXYEAR - 1970) * 365 * 24 * 60 * 60
  43. DATETIME_MIN_UNIXTIME: int = (datetime.MINYEAR - 1970) * 365 * 24 * 60 * 60
  44. def load_plugin(internal_types: Sequence[str], module_name: str,
  45. class_name: str, base_class: Type[_T_co],
  46. configuration: "config.Configuration") -> _T_co:
  47. type_: Union[str, Callable] = configuration.get(module_name, "type")
  48. if callable(type_):
  49. logger.info("%s type is %r", module_name, type_)
  50. return type_(configuration)
  51. if type_ in internal_types:
  52. module = "radicale.%s.%s" % (module_name, type_)
  53. else:
  54. module = type_
  55. try:
  56. class_ = getattr(import_module(module), class_name)
  57. except Exception as e:
  58. raise RuntimeError("Failed to load %s module %r: %s" %
  59. (module_name, module, e)) from e
  60. logger.info("%s type is %r", module_name, module)
  61. return class_(configuration)
  62. def package_version(name):
  63. return metadata.version(name)
  64. def packages_version():
  65. versions = []
  66. versions.append("python=%s.%s.%s" % (sys.version_info[0], sys.version_info[1], sys.version_info[2]))
  67. for pkg in RADICALE_MODULES:
  68. try:
  69. versions.append("%s=%s" % (pkg, package_version(pkg)))
  70. except Exception:
  71. try:
  72. versions.append("%s=%s" % (pkg, package_version("python-" + pkg)))
  73. except Exception:
  74. versions.append("%s=%s" % (pkg, "n/a"))
  75. return " ".join(versions)
  76. def format_address(address: ADDRESS_TYPE) -> str:
  77. host, port, *_ = address
  78. if not isinstance(host, str):
  79. raise NotImplementedError("Unsupported address format: %r" %
  80. (address,))
  81. if host.find(":") == -1:
  82. return "%s:%d" % (host, port)
  83. else:
  84. return "[%s]:%d" % (host, port)
  85. def ssl_context_options_by_protocol(protocol: str, ssl_context_options):
  86. logger.debug("SSL protocol string: '%s' and current SSL context options: '0x%x'", protocol, ssl_context_options)
  87. # disable any protocol by default
  88. logger.debug("SSL context options, disable ALL by default")
  89. ssl_context_options |= ssl.OP_NO_SSLv2
  90. ssl_context_options |= ssl.OP_NO_SSLv3
  91. ssl_context_options |= ssl.OP_NO_TLSv1
  92. ssl_context_options |= ssl.OP_NO_TLSv1_1
  93. ssl_context_options |= ssl.OP_NO_TLSv1_2
  94. ssl_context_options |= ssl.OP_NO_TLSv1_3
  95. logger.debug("SSL cleared SSL context options: '0x%x'", ssl_context_options)
  96. for entry in protocol.split():
  97. entry = entry.strip('+') # remove trailing '+'
  98. if entry == "ALL":
  99. logger.debug("SSL context options, enable ALL (some maybe not supported by underlying OpenSSL, SSLv2 not enabled at all)")
  100. ssl_context_options &= ~ssl.OP_NO_SSLv3
  101. ssl_context_options &= ~ssl.OP_NO_TLSv1
  102. ssl_context_options &= ~ssl.OP_NO_TLSv1_1
  103. ssl_context_options &= ~ssl.OP_NO_TLSv1_2
  104. ssl_context_options &= ~ssl.OP_NO_TLSv1_3
  105. elif entry == "SSLv2":
  106. logger.warning("SSL context options, ignore SSLv2 (totally insecure)")
  107. elif entry == "SSLv3":
  108. ssl_context_options &= ~ssl.OP_NO_SSLv3
  109. logger.debug("SSL context options, enable SSLv3 (maybe not supported by underlying OpenSSL)")
  110. elif entry == "TLSv1":
  111. ssl_context_options &= ~ssl.OP_NO_TLSv1
  112. logger.debug("SSL context options, enable TLSv1 (maybe not supported by underlying OpenSSL)")
  113. elif entry == "TLSv1.1":
  114. logger.debug("SSL context options, enable TLSv1.1 (maybe not supported by underlying OpenSSL)")
  115. ssl_context_options &= ~ssl.OP_NO_TLSv1_1
  116. elif entry == "TLSv1.2":
  117. logger.debug("SSL context options, enable TLSv1.2")
  118. ssl_context_options &= ~ssl.OP_NO_TLSv1_2
  119. elif entry == "TLSv1.3":
  120. logger.debug("SSL context options, enable TLSv1.3")
  121. ssl_context_options &= ~ssl.OP_NO_TLSv1_3
  122. elif entry == "-ALL":
  123. logger.debug("SSL context options, disable ALL")
  124. ssl_context_options |= ssl.OP_NO_SSLv2
  125. ssl_context_options |= ssl.OP_NO_SSLv3
  126. ssl_context_options |= ssl.OP_NO_TLSv1
  127. ssl_context_options |= ssl.OP_NO_TLSv1_1
  128. ssl_context_options |= ssl.OP_NO_TLSv1_2
  129. ssl_context_options |= ssl.OP_NO_TLSv1_3
  130. elif entry == "-SSLv2":
  131. ssl_context_options |= ssl.OP_NO_SSLv2
  132. logger.debug("SSL context options, disable SSLv2")
  133. elif entry == "-SSLv3":
  134. ssl_context_options |= ssl.OP_NO_SSLv3
  135. logger.debug("SSL context options, disable SSLv3")
  136. elif entry == "-TLSv1":
  137. logger.debug("SSL context options, disable TLSv1")
  138. ssl_context_options |= ssl.OP_NO_TLSv1
  139. elif entry == "-TLSv1.1":
  140. logger.debug("SSL context options, disable TLSv1.1")
  141. ssl_context_options |= ssl.OP_NO_TLSv1_1
  142. elif entry == "-TLSv1.2":
  143. logger.debug("SSL context options, disable TLSv1.2")
  144. ssl_context_options |= ssl.OP_NO_TLSv1_2
  145. elif entry == "-TLSv1.3":
  146. logger.debug("SSL context options, disable TLSv1.3")
  147. ssl_context_options |= ssl.OP_NO_TLSv1_3
  148. else:
  149. raise RuntimeError("SSL protocol config contains unsupported entry '%s'" % (entry))
  150. logger.debug("SSL resulting context options: '0x%x'", ssl_context_options)
  151. return ssl_context_options
  152. def ssl_context_minimum_version_by_options(ssl_context_options):
  153. logger.debug("SSL calculate minimum version by context options: '0x%x'", ssl_context_options)
  154. ssl_context_minimum_version = ssl.TLSVersion.SSLv3 # default
  155. if ((ssl_context_options & ssl.OP_NO_SSLv3) and (ssl_context_minimum_version == ssl.TLSVersion.SSLv3)):
  156. ssl_context_minimum_version = ssl.TLSVersion.TLSv1
  157. if ((ssl_context_options & ssl.OP_NO_TLSv1) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1)):
  158. ssl_context_minimum_version = ssl.TLSVersion.TLSv1_1
  159. if ((ssl_context_options & ssl.OP_NO_TLSv1_1) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1_1)):
  160. ssl_context_minimum_version = ssl.TLSVersion.TLSv1_2
  161. if ((ssl_context_options & ssl.OP_NO_TLSv1_2) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1_2)):
  162. ssl_context_minimum_version = ssl.TLSVersion.TLSv1_3
  163. if ((ssl_context_options & ssl.OP_NO_TLSv1_3) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1_3)):
  164. ssl_context_minimum_version = 0 # all disabled
  165. logger.debug("SSL context options: '0x%x' results in minimum version: %s", ssl_context_options, ssl_context_minimum_version)
  166. return ssl_context_minimum_version
  167. def ssl_context_maximum_version_by_options(ssl_context_options):
  168. logger.debug("SSL calculate maximum version by context options: '0x%x'", ssl_context_options)
  169. ssl_context_maximum_version = ssl.TLSVersion.TLSv1_3 # default
  170. if ((ssl_context_options & ssl.OP_NO_TLSv1_3) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1_3)):
  171. ssl_context_maximum_version = ssl.TLSVersion.TLSv1_2
  172. if ((ssl_context_options & ssl.OP_NO_TLSv1_2) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1_2)):
  173. ssl_context_maximum_version = ssl.TLSVersion.TLSv1_1
  174. if ((ssl_context_options & ssl.OP_NO_TLSv1_1) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1_1)):
  175. ssl_context_maximum_version = ssl.TLSVersion.TLSv1
  176. if ((ssl_context_options & ssl.OP_NO_TLSv1) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1)):
  177. ssl_context_maximum_version = ssl.TLSVersion.SSLv3
  178. if ((ssl_context_options & ssl.OP_NO_SSLv3) and (ssl_context_maximum_version == ssl.TLSVersion.SSLv3)):
  179. ssl_context_maximum_version = 0
  180. logger.debug("SSL context options: '0x%x' results in maximum version: %s", ssl_context_options, ssl_context_maximum_version)
  181. return ssl_context_maximum_version
  182. def ssl_get_protocols(context):
  183. protocols = []
  184. if not (context.options & ssl.OP_NO_SSLv3):
  185. if (context.minimum_version < ssl.TLSVersion.TLSv1):
  186. protocols.append("SSLv3")
  187. if not (context.options & ssl.OP_NO_TLSv1):
  188. if (context.minimum_version < ssl.TLSVersion.TLSv1_1) and (context.maximum_version >= ssl.TLSVersion.TLSv1):
  189. protocols.append("TLSv1")
  190. if not (context.options & ssl.OP_NO_TLSv1_1):
  191. if (context.minimum_version < ssl.TLSVersion.TLSv1_2) and (context.maximum_version >= ssl.TLSVersion.TLSv1_1):
  192. protocols.append("TLSv1.1")
  193. if not (context.options & ssl.OP_NO_TLSv1_2):
  194. if (context.minimum_version <= ssl.TLSVersion.TLSv1_2) and (context.maximum_version >= ssl.TLSVersion.TLSv1_2):
  195. protocols.append("TLSv1.2")
  196. if not (context.options & ssl.OP_NO_TLSv1_3):
  197. if (context.minimum_version <= ssl.TLSVersion.TLSv1_3) and (context.maximum_version >= ssl.TLSVersion.TLSv1_3):
  198. protocols.append("TLSv1.3")
  199. return protocols
  200. def unknown_if_empty(value):
  201. if value == "":
  202. return "UNKNOWN"
  203. else:
  204. return value
  205. def user_groups_as_string():
  206. if sys.platform != "win32":
  207. euid = os.geteuid()
  208. try:
  209. username = pwd.getpwuid(euid)[0]
  210. user = "%s(%d)" % (unknown_if_empty(username), euid)
  211. except Exception:
  212. # name of user not found
  213. user = "UNKNOWN(%d)" % euid
  214. egid = os.getegid()
  215. groups = []
  216. try:
  217. gids = os.getgrouplist(username, egid)
  218. for gid in gids:
  219. try:
  220. gi = grp.getgrgid(gid)
  221. groups.append("%s(%d)" % (unknown_if_empty(gi.gr_name), gid))
  222. except Exception:
  223. groups.append("UNKNOWN(%d)" % gid)
  224. except Exception:
  225. try:
  226. groups.append("%s(%d)" % (grp.getgrnam(egid)[0], egid))
  227. except Exception:
  228. # workaround to get groupid by name
  229. groups_all = grp.getgrall()
  230. found = False
  231. for entry in groups_all:
  232. if entry[2] == egid:
  233. groups.append("%s(%d)" % (unknown_if_empty(entry[0]), egid))
  234. found = True
  235. break
  236. if not found:
  237. groups.append("UNKNOWN(%d)" % egid)
  238. s = "user=%s groups=%s" % (user, ','.join(groups))
  239. else:
  240. username = os.getlogin()
  241. s = "user=%s" % (username)
  242. return s
  243. def format_ut(unixtime: int) -> str:
  244. if sys.platform == "win32":
  245. # TODO check how to support this better
  246. return str(unixtime)
  247. if unixtime <= DATETIME_MIN_UNIXTIME:
  248. r = str(unixtime) + "(<=MIN:" + str(DATETIME_MIN_UNIXTIME) + ")"
  249. elif unixtime >= DATETIME_MAX_UNIXTIME:
  250. r = str(unixtime) + "(>=MAX:" + str(DATETIME_MAX_UNIXTIME) + ")"
  251. else:
  252. if sys.version_info < (3, 11):
  253. dt = datetime.datetime.utcfromtimestamp(unixtime)
  254. else:
  255. dt = datetime.datetime.fromtimestamp(unixtime, datetime.UTC)
  256. r = str(unixtime) + "(" + dt.strftime('%Y-%m-%dT%H:%M:%SZ') + ")"
  257. return r