diff --git a/Users/ldap_auth.py b/Users/ldap_auth.py index 2d2d3d6..ea6a078 100644 --- a/Users/ldap_auth.py +++ b/Users/ldap_auth.py @@ -12,7 +12,7 @@ from django.db.models import Q from ldap3 import Connection, Server, ALL, ObjectDef, Reader, NTLM, Entry from ldap3.core.exceptions import LDAPSocketOpenError -from .ldap_errors import LDAPConnectionError, LDAPInvalidCredentials, LDAPAuthException +from .ldap_errors import LDAPConnectionError, LDAPInvalidCredentials, LDAPNotInContextException, LDAPAuthException from .models import User @@ -180,7 +180,10 @@ class LDAPAuthentication(BaseBackend): reader = self.get_all_users(conn) results = reader.match("msDS-PrincipalName", username) - return results[0] + if len(results) == 0: + raise LDAPNotInContextException() + else: + return results[0] def authenticate(self, request, username: str = None, password: str = None) -> Optional[User]: """ @@ -203,6 +206,9 @@ class LDAPAuthentication(BaseBackend): return self.create_from_ldap(ldap_user, guid) except LDAPInvalidCredentials: return None + except LDAPNotInContextException: + messages.add_message(request, messages.ERROR, "This user is not allowed to login to CodeReview, please contact your administrator.") + return None except LDAPConnectionError: if settings.DEBUG is False: messages.add_message(request, messages.ERROR, diff --git a/Users/ldap_errors.py b/Users/ldap_errors.py index 9b4a748..112b3cb 100644 --- a/Users/ldap_errors.py +++ b/Users/ldap_errors.py @@ -23,3 +23,12 @@ class LDAPConnectionError(LDAPAuthException): """ This exception is used when we can't contact ActiveDirectory """ + pass + + +class LDAPNotInContextException(LDAPAuthException): + """ + This exception is used when we can't find the user in the LDAP_BASE_CONTEXT, this could mean that the user is not in our class/campus + """ + pass + diff --git a/Users/ldap_mock.py b/Users/ldap_mock.py index 6726009..d63e4b8 100644 --- a/Users/ldap_mock.py +++ b/Users/ldap_mock.py @@ -28,6 +28,7 @@ class LDAPMockAuthentication(LDAPAuthentication): 'tests/ldap_test_server/test_schema.json') users = {} + raw_users = {} @classmethod def construct_dn(cls, username: str) -> str: @@ -56,6 +57,19 @@ class LDAPMockAuthentication(LDAPAuthentication): user = cls.users.get(username, {'ou': None}) return user.get('ou') + @classmethod + def create_user_manual(cls, conn: Connection, dn: str, user: dict) -> None: + """ + This function creates a user manually without automatic setup of the dn and other values + + :param dn: Distinguished name of the user + :type dn: str + :param user: The dictionary to use when creating the user entry + :type user: dict + """ + + conn.strategy.add_entry(dn, user) + @classmethod def create_fake_user(cls, conn: Connection, username: str, email: str, password: str, first: str, last: str, ou: str = None) -> None: """ @@ -99,6 +113,9 @@ class LDAPMockAuthentication(LDAPAuthentication): for username in cls.users.keys(): user = cls.users.get(username) cls.create_fake_user(conn, username, f"{username}@example.com", user['password'], user['first'], user['last'], user['ou']) + for dn in cls.raw_users.keys(): + user = cls.raw_users.get(dn) + cls.create_user_manual(conn, dn, user) @classmethod def get_connection(cls, username: str, password: str) -> Connection: @@ -116,7 +133,8 @@ class LDAPMockAuthentication(LDAPAuthentication): cls.setup_server() username = username.split('\\')[1] - conn = Connection(cls.server, cls.construct_dn(username), password, + dn = cls.construct_dn(username) if username not in [k.split(',')[0].split('=')[1] for k in cls.raw_users.keys()] else f"cn={username},ou=EvilPeople,dc=example,dc=com" + conn = Connection(cls.server, dn, password, client_strategy=MOCK_SYNC) cls.create_fake_users(conn) return cls.bind_connection(conn) diff --git a/tests/test_auth.py b/tests/test_auth.py index a09c295..166d525 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -18,7 +18,7 @@ class LogoutTest(SimpleBaseCase): @override_settings(AUTHENTICATION_BACKENDS=['Users.ldap_mock.LDAPMockAuthentication'], LDAP_DOMAIN="example", - LDAP_BASE_CONTEXT="ou=ITP Users,dc=itp,dc=example", LDAP_URL="0.0.0.0", LDAP_ADMIN_NAME="example\\admin") + LDAP_BASE_CONTEXT="ou=ITP Users,dc=itp,dc=example,dc=com", LDAP_URL="0.0.0.0", LDAP_ADMIN_NAME="example\\admin") class LDAPAuthTest(SimpleBaseCase): url = reverse('login') @@ -50,6 +50,18 @@ class LDAPAuthTest(SimpleBaseCase): 'ou': "AM" } } + LDAPMockAuthentication.raw_users = { + 'cn=bob,ou=EvilPeople,dc=example,dc=com': { + 'objectGUID': str(uuid4()), + 'objectClass': 'user', + 'mail': 'b.evilguy@evilcorp.bad', + 'distinguishedName': 'cn=bob,ou=EvilPeople,dc=example,dc=com', + 'msDs-principalName': "example\\bob", + 'userPassword': "imsoevil123", + 'givenName': "Bobert", + 'sn': 'EvilGuy' + } + } def test_admin_login(self) -> None: self.client.post(self.url, {'username': "admin", "password": "admin_password123"}) @@ -95,6 +107,10 @@ class LDAPAuthTest(SimpleBaseCase): response = self.client.post(self.url, {'username': "invalid_user", 'password': "invalid_password"}) self.assertEqual(len(response.context.get('form').non_field_errors()), 1) + def test_not_in_context(self) -> None: + response = self.client.post(self.url, {'username': "bob", 'password': "imsoevil123"}) + self.assertMessage(response, "This user is not allowed to login to CodeReview, please contact your administrator.") + @override_settings(AUTHENTICATION_BACKENDS=['Users.ldap_auth.LDAPAuthentication']) def test_cant_connect(self) -> None: response = self.client.post(self.url, {'username': "admin", 'password': "admin_password123"})