Ejemplo n.º 1
0
Archivo: ldap.py Proyecto: epfl-si/amm
    def get_user_dn(self, username):

        server = ldap3.Server('ldap://' + self.ldap_server)
        connection = ldap3.Connection(server)
        connection.open()

        connection.search(
            search_base=self.dn,
            search_filter='(' + self.user_attr + '=' + username + ')'
        )
        return connection.response[0]['dn']
Ejemplo n.º 2
0
 def setUp(self):
     super().setUp()
     self._ldap_test_server = LdapServer(self.ldap_server_data)
     self._ldap_test_server.start()
     ldap3_server = ldap3.Server('localhost', port=self._ldap_test_server.config['port'])
     self._ldap_connection = ldap3.Connection(
         ldap3_server,
         user=self._ldap_test_server.config['bind_dn'],
         password=self._ldap_test_server.config['password'],
         auto_bind=True
     )
Ejemplo n.º 3
0
 def get_connection(self, userdn, password):
     server = ldap3.Server(self.server_address,
                           port=self.server_port,
                           use_ssl=self.use_ssl)
     auto_bind = (self.use_ssl and ldap3.AUTO_BIND_TLS_BEFORE_BIND
                  or ldap3.AUTO_BIND_NO_TLS)
     conn = ldap3.Connection(server,
                             user=userdn,
                             password=password,
                             auto_bind=auto_bind)
     return conn
Ejemplo n.º 4
0
def ldap_server():
    uri = config.get(section, 'uri')
    if not uri:
        return
    uri, _, _, _, _, extensions = parse_ldap_url(uri)
    if uri.scheme.startswith('ldaps'):
        scheme, port = 'ldaps', 636
    else:
        scheme, port = 'ldap', 389
    return ldap3.Server('%s://%s:%s' % (
            scheme, uri.hostname, uri.port or port))
 def getConnection(userdn, username, password):
     server = ldap3.Server(self.server_address,
                           port=self.server_port,
                           use_ssl=self.use_ssl)
     self.log.debug(
         'Attempting to bind {username} with {userdn}'.format(
             username=username, userdn=userdn))
     conn = ldap3.Connection(server,
                             user=self.escape_userdn_if_needed(userdn),
                             password=password)
     return conn
Ejemplo n.º 6
0
 def ldap_auth(self, user, password, auth_conf):
     server = ldap3.Server(auth_conf['host'], get_info=ldap3.NONE)
     conn = ldap3.Connection(server, auth_conf['user_dn'].format(user),
                             password)
     conn.bind()
     result = conn.search(auth_conf['search_base'],
                          auth_conf['search_filter'].format(user),
                          attributes=ldap3.ALL_ATTRIBUTES)
     if not result or not len(conn.entries):
         return (False, None)
     return (True, user)
Ejemplo n.º 7
0
Archivo: auth.py Proyecto: nishan7/LDAP
def connect_server(server_uri, user_dc, password):
    """

    :param server_uri: LDAP Server URI
    :param user_dc: User DC
    :param password: Password
    :return: LDAP conenction
    """
    server = ldap3.Server(server_uri, get_info=ldap3.ALL)
    connection = ldap3.Connection(server, user=user_dc, password=password)
    return connection
Ejemplo n.º 8
0
def run_main():
    """ get the config """
    config = get_config()
    # start the logger for troubleshooting
    myDebug = config['debug']
    if myDebug == '1':
        logger = setup_logging()  # logger

    # starting the main
    logging.info('Starting the main task ...')

    # use user provided options or get [default] stanza options
    try:  # lets do it
        logging.info('read the default options from inputs.conf...')

        # check [default] stanza if we need ssl
        logging.info('reading usessl from inputs.conf...')
        usessl = config['usessl']
        if usessl == '1':
            server = ldap3.Server(host=config['server'],
                                  port=int(config['port']),
                                  use_ssl='%s' % usessl)
        else:
            server = ldap3.Server(host=config['server'],
                                  port=int(config['port']),
                                  use_ssl=False)
        logging.info('usessl is : %s ...' % usessl)

        # set timeout to 30 seconds, sizelimit to 10 and search scope base
        logging.info('reading basedn from inputs.conf...')
        timeout = '30'
        sizelimit = 10
        scope = 'sub'

    except Exception, e:  # get error back
        logging.error('ERROR: unable to get default options from inputs.conf')
        logging.error('ERROR: %s' % e)
        splunk.Intersplunk.generateErrorResults(
            ': unable to get default options from inputs.conf'
        )  # print the error into Splunk UI
        sys.exit()  # exit on error
