Background
Recently I needed to lock down Netbox to only perform LDAP authentication for users present within its local (Django) DB.
After some investigation Googling, I found that there was a setting within the Django LDAP module that would provide exactly this - AUTH_LDAP_NO_NEW_USERS
. Great!
However, from looking into the release notes I soon found that this setting is only available from within django-ldap-auth==2.0.0
which is still yet to be released.
Steps
Below are the steps required to backport the AUTH_LDAP_NO_NEW_USERS
feature.
Note: These steps are based on Netbox 2.5.7 and dango-ldap-auth 1.7.0.
[root@netbox ~]# pip freeze | grep django-auth-ldap
django-auth-ldap==1.7.0
Create LDAP Backend
Create a custom LDAP backend - /opt/netbox/netbox/users/backend.py
- containing the following.
from django_auth_ldap import backend as ldap_backend
# backport for AUTH_LDAP_NO_NEW_USERS setting
ldap_backend.LDAPSettings.defaults.update(NO_NEW_USERS=False)
class MyLDAPBackend(ldap_backend.LDAPBackend):
def get_or_build_user(self, username, ldap_user):
user, built = super().get_or_build_user(username, ldap_user)
if self.settings.NO_NEW_USERS and built: # user was not found in local db and created instead
raise ldap_user.AuthenticationFailed(
f'username {username} does not exist in local DB.'
)
return user, built
Update Settings
Update /opt/netbox/netbox/netbox/settings.py
accordingly.
...
if LDAP_CONFIGURED:
try:
import ldap
import django_auth_ldap
# Prepend LDAPBackend to the default ModelBackend
AUTHENTICATION_BACKENDS = [
+ #'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
]
+ AUTHENTICATION_BACKENDS += ('users.backend.MyLDAPBackend',)
# Optionally disable strict certificate checking
if LDAP_IGNORE_CERT_ERRORS:
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
Update LDAP Config
Within the following file /opt/netbox/netbox/netbox/ldap_config.py
add the following.
...
from django_auth_ldap.config import LDAPSearch
+ AUTH_LDAP_NO_NEW_USERS = True
AUTH_LDAP_USER_SEARCH = LDAPSearch("o=sales",
ldap.SCOPE_SUBTREE,
"(uid=%(user)s)")
...
Restart
Now restart Netbox,
supervisorctl restart netbox
Test
You can now test by going into the Netbox admin portal removing your user and then trying to reauthenticate. Access should now be denied.
Reference
https://stackoverflow.com/questions/55828292/django-auth-with-ldap-and-local-accounts