# Catatan Seekor: LDAP

> **"LDAP is the foundation of enterprise directory services and identity management"**

## 📚 Overview

Lightweight Directory Access Protocol (LDAP) adalah protokol standar untuk mengakses dan mengelola directory services. LDAP banyak digunakan untuk enterprise authentication, user management, dan centralized identity storage.

## 🎯 Learning Objectives

Setelah mempelajari materi ini, Anda akan mampu:

* Memahami konsep dasar LDAP dan directory services
* Menerapkan LDAP untuk authentication dan authorization
* Mengkonfigurasi LDAP server dan client
* Mengintegrasikan LDAP dengan aplikasi

## 📖 Table of Contents

* [LDAP Fundamentals](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/fundamentals.md)
* [Active Directory](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/active-directory.md)
* [LDAP Schema](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/schema.md)
* [LDAP Security](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/security.md)
* [Integration Examples](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/integration.md)

## 🔐 LDAP Concepts

### 1. **What is LDAP?**

* **Lightweight Directory Access Protocol**
* Standard protocol untuk directory services
* Hierarchical data structure
* Optimized untuk read operations
* Widely used in enterprise environments

### 2. **LDAP Components**

* **Directory Information Tree (DIT)**: Hierarchical structure
* **Entries**: Individual records dalam directory
* **Attributes**: Data fields dalam entries
* **Object Classes**: Templates untuk entries
* **Schema**: Rules dan constraints

### 3. **LDAP Operations**

* **Bind**: Authentication
* **Search**: Query directory data
* **Add**: Create new entries
* **Modify**: Update existing entries
* **Delete**: Remove entries

## 📋 LDAP Schema & Attributes

### **Common Attributes**

| Attribute   | Description         | Example                |
| ----------- | ------------------- | ---------------------- |
| `uid`       | User ID             | `john.doe`             |
| `cn`        | Common Name         | `John Doe`             |
| `sn`        | Surname/Last Name   | `Doe`                  |
| `givenName` | First Name          | `John`                 |
| `mail`      | Email Address       | `john.doe@company.com` |
| `l`         | Location/City       | `Jakarta`              |
| `st`        | State/Province      | `DKI Jakarta`          |
| `c`         | Country             | `ID`                   |
| `ou`        | Organizational Unit | `IT Department`        |
| `o`         | Organization        | `Company Name`         |
| `dc`        | Domain Component    | `company.com`          |

### **Object Classes**

* **top**: Base class untuk semua entries
* **person**: Basic person information
* **organizationalPerson**: Employee information
* **inetOrgPerson**: Internet person information
* **groupOfNames**: Group membership
* **organizationalUnit**: Department/division

## 🚀 Quick Start

### 🔰 **Untuk Pemula**

1. Mulai dengan [LDAP Fundamentals](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/fundamentals.md)
2. Pelajari [LDAP Schema](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/schema.md)
3. Pahami [LDAP Security](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/security.md)

### 🎯 **Untuk Developer**

1. Implementasi [Integration Examples](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/integration.md)
2. Pelajari [Active Directory](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/active-directory.md)
3. Kuasai [LDAP Security](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/security.md)

## 📚 Referensi & Resources

### 🌟 **Essential Reading**

