๐Ÿ”’ Security

LDAP

Lightweight Directory Access Protocol

A protocol for accessing directory services, widely used for centralized user management in enterprise environments, including user authentication, organizational structure management, and authorization.

๐Ÿ“– Detailed Explanation

LDAP (Lightweight Directory Access Protocol) is a TCP/IP-based directory service access protocol. A simplified version of the X.500 standard, it is optimized for read operations and is widely used for user authentication, organizational information lookup, and storing application settings. The default ports are 389 (LDAP) and 636 (LDAPS - SSL/TLS).

LDAP directories store data in a tree structure (DIT, Directory Information Tree). From the top down, they are composed of elements such as DC (Domain Component), OU (Organizational Unit), and CN (Common Name). For example, cn=ํ™๊ธธ๋™,ou=engineering,dc=example,dc=com represents the user ํ™๊ธธ๋™ belonging to the engineering department of the example.com domain.

Representative LDAP servers include Microsoft Active Directory (the de facto standard in Windows environments), OpenLDAP (open source), 389 Directory Server (Red Hat), and ApacheDS. In modern environments, cloud services such as AWS Directory Service and Azure AD also provide LDAP compatibility.

The typical LDAP authentication flow is: 1) the user enters a username/password, 2) the application sends a Bind request to the LDAP server, 3) the LDAP server responds with authentication success/failure, 4) if necessary, user attributes (groups, permissions, etc.) are looked up. In an SSO (Single Sign-On) environment, it may also be used together with Kerberos or SAML.

๐Ÿ’ป Code Example

LDAP integration with the Python ldap3 library

from ldap3 import Server, Connection, ALL, SUBTREE
from ldap3.core.exceptions import LDAPBindError, LDAPException
from typing import Optional, List, Dict

# LDAP ์„œ๋ฒ„ ์„ค์ •
LDAP_SERVER = "ldap://ldap.example.com:389"
LDAP_BASE_DN = "dc=example,dc=com"
LDAP_BIND_DN = "cn=admin,dc=example,dc=com"
LDAP_BIND_PASSWORD = "admin_password"


class LDAPClient:
    """LDAP ์—ฐ๋™ ํด๋ผ์ด์–ธํŠธ"""

    def __init__(self, server_url: str, base_dn: str):
        self.server = Server(server_url, get_info=ALL)
        self.base_dn = base_dn
        self.conn = None

    def bind_admin(self, bind_dn: str, password: str) -> bool:
        """๊ด€๋ฆฌ์ž ๊ณ„์ •์œผ๋กœ ๋ฐ”์ธ๋”ฉ"""
        try:
            self.conn = Connection(
                self.server,
                user=bind_dn,
                password=password,
                auto_bind=True
            )
            return True
        except LDAPBindError:
            return False

    def authenticate_user(self, username: str, password: str) -> Optional[dict]:
        """์‚ฌ์šฉ์ž ์ธ์ฆ (Bind ๋ฐฉ์‹)"""
        # 1. ๋จผ์ € ์‚ฌ์šฉ์ž DN ๊ฒ€์ƒ‰
        user_dn = self._find_user_dn(username)
        if not user_dn:
            return None

        # 2. ์‚ฌ์šฉ์ž ๊ณ„์ •์œผ๋กœ ์ง์ ‘ ๋ฐ”์ธ๋”ฉ ์‹œ๋„
        try:
            user_conn = Connection(
                self.server,
                user=user_dn,
                password=password,
                auto_bind=True
            )
            user_conn.unbind()

            # 3. ์ธ์ฆ ์„ฑ๊ณต ์‹œ ์‚ฌ์šฉ์ž ์ •๋ณด ๋ฐ˜ํ™˜
            return self.get_user_info(username)

        except LDAPBindError:
            return None  # ์ธ์ฆ ์‹คํŒจ

    def _find_user_dn(self, username: str) -> Optional[str]:
        """์‚ฌ์šฉ์ž DN ๊ฒ€์ƒ‰"""
        search_filter = f"(sAMAccountName={username})"  # AD ํ™˜๊ฒฝ
        # OpenLDAP์ธ ๊ฒฝ์šฐ: f"(uid={username})"

        self.conn.search(
            search_base=self.base_dn,
            search_filter=search_filter,
            search_scope=SUBTREE,
            attributes=['distinguishedName']
        )

        if self.conn.entries:
            return str(self.conn.entries[0].distinguishedName)
        return None

    def get_user_info(self, username: str) -> Optional[dict]:
        """์‚ฌ์šฉ์ž ์ƒ์„ธ ์ •๋ณด ์กฐํšŒ"""
        search_filter = f"(sAMAccountName={username})"

        self.conn.search(
            search_base=self.base_dn,
            search_filter=search_filter,
            search_scope=SUBTREE,
            attributes=[
                'cn', 'mail', 'displayName', 'department',
                'memberOf', 'telephoneNumber', 'title'
            ]
        )

        if not self.conn.entries:
            return None

        entry = self.conn.entries[0]
        return {
            'username': username,
            'dn': str(entry.entry_dn),
            'name': str(entry.cn) if entry.cn else None,
            'email': str(entry.mail) if entry.mail else None,
            'display_name': str(entry.displayName) if entry.displayName else None,
            'department': str(entry.department) if entry.department else None,
            'title': str(entry.title) if entry.title else None,
            'groups': [str(g) for g in entry.memberOf] if entry.memberOf else []
        }

    def get_user_groups(self, username: str) -> List[str]:
        """์‚ฌ์šฉ์ž๊ฐ€ ์†ํ•œ ๊ทธ๋ฃน ๋ชฉ๋ก ์กฐํšŒ"""
        user_info = self.get_user_info(username)
        if not user_info:
            return []

        # memberOf์—์„œ ๊ทธ๋ฃน CN๋งŒ ์ถ”์ถœ
        groups = []
        for group_dn in user_info.get('groups', []):
            # "CN=Developers,OU=Groups,DC=example,DC=com" -> "Developers"
            cn_part = group_dn.split(',')[0]
            if cn_part.startswith('CN='):
                groups.append(cn_part[3:])
        return groups

    def is_member_of(self, username: str, group_name: str) -> bool:
        """ํŠน์ • ๊ทธ๋ฃน ๋ฉค๋ฒ„์‹ญ ํ™•์ธ"""
        groups = self.get_user_groups(username)
        return group_name in groups

    def search_users(self, search_term: str, limit: int = 100) -> List[dict]:
        """์‚ฌ์šฉ์ž ๊ฒ€์ƒ‰"""
        search_filter = f"(&(objectClass=person)(|(cn=*{search_term}*)(mail=*{search_term}*)))"

        self.conn.search(
            search_base=self.base_dn,
            search_filter=search_filter,
            search_scope=SUBTREE,
            attributes=['cn', 'mail', 'sAMAccountName'],
            size_limit=limit
        )

        results = []
        for entry in self.conn.entries:
            results.append({
                'username': str(entry.sAMAccountName) if entry.sAMAccountName else None,
                'name': str(entry.cn) if entry.cn else None,
                'email': str(entry.mail) if entry.mail else None,
            })
        return results

    def close(self):
        """์—ฐ๊ฒฐ ์ข…๋ฃŒ"""
        if self.conn:
            self.conn.unbind()


