Exemple #1
0
    def __new__(cls, *args, **kwargs):
        try:
            from django_auth_ldap.backend import (
                LDAPBackend as LDAPBackend_,
                LDAPSettings,
            )
            import ldap
        except ModuleNotFoundError as e:
            if getattr(e, "name") == "django_auth_ldap":
                logging.error(
                    "LDAP authentication has been configured, but django-auth-ldap is not installed."
                )

        # Try to import `ldap_config.py`
        # FIXME(jathan): Have this read from `django.conf.settings` instead vs.
        # another config file that has to be dropped inside of the Nautobot code
        # deployment.
        try:
            from nautobot.core import ldap_config
        except (ModuleNotFoundError, ImportError) as e:
            if getattr(e, "name") == "ldap_config":
                logging.error(
                    "LDAP configuration file not found: Check that ldap_config.py has been created."
                )
            ldap_config = None

        # Once we've asserted that imports/settings work, set this backend as
        # usable.
        try:
            getattr(ldap_config, "AUTH_LDAP_SERVER_URI")
        except AttributeError:
            logging.error(
                "Required parameter AUTH_LDAP_SERVER_URI is missing from ldap_config.py."
            )
        else:
            cls.is_usable = True

        # If the LDAP dependencies aren't set/working, just return a dummy
        # backend and soft fail.
        if not cls.is_usable:
            return DummyBackend()

        # Create a new instance of django-auth-ldap's LDAPBackend
        obj = LDAPBackend_()

        # Read LDAP configuration parameters from ldap_config.py instead of settings.py
        settings = LDAPSettings()
        for param in dir(ldap_config):
            if param.startswith(settings._prefix):
                setattr(settings, param[10:], getattr(ldap_config, param))
        obj.settings = settings

        # Optionally disable strict certificate checking
        if getattr(ldap_config, "LDAP_IGNORE_CERT_ERRORS", False):
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

        return obj
Exemple #2
0
    def create_ldap_user(sender, instance, created, **kwargs):
        username = instance.first_name[0] + "".join(instance.last_name.split(" "))
        username = unidecode.unidecode(username.lower())
        
        if not created or User.objects.filter(username=username).count():
            return

        ldap_c = _LDAPConfig.get_ldap()

        ldap_settings = LDAPSettings()
        conn = ldap_c.initialize(django_settings.AUTH_LDAP_SERVER_URI)
        conn.simple_bind_s(django_settings.AUTH_LDAP_BIND_DN, django_settings.AUTH_LDAP_BIND_PASSWORD)
        for opt, value in ldap_settings.CONNECTION_OPTIONS.iteritems():
            conn.set_option(opt, value)

        uid = gid = 1500 + instance.id
        new_password = get_pronounceable_password()
        new_user_group = [
                    ('objectclass', ['posixGroup', 'top']),
                    ('gidNumber', str(gid)),
                    ]
        try:
            conn.add_s('cn=' + str(username) + ',ou=groups,dc=bomberos,dc=usb,dc=ve', new_user_group)
        except:
            pass

        new_user = [
                    ('objectclass', ['inetOrgPerson', 'posixAccount', 'top']),
                    ('gidNumber', str(gid)),
                    ('uidNumber', str(uid)),
                    ('sn', str(instance)),
                    ('givenName', str(instance.first_name.encode('UTF-8'))),
                    ('displayName', str(instance.first_name.encode('UTF-8')) + " " + str(instance.last_name.encode('UTF-8'))),
                    ('cn', str(instance.first_name.encode('UTF-8')) + " " + str(instance.last_name.encode('UTF-8'))),
                    ('homeDirectory', str('/home/') + str(username) + '/'),
                    ('loginShell', str('/bin/bash')),
                    ('userPassword', makeSecret(new_password)),
                    ('mail', username+"@bomberos.usb.ve"),
                    ]

        try:
            conn.add_s('uid=' + username + ',ou=users,dc=bomberos,dc=usb,dc=ve', new_user)
        except:
            pass
        mod_attrs = [(ldap_c.MOD_ADD, 'memberUid', username)]
        try:
            conn.modify_s('cn=cbvusb,ou=groups,dc=bomberos,dc=usb,dc=ve', mod_attrs)
        except:
            pass

        send_welcome_email(str(instance), username, new_password, instance.alternate_email)
        send_webmaster_email(username)
        instance.primary_email = username + "@bomberos.usb.ve"
        instance.save()