Ejemplo n.º 9
0
def get_ldap_stat(server_id):

    server = Server.query.get(server_id)
    if server:
        try:
            ldap_server = ldap3.Server('ldaps://{}:1636'.format(server.hostname))
            conn = ldap3.Connection(ldap_server)
            if conn.bind(): 
                return "1"
        except:
            pass
    return "0"
Ejemplo n.º 10
0
def establish_and_return_ldap_connection(host, port, use_ssl, ca_certs_file,
                                         ca_certs_data, bind_dn, bind_pw):
    tls = None
    if ca_certs_file or ca_certs_data:
        tls = ldap3.Tls(ca_certs_file=ca_certs_file,
                        ca_certs_data=ca_certs_data,
                        validate=ssl.CERT_REQUIRED)
    server = ldap3.Server(host=host, port=port, use_ssl=use_ssl, tls=tls)
    return ldap3.Connection(server,
                            user=bind_dn,
                            password=bind_pw,
                            auto_bind=True)
Ejemplo n.º 11
0
def get_ldap_connection():

    user = '******'
    password = '******'

    try:
        return ldap3.Connection(ldap3.Server('ldap://localhost:389'),
                                user,
                                password,
                                auto_bind=True)
    except:
        return None
Ejemplo n.º 12
0
def ldump():
    """
    Searches for students, faculty, and staff, and saves them all.
    """
    c = ldap3.Connection(ldap3.Server(ADDRESS, PORT))
    c.open()
    entries = []
    ids = set()
    for dept, query, in QUERIES:
        add_results(c, dept, query, entries, ids)
    write_csv_results(entries)
    c.unbind()
Ejemplo n.º 13
0
    def ensure_connection(self):
        tls = None
        if self.connection is None:
            if self.settings_dict.get('TLS', False):
                tls = TLS()

            server = ldap3.Server(self.settings_dict['NAME'], tls=tls)
            self.connection = ldap3.Connection(
                server,
                user=self.settings_dict['USER'],
                password=self.settings_dict['PASSWORD'],
                auto_bind=True)
Ejemplo n.º 14
0
class ldapipl:


server = ldap3.Server('tetsuo')
conn = ldap3.Connection(server, user= LDAP_DOMAIN + "\\" + LDAP_USER, password = LDAP_PWD, authentication='NTLM')
conn.bind()
if not conn.bind():
    print('error in bind', conn.result)
print conn
"""conn.search(search_base = 'CN=Users,DC=XXXXXX,DC=COM',
	search_filter = '(objectClass=user)',
	search_scope = 'SUBTREE',
	attributes = ['cn', 'givenName','objectClass'],
	paged_size = 50)
total_entries += len(conn.response)
for entry in conn.response:
	try :
		print entry['dn']
	except:
		print "--" + str(entry['dn'].encode("iso-8859-1" ))
	print entry['attributes']

cookie = conn.result['controls']['1.2.840.113556.1.4.319']['value']['cookie']
while cookie:
	conn.search(search_base = 'CN=Users',
		search_filter = '(objectClass=user)',
		search_scope = 'SUBTREE',
		attributes = ['cn', 'givenName','objectClass'],
		paged_size = 50,
		paged_cookie = cookie)
	total_entries += len(conn.response)
	cookie = conn.result['controls']['1.2.840.113556.1.4.319']['value']['cookie']
	for entry in conn.response:
		try :
			print entry['dn']
		except:
			print "--" + str(entry['dn'].encode("iso-8859-1" ))
		print entry['attributes']
print('Total entries retrieved:', total_entries)

#conn.add('cn=testpython,cn=users,dc=xxxxxxx,dc=com', ['top','person','organizationalPerson','user'], {'sn': 'Young'})
conn.add('cn=testpython,cn=users,dc=xxxxxxx,dc=com', ['top','group'])"""