# ์‚ฌ์šฉ ์˜ˆ์‹œ
if __name__ == "__main__":
    # LDAP ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™”
    ldap = LDAPClient(LDAP_SERVER, LDAP_BASE_DN)

    # ๊ด€๋ฆฌ์ž๋กœ ๋ฐ”์ธ๋”ฉ
    if ldap.bind_admin(LDAP_BIND_DN, LDAP_BIND_PASSWORD):
        print("๊ด€๋ฆฌ์ž ๋ฐ”์ธ๋”ฉ ์„ฑ๊ณต")

        # ์‚ฌ์šฉ์ž ์ธ์ฆ ํ…Œ์ŠคํŠธ
        user = ldap.authenticate_user("hong.gildong", "user_password")
        if user:
            print(f"์ธ์ฆ ์„ฑ๊ณต: {user['display_name']} ({user['email']})")
            print(f"์†Œ์† ๊ทธ๋ฃน: {ldap.get_user_groups('hong.gildong')}")

            # ๊ถŒํ•œ ํ™•์ธ
            if ldap.is_member_of("hong.gildong", "Administrators"):
                print("๊ด€๋ฆฌ์ž ๊ถŒํ•œ ์žˆ์Œ")
        else:
            print("์ธ์ฆ ์‹คํŒจ")

        # ์‚ฌ์šฉ์ž ๊ฒ€์ƒ‰
        users = ldap.search_users("๊ฐœ๋ฐœ")
        for u in users:
            print(f"๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ: {u['name']} - {u['email']}")

        ldap.close()

๐Ÿ—ฃ๏ธ How It's Said in Practice

Infrastructure Engineer "We got a request to set up authentication for a new internal system through AD integration. Should we configure it with LDAPS?"
Security Team "Yes, plaintext LDAP is not allowed; be sure to use LDAPS (port 636) or StartTLS. Create the service account with least privilege, and please store the binding account password in Vault."
Backend Developer "We also need group-based permission checks, so we have to query the memberOf attribute. With AD, we need to take nested groups into account too, right?"
Interviewer "Do you have experience implementing an authentication system using LDAP?"
Candidate "Yes, I have experience integrating Active Directory in an internal system. I first bound with a service account to search for the user's DN, then bound again with that DN and the user's password to authenticate. I assigned roles based on group membership and used LDAPS for encrypted communication. I also implemented a Connection Pool to improve performance."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer "User input is going directly into the LDAP search filter. There is an LDAP Injection vulnerability."
Author "You're right, I'll escape special characters with a function like escape_filter_chars(). Characters such as parentheses, asterisks, and backslashes are dangerous."

โš ๏ธ Cautions

  • Encryption required: With plaintext LDAP (port 389), passwords are exposed on the network. Be sure to use LDAPS (636) or StartTLS.
  • Preventing LDAP Injection: Do not put user input directly into search filters. Escape special characters (*, (, ), \, NUL) to prevent injection attacks.
  • Service account privileges: Grant the binding service account read-only permission, and remove permissions for changing passwords or creating users. Manage passwords securely.

๐Ÿ“š Learn More