Exemple #3
0
def search_ldap_for_user(username):
    """
    Connects to LDAP using the settings and credentials defined for django_auth_ldap, then searches for a
    user matching the given username.

    Returns None if the user isn't found in LDAP, or tuple of (user_dn, ldap_attrs_dict) if it is.
    """
    # This is pretty gnarly, but the way that django_auth_ldap's got all its LDAP code split up across its
    # various classes, this is probably much less nasty than trying to do it more directly.
    ldap_user = _LDAPUser(LDAPBackend(), username=username.strip())
    results = LDAPSettings().USER_SEARCH.execute(ldap_user.connection,
                                                 {'user': username})
    if len(results) == 1:
        return results[0]
    return None
Exemple #4
0
    def update_ldap_password(self, password = None):
        if not django_settings.AUTH_LDAP_BIND_PASSWORD:
            return
        
        ldap_c = _LDAPConfig.get_ldap()
        ldap_settings = LDAPSettings()
        conn = ldap_c.initialize(django_settings.AUTH_LDAP_SERVER_URI)
        conn.simple_bind_s(django_settings.AUTH_LDAP_BIND_DN, django_settings.AUTH_LDAP_BIND_PASSWORD)
        
        for opt, value in ldap_settings.CONNECTION_OPTIONS.iteritems():
            conn.set_option(opt, value)
        
        new_password = get_pronounceable_password() if not password else password
        username = self.primary_email.split("@")[0]
        mod_attrs = [(ldap_c.MOD_REPLACE, 'userPassword', makeSecret(new_password))]
        conn.modify_s('uid='+username+',ou=users,dc=bomberos,dc=usb,dc=ve', mod_attrs)

        send_welcome_email(str(self), username, new_password, self.alternate_email)
Exemple #5
0
    def __new__(cls, *args, **kwargs):
        try:
            from django_auth_ldap.backend import LDAPSettings
            import ldap
        except ModuleNotFoundError as e:
            if getattr(e, 'name') == 'django_auth_ldap':
                raise ImproperlyConfigured(
                    "LDAP authentication has been configured, but django-auth-ldap is not installed."
                )
            raise e

        try:
            from netbox import ldap_config
        except ModuleNotFoundError as e:
            if getattr(e, 'name') == 'ldap_config':
                raise ImproperlyConfigured(
                    "LDAP configuration file not found: Check that ldap_config.py has been created alongside "
                    "configuration.py."
                )
            raise e

        try:
            getattr(ldap_config, 'AUTH_LDAP_SERVER_URI')
        except AttributeError:
            raise ImproperlyConfigured(
                "Required parameter AUTH_LDAP_SERVER_URI is missing from ldap_config.py."
            )

        obj = NBLDAPBackend()

        # Read LDAP configuration parameters from ldap_config.py instead of settings.py
        settings = LDAPSettings()
        for param in dir(ldap_config):
            if param.startswith(settings._prefix):
                setattr(settings, param[10:], getattr(ldap_config, param))
        obj.settings = settings

        # Optionally disable strict certificate checking
        if getattr(ldap_config, 'LDAP_IGNORE_CERT_ERRORS', False):
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

        return obj
Exemple #6
0
    def __new__(cls, *args, **kwargs):
        try:
            import ldap
            from django_auth_ldap.backend import LDAPBackend as LDAPBackend_, LDAPSettings
        except ImportError:
            raise ImproperlyConfigured(
                "LDAP authentication has been configured, but django-auth-ldap is not installed."
            )

        try:
            from netbox import ldap_config
        except ImportError:
            raise ImproperlyConfigured("ldap_config.py does not exist")

        try:
            getattr(ldap_config, 'AUTH_LDAP_SERVER_URI')
        except AttributeError:
            raise ImproperlyConfigured(
                "Required parameter AUTH_LDAP_SERVER_URI is missing from ldap_config.py."
            )

        # Create a new instance of django-auth-ldap's LDAPBackend
        obj = LDAPBackend_()

        # Read LDAP configuration parameters from ldap_config.py instead of settings.py
        settings = LDAPSettings()
        for param in dir(ldap_config):
            if param.startswith(settings._prefix):
                setattr(settings, param[10:], getattr(ldap_config, param))
        obj.settings = settings

        # Optionally disable strict certificate checking
        if getattr(ldap_config, 'LDAP_IGNORE_CERT_ERRORS', False):
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

        # Enable logging for django_auth_ldap
        ldap_logger = logging.getLogger('django_auth_ldap')
        ldap_logger.addHandler(logging.StreamHandler())
        ldap_logger.setLevel(logging.INFO)

        return obj