Mar 22, 2022

Django authentication with group mirror in netbox - FreeIPA and Active Directory

Scenario:

Enable the authentication on NetBox to be able to mirror the LDAP groups and assign the permissions automatically inside NetBox, without any interaction.

Official documentation:

Environment versions

Netbox: v2.11.10

Python: 3.8.10

FreeIPA: 4.9.8

IPA

DOMAIN: dc=lab,dc=local

Log and trobleshoting

  • Check logs
  • Use LDAPsearch to check if the user is inside the defined group, look for memberOF e.g:

ldapsearch -x \ -b "cn=<your group name>,ou=group,dc=<your org>,dc=com" \ -H ldaps://<ldap server>:<port>

ldapsearch -H host -LLL -b "cn=" uid=* memberOf

  • check ports
  • check communication client/server

If there are syntax errors present, the NetBox process will not spawn an instance, and errors should be logged to /var/log/messages.

For troubleshooting LDAP user/group queries, add or merge the following logging configuration to configuration.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'netbox_auth_log': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '/opt/netbox/local/logs/django-ldap-debug.log',
            'maxBytes': 1024 * 500,
            'backupCount': 5,
        },
    },
    'loggers': {
        'django_auth_ldap': {
            'handlers': ['netbox_auth_log'],
            'level': 'DEBUG',
        },
    },
}

Logs when the authentication works

search_s('cn=users,cn=accounts,dc=lab,dc=local', 2, '(uid=%(user)s)') returned 1 objects: uid=luiz,cn=users,cn=accounts,dc=lab,dc=local
Populating Django user luiz
uid=luiz,cn=users,cn=accounts,dc=lab,dc=local is a member of cn=active,cn=groups,cn=accounts,dc=lab,dc=local
uid=luiz,cn=users,cn=accounts,dc=lab,dc=local is a member of cn=staff,cn=groups,cn=accounts,dc=lab,dc=local
uid=luiz,cn=users,cn=accounts,dc=lab,dc=local is a member of cn=superuser,cn=groups,cn=accounts,dc=lab,dc=local

Configuration file base - LDAP - FREE IPA

########################################################################################################################
# LDAP Authentication Settings
########################################################################################################################

import ldap
import os
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType

LDAP_SERVER = 'freeipa.auth'
AUTH_LDAP_SERVER_URI = 'ldap://' + LDAP_SERVER

AUTH_LDAP_BIND_DN = 'uid=admin,cn=users,cn=accounts,dc=hqvfx,dc=auth'
AUTH_LDAP_BIND_PASSWORD = os.environ.get('MY_PASS')
AUTH_LDAP_USER_DN_TEMPLATE = 'uid=%(user)s,cn=users,cn=accounts,dc=hqvfx,dc=auth'

AUTH_LDAP_USER_ATTR_MAP = {
    'first_name': 'givenName',
    'last_name': 'sn',
    'email': 'mail'
}

AUTH_LDAP_GROUP_BASE = "cn=groups,cn=accounts,dc=hqvfx,dc=auth"
AUTH_LDAP_GROUP_FILTER = "(objectClass=groupOfNames)"
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(AUTH_LDAP_GROUP_BASE,
                                    ldap.SCOPE_SUBTREE, AUTH_LDAP_GROUP_FILTER)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn")

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    'is_staff': 'cn=ipausers,' + AUTH_LDAP_GROUP_BASE,
    'is_support': 'cn=ipausers,' + AUTH_LDAP_GROUP_BASE,
    'is_superuser': 'cn=ipausers,' + AUTH_LDAP_GROUP_BASE,
}

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)
# Mirror LDAP group assignments.
AUTH_LDAP_MIRROR_GROUPS = True 

# This is the default, but I like to be explicit.
AUTH_LDAP_ALWAYS_UPDATE_USER = True

Configuration file base - LDAP - Active Directory

import ldap
from django_auth_ldap.config import LDAPSearch, NestedGroupOfNamesType

