| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
import ldap |
| 5 |
import logging |
| 6 |
from ldap.filter import filter_format |
| 7 |
|
| 8 |
from odoo import _, fields, models, tools |
| 9 |
from odoo.exceptions import AccessDenied |
| 10 |
from odoo.tools.misc import str2bool |
| 11 |
|
| 12 |
_logger = logging.getLogger(__name__) |
| 13 |
|
| 14 |
|
| 15 |
class LDAPWrapper: |
| 16 |
def __init__(self, obj): |
| 17 |
self.__obj__ = obj |
| 18 |
|
| 19 |
def passwd_s(self, *args, **kwargs): |
| 20 |
self.__obj__.passwd_s(*args, **kwargs) |
| 21 |
|
| 22 |
def search_st(self, *args, **kwargs): |
| 23 |
return self.__obj__.search_st(*args, **kwargs) |
| 24 |
|
| 25 |
def simple_bind_s(self, *args, **kwargs): |
| 26 |
self.__obj__.simple_bind_s(*args, **kwargs) |
| 27 |
|
| 28 |
def unbind(self, *args, **kwargs): |
| 29 |
self.__obj__.unbind(*args, **kwargs) |
| 30 |
|
| 31 |
|
| 32 |
class ResCompanyLdap(models.Model): |
| 33 |
_name = 'res.company.ldap' |
| 34 |
_description = 'Company LDAP configuration' |
| 35 |
_order = 'sequence' |
| 36 |
_rec_name = 'ldap_server' |
| 37 |
|
| 38 |
sequence = fields.Integer(default=10) |
| 39 |
company = fields.Many2one('res.company', string='Company', required=True, ondelete='cascade') |
| 40 |
ldap_server = fields.Char(string='LDAP Server address', required=True, default='127.0.0.1') |
| 41 |
ldap_server_port = fields.Integer(string='LDAP Server port', required=True, default=389) |
| 42 |
ldap_binddn = fields.Char('LDAP binddn', |
| 43 |
help="The user account on the LDAP server that is used to query the directory. " |
| 44 |
"Leave empty to connect anonymously.") |
| 45 |
ldap_password = fields.Char(string='LDAP password', |
| 46 |
help="The password of the user account on the LDAP server that is used to query the directory.") |
| 47 |
ldap_filter = fields.Char(string='LDAP filter', required=True, help="""\ |
| 48 |
Filter used to look up user accounts in the LDAP database. It is an\ |
| 49 |
arbitrary LDAP filter in string representation. Any `%s` placeholder\ |
| 50 |
will be replaced by the login (identifier) provided by the user, the filter\ |
| 51 |
should contain at least one such placeholder. |
| 52 |
|
| 53 |
The filter must result in exactly one (1) result, otherwise the login will\ |
| 54 |
be considered invalid. |
| 55 |
|
| 56 |
Example (actual attributes depend on LDAP server and setup): |
| 57 |
|
| 58 |
(&(objectCategory=person)(objectClass=user)(sAMAccountName=%s)) |
| 59 |
|
| 60 |
or |
| 61 |
|
| 62 |
(|(mail=%s)(uid=%s)) |
| 63 |
""") |
| 64 |
ldap_base = fields.Char(string='LDAP base', required=True, help="DN of the user search scope: all descendants of this base will be searched for users.") |
| 65 |
user = fields.Many2one('res.users', string='Template User', |
| 66 |
help="User to copy when creating new users") |
| 67 |
create_user = fields.Boolean(default=True, |
| 68 |
help="Automatically create local user accounts for new users authenticating via LDAP") |
| 69 |
ldap_tls = fields.Boolean(string='Use TLS', |
| 70 |
help="Request secure TLS/SSL encryption when connecting to the LDAP server. " |
| 71 |
"This option requires a server with STARTTLS enabled, " |
| 72 |
"otherwise all authentication attempts will fail.") |
| 73 |
|
| 74 |
def _get_ldap_dicts(self): |
| 75 |
""" |
| 76 |
Retrieve res_company_ldap resources from the database in dictionary |
| 77 |
format. |
| 78 |
:return: ldap configurations |
| 79 |
:rtype: list of dictionaries |
| 80 |
""" |
| 81 |
|
| 82 |
res = self.sudo().search_read([('ldap_server', '!=', False)], [ |
| 83 |
'id', |
| 84 |
'company', |
| 85 |
'ldap_server', |
| 86 |
'ldap_server_port', |
| 87 |
'ldap_binddn', |
| 88 |
'ldap_password', |
| 89 |
'ldap_filter', |
| 90 |
'ldap_base', |
| 91 |
'user', |
| 92 |
'create_user', |
| 93 |
'ldap_tls' |
| 94 |
], order='sequence') |
| 95 |
return res |
| 96 |
|
| 97 |
def _connect(self, conf): |
| 98 |
""" |
| 99 |
Connect to an LDAP server specified by an ldap |
| 100 |
configuration dictionary. |
| 101 |
|
| 102 |
:param dict conf: LDAP configuration |
| 103 |
:return: an LDAP object |
| 104 |
""" |
| 105 |
|
| 106 |
uri = 'ldap://%s:%d' % (conf['ldap_server'], conf['ldap_server_port']) |
| 107 |
|
| 108 |
connection = ldap.initialize(uri) |
| 109 |
ldap_chase_ref_disabled = self.env['ir.config_parameter'].sudo().get_param('auth_ldap.disable_chase_ref', 'True') |
| 110 |
if str2bool(ldap_chase_ref_disabled): |
| 111 |
connection.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF) |
| 112 |
if conf['ldap_tls']: |
| 113 |
connection.start_tls_s() |
| 114 |
return LDAPWrapper(connection) |
| 115 |
|
| 116 |
def _get_entry(self, conf, login): |
| 117 |
filter_tmpl = conf['ldap_filter'] |
| 118 |
placeholders = filter_tmpl.count('%s') |
| 119 |
if not placeholders: |
| 120 |
_logger.warning("LDAP filter %r contains no placeholder ('%%s').", filter_tmpl) |
| 121 |
|
| 122 |
formatted_filter = filter_format(filter_tmpl, [login] * placeholders) |
| 123 |
results = self._query(conf, formatted_filter) |
| 124 |
|
| 125 |
|
| 126 |
results = [entry for entry in results if entry[0]] |
| 127 |
|
| 128 |
dn, entry = False, False |
| 129 |
if len(results) == 1: |
| 130 |
dn, _ = entry = results[0] |
| 131 |
return dn, entry |
| 132 |
|
| 133 |
def _authenticate(self, conf, login, password): |
| 134 |
""" |
| 135 |
Authenticate a user against the specified LDAP server. |
| 136 |
|
| 137 |
In order to prevent an unintended 'unauthenticated authentication', |
| 138 |
which is an anonymous bind with a valid dn and a blank password, |
| 139 |
check for empty passwords explicitely (:rfc:`4513#section-6.3.1`) |
| 140 |
:param dict conf: LDAP configuration |
| 141 |
:param login: username |
| 142 |
:param password: Password for the LDAP user |
| 143 |
:return: LDAP entry of authenticated user or False |
| 144 |
:rtype: dictionary of attributes |
| 145 |
""" |
| 146 |
|
| 147 |
if not password: |
| 148 |
return False |
| 149 |
|
| 150 |
dn, entry = self._get_entry(conf, login) |
| 151 |
if not dn: |
| 152 |
return False |
| 153 |
try: |
| 154 |
conn = self._connect(conf) |
| 155 |
conn.simple_bind_s(dn, password) |
| 156 |
conn.unbind() |
| 157 |
except ldap.INVALID_CREDENTIALS: |
| 158 |
return False |
| 159 |
except ldap.LDAPError as e: |
| 160 |
_logger.error('An LDAP exception occurred: %s', e) |
| 161 |
return False |
| 162 |
return entry |
| 163 |
|
| 164 |
def _query(self, conf, filter, retrieve_attributes=None): |
| 165 |
""" |
| 166 |
Query an LDAP server with the filter argument and scope subtree. |
| 167 |
|
| 168 |
Allow for all authentication methods of the simple authentication |
| 169 |
method: |
| 170 |
|
| 171 |
- authenticated bind (non-empty binddn + valid password) |
| 172 |
- anonymous bind (empty binddn + empty password) |
| 173 |
- unauthenticated authentication (non-empty binddn + empty password) |
| 174 |
|
| 175 |
.. seealso:: |
| 176 |
:rfc:`4513#section-5.1` - LDAP: Simple Authentication Method. |
| 177 |
|
| 178 |
:param dict conf: LDAP configuration |
| 179 |
:param filter: valid LDAP filter |
| 180 |
:param list retrieve_attributes: LDAP attributes to be retrieved. \ |
| 181 |
If not specified, return all attributes. |
| 182 |
:return: ldap entries |
| 183 |
:rtype: list of tuples (dn, attrs) |
| 184 |
|
| 185 |
""" |
| 186 |
|
| 187 |
results = [] |
| 188 |
try: |
| 189 |
conn = self._connect(conf) |
| 190 |
ldap_password = conf['ldap_password'] or '' |
| 191 |
ldap_binddn = conf['ldap_binddn'] or '' |
| 192 |
conn.simple_bind_s(ldap_binddn, ldap_password) |
| 193 |
results = conn.search_st(conf['ldap_base'], ldap.SCOPE_SUBTREE, filter, retrieve_attributes, timeout=60) |
| 194 |
conn.unbind() |
| 195 |
except ldap.INVALID_CREDENTIALS: |
| 196 |
_logger.error('LDAP bind failed.') |
| 197 |
except ldap.LDAPError as e: |
| 198 |
_logger.error('An LDAP exception occurred: %s', e) |
| 199 |
return results |
| 200 |
|
| 201 |
def _map_ldap_attributes(self, conf, login, ldap_entry): |
| 202 |
""" |
| 203 |
Compose values for a new resource of model res_users, |
| 204 |
based upon the retrieved ldap entry and the LDAP settings. |
| 205 |
:param dict conf: LDAP configuration |
| 206 |
:param login: the new user's login |
| 207 |
:param tuple ldap_entry: single LDAP result (dn, attrs) |
| 208 |
:return: parameters for a new resource of model res_users |
| 209 |
:rtype: dict |
| 210 |
""" |
| 211 |
data = { |
| 212 |
'name': ldap_entry[1]['cn'][0], |
| 213 |
'login': login, |
| 214 |
'company_id': conf['company'][0] |
| 215 |
} |
| 216 |
if tools.single_email_re.match(login): |
| 217 |
data['email'] = login |
| 218 |
return data |
| 219 |
|
| 220 |
def _get_or_create_user(self, conf, login, ldap_entry): |
| 221 |
""" |
| 222 |
Retrieve an active resource of model res_users with the specified |
| 223 |
login. Create the user if it is not initially found. |
| 224 |
|
| 225 |
:param dict conf: LDAP configuration |
| 226 |
:param login: the user's login |
| 227 |
:param tuple ldap_entry: single LDAP result (dn, attrs) |
| 228 |
:return: res_users id |
| 229 |
:rtype: int |
| 230 |
""" |
| 231 |
login = login.lower().strip() |
| 232 |
self.env.cr.execute("SELECT id, active FROM res_users WHERE lower(login)=%s", (login,)) |
| 233 |
res = self.env.cr.fetchone() |
| 234 |
if res: |
| 235 |
if res[1]: |
| 236 |
return res[0] |
| 237 |
elif conf['create_user']: |
| 238 |
_logger.debug("Creating new Odoo user \"%s\" from LDAP" % login) |
| 239 |
values = self._map_ldap_attributes(conf, login, ldap_entry) |
| 240 |
SudoUser = self.env['res.users'].sudo().with_context(no_reset_password=True) |
| 241 |
if conf['user']: |
| 242 |
values['active'] = True |
| 243 |
return SudoUser.browse(conf['user'][0]).copy(default=values).id |
| 244 |
else: |
| 245 |
return SudoUser.create(values).id |
| 246 |
|
| 247 |
raise AccessDenied(_("No local user found for LDAP login and not configured to create one")) |
| 248 |
|
| 249 |
def _change_password(self, conf, login, old_passwd, new_passwd): |
| 250 |
changed = False |
| 251 |
dn, entry = self._get_entry(conf, login) |
| 252 |
if not dn: |
| 253 |
return False |
| 254 |
try: |
| 255 |
conn = self._connect(conf) |
| 256 |
conn.simple_bind_s(dn, old_passwd) |
| 257 |
conn.passwd_s(dn, old_passwd, new_passwd) |
| 258 |
changed = True |
| 259 |
conn.unbind() |
| 260 |
except ldap.INVALID_CREDENTIALS: |
| 261 |
pass |
| 262 |
except ldap.LDAPError as e: |
| 263 |
_logger.error('An LDAP exception occurred: %s', e) |
| 264 |
return changed |
| 265 |
|
| 266 |
def test_ldap_connection(self): |
| 267 |
""" |
| 268 |
Test the LDAP connection using the current configuration. |
| 269 |
Returns a dictionary with notification parameters indicating success or failure. |
| 270 |
""" |
| 271 |
conf = { |
| 272 |
'ldap_server': self.ldap_server, |
| 273 |
'ldap_server_port': self.ldap_server_port, |
| 274 |
'ldap_binddn': self.ldap_binddn, |
| 275 |
'ldap_password': self.ldap_password, |
| 276 |
'ldap_base': self.ldap_base, |
| 277 |
'ldap_tls': self.ldap_tls |
| 278 |
} |
| 279 |
|
| 280 |
bind_dn = self.ldap_binddn or '' |
| 281 |
bind_passwd = self.ldap_password or '' |
| 282 |
|
| 283 |
try: |
| 284 |
conn = self._connect(conf) |
| 285 |
conn.simple_bind_s(bind_dn, bind_passwd) |
| 286 |
conn.unbind() |
| 287 |
|
| 288 |
return { |
| 289 |
'type': 'ir.actions.client', |
| 290 |
'tag': 'display_notification', |
| 291 |
'params': { |
| 292 |
'type': 'success', |
| 293 |
'title': _('Connection Test Successful!'), |
| 294 |
'message': _("Successfully connected to LDAP server at %(server)s:%(port)d", |
| 295 |
server=self.ldap_server, port=self.ldap_server_port), |
| 296 |
'sticky': False, |
| 297 |
} |
| 298 |
} |
| 299 |
|
| 300 |
except ldap.SERVER_DOWN: |
| 301 |
return { |
| 302 |
'type': 'ir.actions.client', |
| 303 |
'tag': 'display_notification', |
| 304 |
'params': { |
| 305 |
'type': 'danger', |
| 306 |
'title': _('Connection Test Failed!'), |
| 307 |
'message': _("Cannot contact LDAP server at %(server)s:%(port)d", |
| 308 |
server=self.ldap_server, port=self.ldap_server_port), |
| 309 |
'sticky': False, |
| 310 |
} |
| 311 |
} |
| 312 |
|
| 313 |
except ldap.INVALID_CREDENTIALS: |
| 314 |
return { |
| 315 |
'type': 'ir.actions.client', |
| 316 |
'tag': 'display_notification', |
| 317 |
'params': { |
| 318 |
'type': 'danger', |
| 319 |
'title': _('Connection Test Failed!'), |
| 320 |
'message': _("Invalid credentials for bind DN %(binddn)s", |
| 321 |
binddn=self.ldap_binddn), |
| 322 |
'sticky': False, |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
except ldap.TIMEOUT: |
| 327 |
return { |
| 328 |
'type': 'ir.actions.client', |
| 329 |
'tag': 'display_notification', |
| 330 |
'params': { |
| 331 |
'type': 'danger', |
| 332 |
'title': _('Connection Test Failed!'), |
| 333 |
'message': _("Connection to LDAP server at %(server)s:%(port)d timed out", |
| 334 |
server=self.ldap_server, port=self.ldap_server_port), |
| 335 |
'sticky': False, |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
except ldap.LDAPError as e: |
| 340 |
return { |
| 341 |
'type': 'ir.actions.client', |
| 342 |
'tag': 'display_notification', |
| 343 |
'params': { |
| 344 |
'type': 'danger', |
| 345 |
'title': _('Connection Test Failed!'), |
| 346 |
'message': _("An error occurred: %(error)s", |
| 347 |
error=e), |
| 348 |
'sticky': False, |
| 349 |
} |
| 350 |
} |