if conn.search('CN=Thierry ETA,CN=Users,DC=xxxxxxx,DC=com', '(objectclass=person)'):
	print 'ok'
else :
	print 'pas ok'

print(conn.result)

# close the connection

conn.unbind()
Ejemplo n.º 15
0
def clear():
    import ldap3
    # Connecting to a fake server with a fake account:
    server = ldap3.Server(BIND_HOST, port=BIND_PORT)
    conn = ldap3.Connection(server,
                            user=BIND_DN,
                            password=BIND_PW,
                            auto_bind=True)
    conn.delete(fakeuser['dn'])
    conn.delete(BASE_DN)
    conn.delete(DOMAIN_DN)
    conn.close()
Ejemplo n.º 16
0
    def _ldap_bind(self, action_result=None):
        """
        returns phantom.APP_SUCCESS if connection succeeded,
        else phantom.APP_ERROR.

        If an action_result is passed in, method will
        appropriately use it. Otherwise just return
        APP_SUCCESS/APP_ERROR
        """
        if self._ldap_connection and \
                self._ldap_connection.bound and \
                not self._ldap_connection.closed:
            return True
        elif self._ldap_connection is not None:
            self._ldap_connection.unbind()

        try:
            server_param = {
                "use_ssl": self._ssl,
                "port": self._ssl_port,
                "host": self._server,
                "get_info": ldap3.ALL
            }

            self._ldap_server = ldap3.Server(**server_param)
            self.save_progress("configured server {}...".format(self._server))
            self._ldap_connection = ldap3.Connection(self._ldap_server,
                                                     user=self._username,
                                                     password=self._password,
                                                     raise_exceptions=True)
            self.save_progress("binding to directory...")

            if not self._ldap_connection.bind():
                if action_result:
                    return action_result.set_status(
                        phantom.APP_ERROR,
                        self._ldap_connection.result['description'])
                else:
                    return phantom.APP_ERROR

            if action_result:
                return action_result.set_status(phantom.APP_SUCCESS)
            else:
                return phantom.APP_SUCCESS

        except Exception as e:
            self.debug_print("[DEBUG] ldap_bind, e = {}".format(e))
            if action_result:
                return action_result.set_status(phantom.APP_ERROR,
                                                status_message="",
                                                exception=e)
            else:
                return phantom.APP_ERROR
Ejemplo n.º 17
0
 def __init__(self, cfg):
     self.sleeper = cfg['LDAP_THROTTLE']
     self.server_addr = cfg['LDAP_SERVER']
     self.user = cfg['LDAP_USER']
     self.passw = cfg['LDAP_PASSWORD']
     self.user_grp = cfg['LDAP_USERGROUP']
     self.server = ldap3.Server(self.server_addr)
     self.conn = ldap3.Connection(
         self.server,
         'cn={0},ou={1},dc=brown,dc=edu'.format(
             self.user, self.user_grp),
         self.passw, auto_bind=True)
Ejemplo n.º 18
0
def authenticate(address, username, password):
    try:
        if len(password) == 0:
            password = "******"

        server = ldap3.Server("ldap://192.168.4.222")
        conn = ldap3.Connection(server)

        # conn.search()

    except Exception:
        raise "Wrong username or password"
Ejemplo n.º 19
0
 def __init__(self):
     self.server_pool = ldap3.ServerPool(
         servers=[ldap3.Server(s, use_ssl=AD_USE_TLS) for s in SERVER_LIST],
         pool_strategy=ldap3.POOLING_STRATEGY_FIRST,
         active=True)
     self.connection = ldap3.Connection(
         self.server_pool,
         user=AD_USER,
         password=AD_PASSWD,
         auto_bind=ldap3.AUTO_BIND_NO_TLS
     )  # use_ssl=True above makes it use TLS, so we don't have to use the StartTLS command in the connection.
     self.connection.raise_exceptions = True
