ldap.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright 2022 Peter Varkoly
  3. #
  4. # This library is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This library is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  16. """
  17. Authentication backend that checks credentials with a ldap server.
  18. Following parameters are needed in the configuration
  19. ldap_uri The ldap url to the server like ldap://localhost
  20. ldap_base The baseDN of the ldap server
  21. ldap_reader_dn The DN of a ldap user with read access to get the user accounts
  22. ldap_secret The password of the ldap_reader_dn
  23. ldap_filter The search filter to find the user to authenticate by the username
  24. ldap_load_groups If the groups of the authenticated users need to be loaded
  25. """
  26. from radicale import auth, config
  27. from radicale.log import logger
  28. class Auth(auth.BaseAuth):
  29. _ldap_uri: str
  30. _ldap_base: str
  31. _ldap_reader_dn: str
  32. _ldap_secret: str
  33. _ldap_filter: str
  34. _ldap_load_groups: bool
  35. _ldap_version: 3
  36. def __init__(self, configuration: config.Configuration) -> None:
  37. super().__init__(configuration)
  38. try:
  39. import ldap3
  40. except ImportError as e:
  41. try:
  42. import ldap
  43. self._ldap_version = 2
  44. except ImportError as e:
  45. raise RuntimeError("LDAP authentication requires the ldap3 module") from e
  46. self._ldap_uri = configuration.get("auth", "ldap_uri")
  47. self._ldap_base = configuration.get("auth", "ldap_base")
  48. self._ldap_reader_dn = configuration.get("auth", "ldap_reader_dn")
  49. self._ldap_load_groups = configuration.get("auth", "ldap_load_groups")
  50. self._ldap_secret = configuration.get("auth", "ldap_secret")
  51. self._ldap_filter = configuration.get("auth", "ldap_filter")
  52. def _login2(self, login: str, password: str) -> str:
  53. try:
  54. """Bind as reader dn"""
  55. conn = ldap.initialize(self._ldap_uri)
  56. conn.protocol_version = 3
  57. conn.set_option(ldap.OPT_REFERRALS, 0)
  58. conn.simple_bind_s(self._ldap_reader_dn, self._ldap_secret)
  59. """Search for the dn of user to authenticate"""
  60. res = conn.search_s(self._ldap_base, ldap.SCOPE_SUBTREE, filterstr=self._ldap_filter.format(login), attrlist=['memberOf'])
  61. if len(res) == 0:
  62. """User could not be find"""
  63. return ""
  64. user_dn = res[0][0]
  65. logger.debug("LDAP Auth user: %s",user_dn)
  66. """Close ldap connection"""
  67. conn.unbind()
  68. except Exception:
  69. raise RuntimeError("Invalide ldap configuration")
  70. try:
  71. """Bind as user to authenticate"""
  72. conn = ldap.initialize(self._ldap_uri)
  73. conn.protocol_version = 3
  74. conn.set_option(ldap.OPT_REFERRALS, 0)
  75. conn.simple_bind_s(user_dn,password)
  76. tmp = []
  77. if self._ldap_load_groups:
  78. tmp = []
  79. for t in res[0][1]['memberOf']:
  80. tmp.append(t.decode('utf-8').split(',')[0][3:])
  81. self._ldap_groups = set(tmp)
  82. logger.debug("LDAP Auth groups of user: %s",",".join(self._ldap_groups))
  83. conn.unbind()
  84. return login
  85. except ldap.INVALID_CREDENTIALS:
  86. return ""
  87. def _login3(self, login: str, password: str) -> str:
  88. """Connect the server"""
  89. try:
  90. server = ldap3.Server(self._ldap_uri)
  91. conn = ldap3.Connection(server, self._ldap_reader_dn, password=self._ldap_secret)
  92. except self.ldap3.core.exceptions.LDAPSocketOpenError:
  93. raise RuntimeError("Unable to reach ldap server")
  94. except Exception:
  95. pass
  96. if not conn.bind():
  97. raise RuntimeError("Unable to read from ldap server")
  98. """Search the user dn"""
  99. conn.search(
  100. search_base = self._ldap_base,
  101. search_filter = self._ldap_filter.format(login),
  102. search_scope = 'SUBTREE',
  103. attributes = ['memberOf']
  104. )
  105. if len(conn.entries) == 0:
  106. """User could not be find"""
  107. return ""
  108. user_entry = conn.entries[0].entry_to_json()
  109. conn.unbind()
  110. user_dn = user_entry['dn']
  111. try:
  112. """Try to bind as the user itself"""
  113. conn = ldap3.Connection(server, user_dn, password=password)
  114. if not conn.bind():
  115. return ""
  116. if self._ldap_load_groups:
  117. tmp = []
  118. for g in user_entry['attributes']['memberOf']:
  119. tmp.append(g)
  120. self._ldap_groups = set(tmp)
  121. conn.unbind()
  122. return login
  123. except Exception:
  124. pass
  125. return ""
  126. def login(self, login: str, password: str) -> str:
  127. """Validate credentials.
  128. In first step we make a connection to the ldap server with the ldap_reader_dn credential.
  129. In next step the DN of the user to authenticate will be searched.
  130. In the last step the authentication of the user will be proceeded.
  131. """
  132. if self._ldap_version == 2:
  133. return _login2(self, login, password)
  134. return _login3(self, login, password)