# Server URI
AUTH_LDAP_SERVER_URI = "ldap://192.168.0.227"
# The following may be needed if you are binding to Active Directory.
AUTH_LDAP_CONNECTION_OPTIONS = {
    ldap.OPT_REFERRALS: 0
}
# Set the DN and password for the NetBox service account.
AUTH_LDAP_BIND_DN = "CN=netboxsa,OU=Service Accounts,DC=windows-lab,DC=com"
AUTH_LDAP_BIND_PASSWORD = "********"

# Include this setting if you want to ignore certificate errors. This might be needed to accept a self-signed cert.
# Note that this is a NetBox-specific setting which sets:
#     ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
LDAP_IGNORE_CERT_ERRORS = True

from django_auth_ldap.config import LDAPSearch
# This search matches users with the sAMAccountName equal to the provided username. This is required if the user’s
# username is not in their DN (Active Directory).
AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=windows-lab,DC=com",
                                    ldap.SCOPE_SUBTREE,
                                    "(sAMAccountName=%(user)s)")

# If a user’s DN is producible from their username, we don’t need to search.
#AUTH_LDAP_USER_DN_TEMPLATE = "UID=%(user)s,OU=Service Accounts,DC=windows-lab,DC=com"
# You can map user attributes to Django attributes as so.
AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail"
}

# This search ought to return all groups to which the user belongs. django_auth_ldap uses this to determine group
# hierarchy.
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=windows-lab,DC=com", ldap.SCOPE_SUBTREE,
                                    "(objectClass=group)")
AUTH_LDAP_GROUP_TYPE = NestedGroupOfNamesType()

# Define a group required to login.
AUTH_LDAP_REQUIRE_GROUP = "CN=NetboxActive,OU=Service Accounts,DC=windows-lab,DC=com"

# Mirror LDAP group assignments.
AUTH_LDAP_MIRROR_GROUPS = True

# Define special user types using groups. Exercise great caution when assigning superuser status.
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    "is_active": "CN=NetboxActive,OU=Service Accounts,DC=windows-lab,DC=com",
    "is_staff": "CN=NetboxStaff,OU=Service Accounts,DC=windows-lab,DC=com",
    "is_superuser": "CN=NetboxSuperuser,OU=Service Accounts,DC=windows-lab,DC=com"
}

# For more granular permissions, we can map LDAP groups to Django groups.
AUTH_LDAP_FIND_GROUP_PERMS = True
# Cache groups for one hour to reduce LDAP traffic
#AUTH_LDAP_CACHE_TIMEOUT = 3600

Permissions

  • is_active - All users must be mapped to at least this group to enable authentication. Without this, users cannot log in.
  • is_staff - Users mapped to this group are enabled for access to the administration tools; this is the equivalent of checking the "staff status" box on a manually created user. This doesn't grant any specific permissions.
  • is_superuser - Users mapped to this group will be granted superuser status. Superusers are implicitly granted all permissions.

Commom issue

Authentication failed for admin: user DN/password rejected by LDAP server.
search_s('cn=users,cn=accounts,dc=lab,dc=local', 2, '(uid=%(user)s)') returned 1 objects: uid=luiz,cn=users,cn=accounts,dc=lab,dc=local
Caught LDAPError while authenticating luiz: UNWILLING_TO_PERFORM({'msgtype': 111, 'msgid': 5, 'result': 53, 'desc': 'Server is unwilling to perform', 'ctrls': []})
search_s('cn=users,cn=accounts,dc=lab,dc=local', 2, '(uid=%(user)s)') returned 1 objects: uid=luiz,cn=users,cn=accounts,dc=lab,dc=local
Caught LDAPError while authenticating luiz: UNWILLING_TO_PERFORM({'msgtype': 111, 'msgid': 5, 'result': 53, 'desc': 'Server is unwilling to perform', 'ctrls': []})

Caught LDAPError while authenticating lpereira: UNWILLING_TO_PERFORM({'desc': 'Server is unwilling to perform'},)

No comments:

Post a Comment