Ejemplo n.º 20
0
 def __init__(self, app):
     self.app = app
     self.host = app.config['LDAP_HOST']
     self.bind = app.config['LDAP_BIND']
     self.password = app.config['LDAP_PASSWORD']
     tls = ldap3.Tls(validate=ssl.CERT_REQUIRED)
     server = ldap3.Server(self.host,
                           port=636,
                           use_ssl=True,
                           get_info=ldap3.ALL,
                           tls=tls)
     self.server = server
Ejemplo n.º 21
0
    def __init__(self, hostname, port, timeout, ssl=False):
        self.hostname = hostname
        self.port = port
        self.timeout = timeout
        self.ssl = ssl

        self.server = ldap3.Server(self.hostname,
                                   port=self.port,
                                   get_info=ldap3.ALL,
                                   connect_timeout=self.timeout,
                                   use_ssl=self.ssl)
        self.conn = None
Ejemplo n.º 22
0
 def __connect(self):
     if not self.__conn:
         s = ldap3.Server(self.SERVER,
                          port=636,
                          use_ssl=True,
                          get_info=ldap3.ALL)
         self.__conn = ldap3.Connection(s,
                                        auto_bind=True,
                                        user=self.USERNAME,
                                        password=self.PASSWORD,
                                        client_strategy=ldap3.SYNC,
                                        authentication=ldap3.SIMPLE)
Ejemplo n.º 23
0
Archivo: utils.py Proyecto: epfl-si/amm
def _get_LDAP_connection():
    """
    Return a LDAP connection
    """
    ldap_server = base.get_config('LDAP_SERVER_FOR_SEARCH')
    ldap_base = base.get_config('LDAP_BASE_DN')

    server = ldap3.Server('ldap://' + ldap_server)
    connection = ldap3.Connection(server)
    connection.open()

    return connection, ldap_base
Ejemplo n.º 24
0
    def bind(self, use_ssl=True, force=False):

        setattr(base.current_app, self.__class__.__name__, self)

        base.logIt("Bind to database")

        if Config.mappingLocations['default'] == 'ldap':
            self.moddb = BackendTypes.LDAP
        elif Config.mappingLocations['default'] == 'rdbm':
            self.read_jans_schema()
            if Config.rdbm_type == 'mysql':
                self.moddb = BackendTypes.MYSQL
            elif Config.rdbm_type == 'pgsql':
                self.moddb = BackendTypes.PGSQL
            elif Config.rdbm_type == 'spanner':
                self.moddb = BackendTypes.SPANNER
                self.spanner = Spanner()
        else:
            self.moddb = BackendTypes.COUCHBASE

        if not hasattr(self, 'ldap_conn') or force:
            for group in Config.mappingLocations:
                if Config.mappingLocations[group] == 'ldap':
                    base.logIt("Making LDAP Conncetion")
                    ldap_server = ldap3.Server(Config.ldap_hostname,
                                               port=int(Config.ldaps_port),
                                               use_ssl=use_ssl)
                    self.ldap_conn = ldap3.Connection(
                        ldap_server,
                        user=Config.ldap_binddn,
                        password=Config.ldapPass,
                    )
                    base.logIt(
                        "Making LDAP Connection to host {}:{} with user {}".
                        format(Config.ldap_hostname, Config.ldaps_port,
                               Config.ldap_binddn))
                    self.ldap_conn.bind()
                    break

        if not self.session or force:
            for group in Config.mappingLocations:
                if Config.mappingLocations[group] == 'rdbm':
                    if Config.rdbm_type in ('mysql', 'pgsql'):
                        base.logIt("Making MySql Conncetion")
                        result = self.mysqlconnection()
                        if not result[0]:
                            print("{}FATAL: {}{}".format(
                                colors.FAIL, result[1], colors.ENDC))
                        break

        self.set_cbm()
        self.default_bucket = Config.couchbase_bucket_prefix