* [LDAP RFC 4511](https://tools.ietf.org/html/rfc4511) - LDAP protocol specification
* [Microsoft Active Directory](https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/get-started/virtual-dc/active-directory-domain-services-overview)
* [OpenLDAP Documentation](https://www.openldap.org/doc/)
* [Apache Directory](https://directory.apache.org/) - LDAP server implementation

### 📖 **Books**

* **"Understanding LDAP"** by Heinz Johner
* **"LDAP System Administration"** by Gerald Carter
* **"Active Directory"** by Brian Desmond
* **"LDAP Programming"** by Tim Howes

### 🎓 **Online Courses**

* [Microsoft Learn: Active Directory](https://docs.microsoft.com/en-us/learn/paths/identity-fundamentals/)
* [Coursera: Identity Management](https://www.coursera.org/learn/identity-management)
* [edX: Directory Services](https://www.edx.org/learn/directory-services)

### 🛠️ **Tools & Frameworks**

* [OpenLDAP](https://www.openldap.org/) - Open source LDAP server
* [Apache Directory Studio](https://directory.apache.org/studio/) - LDAP client
* [JXplorer](http://jxplorer.org/) - Cross-platform LDAP browser
* [LDAP Admin](http://www.ldapadmin.org/) - LDAP administration tool

### 🔗 **Communities & Forums**

* [OpenLDAP Community](https://www.openldap.org/community/)
* [Microsoft Active Directory Forum](https://social.technet.microsoft.com/Forums/en-US/home?forum=winserverDS)
* [Stack Overflow LDAP](https://stackoverflow.com/questions/tagged/ldap)
* [Reddit r/sysadmin](https://www.reddit.com/r/sysadmin/)

## 🎯 Best Practices

### 🔐 **LDAP Security**

* ✅ Use LDAPS (LDAP over SSL/TLS)
* ✅ Implement strong authentication
* ✅ Use connection pooling
* ✅ Implement access controls
* ✅ Regular security audits

### 🏗️ **LDAP Design**

* ✅ Plan directory structure carefully
* ✅ Use meaningful naming conventions
* ✅ Implement proper indexing
* ✅ Consider scalability
* ✅ Document schema design

### 🔒 **Authentication & Authorization**

* ✅ Secure bind operations
* ✅ Implement password policies
* ✅ Use service accounts appropriately
* ✅ Monitor access logs
* ✅ Regular account reviews

## 🚨 Security Checklist

### 🔍 **Pre-Implementation**

* [ ] LDAP requirements defined
* [ ] Directory structure planned
* [ ] Security policies established
* [ ] Schema design completed

### 🛠️ **During Implementation**

* [ ] LDAP server configured
* [ ] Security settings applied
* [ ] Schema implemented
* [ ] Authentication configured
* [ ] Access controls set

### 🧪 **Testing & Deployment**

* [ ] Security testing completed
* [ ] Performance testing done
* [ ] User acceptance testing
* [ ] Security audit
* [ ] Documentation completed

### 📊 **Maintenance**

* [ ] Regular backups
* [ ] Security updates
* [ ] Performance monitoring
* [ ] User training
* [ ] Regular reviews

## 🔍 Common Vulnerabilities

### 🚨 **LDAP Injection**

* Unvalidated user input
* Malicious LDAP queries
* Information disclosure
* Unauthorized access

### 🔓 **Authentication Issues**

* Weak passwords
* Plain text authentication
* Brute force attacks
* Account lockout bypass

### 🚫 **Configuration Errors**

* Insecure default settings
* Missing access controls
* Weak encryption
* Misconfigured permissions

## 🛡️ Security Controls

### 🔒 **Preventive Controls**

* Input validation
* Strong authentication
* Access controls
* Encryption
* Secure configuration

### 🔍 **Detective Controls**

* Access logging
* Security monitoring
* Intrusion detection
* Regular audits
* Performance monitoring

### 🚨 **Corrective Controls**

* Incident response
* Account management
* Security updates
* User training
* Continuous improvement

## 📊 Implementation Examples

### 🔐 **LDAP Authentication (Python)**

```python
import ldap3
from ldap3 import Server, Connection, ALL, NTLM

def ldap_authenticate(username, password, ldap_server, ldap_domain):
    try:
        # LDAP server connection
        server = Server(ldap_server, get_info=ALL)
        
        # User DN format
        user_dn = f"{username}@{ldap_domain}"
        
        # Attempt connection
        conn = Connection(server, user=user_dn, password=password, authentication=NTLM)
        
        if conn.bind():
            # Authentication successful
            print(f"User {username} authenticated successfully")
            
            # Search for user information
            search_filter = f"(sAMAccountName={username})"
            conn.search('DC=company,DC=com', search_filter, attributes=['cn', 'mail', 'memberOf'])
            
            if conn.entries:
                user_info = conn.entries[0]
                return {
                    'authenticated': True,
                    'cn': user_info.cn.value,
                    'email': user_info.mail.value,
                    'groups': [group.split(',')[0].split('=')[1] for group in user_info.memberOf.values]
                }
        else:
            print(f"Authentication failed for user {username}")
            return {'authenticated': False, 'error': 'Invalid credentials'}
            
    except Exception as e:
        print(f"LDAP error: {str(e)}")
        return {'authenticated': False, 'error': str(e)}
    finally:
        if 'conn' in locals():
            conn.unbind()

# Example usage
ldap_server = "ldap://dc.company.com"
ldap_domain = "company.com"
username = "john.doe"
password = "user_password"

result = ldap_authenticate(username, password, ldap_server, ldap_domain)
print(result)
```

### 🔑 **LDAP Search (Node.js)**

```javascript
const ldap = require('ldapjs');

function searchUsers(searchBase, filter, attributes) {
    return new Promise((resolve, reject) => {
        const client = ldap.createClient({
            url: 'ldap://ldap.company.com:389'
        });

        client.bind('cn=admin,dc=company,dc=com', 'admin_password', (err) => {
            if (err) {
                reject(err);
                return;
            }

            const searchOptions = {
                scope: 'sub',
                filter: filter || '(objectClass=person)',
                attributes: attributes || ['cn', 'mail', 'uid']
            };

            client.search(searchBase, searchOptions, (err, res) => {
                if (err) {
                    reject(err);
                    return;
                }

                const users = [];

                res.on('searchEntry', (entry) => {
                    users.push(entry.object);
                });

                res.on('error', (err) => {
                    reject(err);
                });

                res.on('end', () => {
                    client.unbind();
                    resolve(users);
                });
            });
        });
    });
}

// Example usage
searchUsers('dc=company,dc=com', '(cn=*John*)', ['cn', 'mail', 'uid'])
    .then(users => {
        console.log('Found users:', users);
    })
    .catch(err => {
        console.error('Search error:', err);
    });
```

### 🔒 **LDAP Connection (Java)**

```java
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.*;
import java.util.Hashtable;

public class LDAPClient {
    
    private DirContext context;
    
    public LDAPClient(String url, String username, String password) throws Exception {
        Hashtable<String, String> env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
        
        context = new InitialDirContext(env);
    }
    
    public boolean authenticateUser(String userDN, String password) {
        try {
            DirContext userContext = new InitialDirContext();
            userContext.addToEnvironment(Context.PROVIDER_URL, context.getEnvironment().get(Context.PROVIDER_URL));
            userContext.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
            userContext.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            userContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            
            userContext.getAttributes("");
            userContext.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    public void searchUsers(String searchBase, String filter) throws Exception {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setReturningAttributes(new String[]{"cn", "mail", "uid"});
        
        NamingEnumeration<SearchResult> results = context.search(searchBase, filter, searchControls);
        
        while (results.hasMore()) {
            SearchResult result = results.next();
            Attributes attrs = result.getAttributes();
            
            System.out.println("User: " + attrs.get("cn").get());
            System.out.println("Email: " + attrs.get("mail").get());
            System.out.println("UID: " + attrs.get("uid").get());
            System.out.println("---");
        }
    }
    
    public void close() throws Exception {
        if (context != null) {
            context.close();
        }
    }
    
    public static void main(String[] args) {
        try {
            LDAPClient client = new LDAPClient(
                "ldap://ldap.company.com:389",
                "cn=admin,dc=company,dc=com",
                "admin_password"
            );
            
            // Search for users
            client.searchUsers("dc=company,dc=com", "(objectClass=person)");
            
            // Authenticate user
            boolean authenticated = client.authenticateUser(
                "cn=john.doe,ou=users,dc=company,dc=com",
                "user_password"
            );
            
            System.out.println("Authentication: " + authenticated);
            
            client.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

## 🚀 Advanced Topics

### 🔐 **LDAP Security Features**

* SASL authentication
* GSSAPI/Kerberos
* Certificate-based authentication
* Access control lists (ACLs)
* Audit logging

### 🌐 **LDAP Integration Patterns**

* Web application authentication
* API authentication
* Desktop application SSO
* Mobile app authentication
* Cloud service integration

### 🔒 **High Availability**

* LDAP replication
* Load balancing
* Failover configuration
* Backup and recovery
* Disaster recovery

## 🤝 Contributing

Kontribusi untuk memperbaiki dan menambahkan konten LDAP sangat dihargai! Silakan:

1. Fork repository ini
2. Buat branch untuk fitur baru
3. Commit perubahan Anda
4. Push ke branch
5. Buat Pull Request

## 📄 License

Konten ini tersedia di bawah [MIT License](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/security/catatan-seekor-ldap/LICENSE/README.md).

## 🙏 Acknowledgments

* OpenLDAP Foundation
* Microsoft Active Directory team
* LDAP community developers
* Directory services practitioners

***

**⚠️ Disclaimer**: Catatan ini dibuat untuk tujuan pembelajaran. Selalu test LDAP configuration di environment yang aman dan konsultasikan dengan experts untuk implementasi production.

**📁 Remember**: LDAP is the backbone of enterprise identity management. Configure it securely!
