SURFscz / SRAM-deploy

Deploy scripts for the SCZ
Apache License 2.0
5 stars 5 forks source link

restrict ldap session length #551

Open baszoetekouw opened 1 week ago

baszoetekouw commented 1 week ago

Currently, the session length for an ldap connection seem pretty long (at least > 2 hours). This is problematic, because the session keeps being active, even if the bind password has been reset after the session has started.

So, we want to terminate ldap connections after 15 minutes or so. However, I can't find an option to do that.

Script to test this:

import time
from datetime import datetime
from ldap3 import Server, Connection, ALL, Tls

# Configuration
LDAP_SERVER = 'ldaps://ldap.test.sram.surf.nl'  # Replace with your LDAP server address
LDAP_PORT = 636  # Default port for LDAPS
LDAP_USER = 'cn=admin,dc=123,dc=services,dc=sram-tst,dc=surf,dc=nl'  # Replace with your LDAP bind DN
LDAP_PASSWORD = 'the_password'
SEARCH_BASE = 'dc=123,dc=services,dc=sram-tst,dc=surf,dc=nl'  # Base DN for the search
SEARCH_FILTER = '(objectClass=person)'  # Adjust filter as needed
SEARCH_ATTRIBUTES = ['uid', 'mail']  # Attributes to retrieve

# TLS configuration (optional)
tls_config = Tls()

try:
    # Initialize server and connection
    server = Server(LDAP_SERVER, port=LDAP_PORT, use_ssl=True, get_info=ALL, tls=tls_config)
    conn = Connection(server, user=LDAP_USER, password=LDAP_PASSWORD, auto_bind=True)

    print("Connected to the LDAP server successfully.")

    # Keep the session open and run queries periodically
    i=0
    while i:=i+1:
        conn.search(search_base=SEARCH_BASE,
                    search_filter=SEARCH_FILTER,
                    attributes=SEARCH_ATTRIBUTES)

        print(f"{i: 4d} {datetime.now()}  Search results ({len(conn.entries)} entries found)")

        # Wait for 10 seconds before the next query
        time.sleep(60)

except Exception as e:
    print(f"An error occurred: {e}")

finally:
    if 'conn' in locals() and conn.bound:
        conn.unbind()
        print("LDAP connection closed.")