Ejemplo n.º 25
0
    def authenticate(self, handler, data):
        username = data['username']
        password = data['password']

        # Protect against invalid usernames as well as LDAP injection attacks
        if not re.match(self.valid_username_regex, username):
            self.log.warn('Invalid username')
            return None

        # No empty passwords!
        if password is None or password.strip() == '':
            self.log.warn('Empty password')
            return None

        userdn = self.bind_dn_template.format(username=username)

        server = ldap3.Server(self.server_address,
                              port=self.server_port,
                              use_ssl=self.use_ssl)
        conn = ldap3.Connection(server, user=userdn, password=password)

        if conn.bind():
            if self.allowed_groups:
                if self.lookup_dn:
                    # In some cases, like AD, we don't bind with the DN, and need to discover it.
                    conn.search(search_base=self.user_search_base,
                                search_scope=ldap3.SUBTREE,
                                search_filter='({userattr}={username})'.format(
                                    userattr=self.user_attribute,
                                    username=username),
                                attributes=[self.user_attribute])

                    if len(conn.response) == 0:
                        self.log.warn(
                            'User with {userattr}={username} not found in directory'
                            .format(userattr=self.user_attribute,
                                    username=username))
                        return None
                    userdn = conn.response[0]['dn']

                for group in self.allowed_groups:
                    if conn.search(group,
                                   search_scope=ldap3.BASE,
                                   search_filter='(member={userdn})'.format(
                                       userdn=userdn),
                                   attributes=['member']):
                        return username
            else:
                return username
        else:
            self.log.warn('Invalid password')
            return None
Ejemplo n.º 26
0
    def test_init(self):
        """Tests init logic."""
        admin_obj = admin.Admin(None, 'dc=test,dc=com')
        admin_obj.ldap = ldap3.Connection(ldap3.Server('fake'),
                                          client_strategy=ldap3.MOCK_SYNC)

        admin_obj.init()

        dn_list = [arg[0][0] for arg in admin_obj.ldap.add.call_args_list]

        self.assertTrue('dc=test,dc=com' in dn_list)
        self.assertTrue('ou=treadmill,dc=test,dc=com' in dn_list)
        self.assertTrue('ou=apps,ou=treadmill,dc=test,dc=com' in dn_list)
Ejemplo n.º 27
0
 def connection(self):  # pragma: no cover
     """Establish LDAP connection."""
     # self.server allows us to fetch server info
     # (including LDAP schema list) if we wish to
     # add this feature later
     self.server = ldap3.Server(self.host, port=self.port, get_info=ldap3.ALL)
     self.conn = ldap3.Connection(
         self.server,
         user=self.user_dn,
         password=self.user_pw,
         auto_bind=True,
         lazy=True,
         receive_timeout=1)
Ejemplo n.º 28
0
def poc(arg):
    check_port = lambda x: x if re.match(r"(.*?):(\d+)$", x) else x + ':389'
    host, port = check_port(arg).split(':')
    timeout = 5
    try:
        server = ldap3.Server(host,
                              get_info=ldap3.ALL,
                              connect_timeout=timeout)
        conn = ldap3.Connection(server, auto_bind=True)
        if len(server.info.naming_contexts) > 0:
            return True
    except Exception:
        return
Ejemplo n.º 29
0
def auth(username, password):
    conf = conf_path()
    LDAP_SERVER = conf.ladp_server
    LDAP_DOMAIN = conf.ladp_domain
    c = ldap3.Connection(ldap3.Server(LDAP_SERVER, get_info=ldap3.ALL),
                         user=username + '@' + LDAP_DOMAIN,
                         password=password)
    ret = c.bind()
    if ret:
        c.unbind()
        return True
    else:
        return False
Ejemplo n.º 30
0
def connect_gssapi(host):
    serv = ldap3.Server(host,
                        tls=ldap3.Tls(validate=ssl.CERT_REQUIRED),
                        get_info="DSA")
    conn = ldap3.Connection(serv,
                            authentication="SASL",
                            sasl_mechanism="GSSAPI")
    conn.open()
    if not conn.start_tls():
        raise Exception("start_tls failed", conn.result)
    if not conn.bind():
        raise Exception("bind failed", conn.result)
    return conn