ldap4net

repository·master·Indexed 42 days ago

https://github.com/flamencist/ldap4net

A cross-platform .NET Core port of the OpenLDAP client library and Windows LDAP API. It enables interaction with LDAP-compatible directory servers, including Microsoft Active Directory, across Windows, Linux, OSX, and FreeBSD. Supports .NET Standard 2.0+ runtimes and features TLS/SSL, SASL authentication (GSSAPI/Kerberos, Negotiate, DIGEST-MD5), and LDAP V3 controls such as Paging, Directory Sync, and Virtual List View.

Tokens
2.9K
Snippets
11
Records
13
Agent score
3%

What's inside ldap4net

  1. Overview of ldap4net features and supported platforms

    master

    Supported Platforms

    • Most popular Linux distributions
    • FreeBSD
    • OSX
    • Windows
    • Compatible with .NET Standard 2.0+ runtimes (including .NET Core, Mono, and .NET Framework).

    Key Features

    • Security: Supports TLS/SSL.
    • Data Types: Supports Unicode and Binary values.
    • Authentication:
      • Simple, Basic, and Anonymous.
      • SASL: GSSAPI (Kerberos V5), Negotiate, DIGEST-MD5, and EXTERNAL.
      • SASL proxy authorization.
    • LDAP V3 Controls: Supports Paging (PageResultRequestControl), Directory Sync (DirSyncRequestControl), Sorting (SortRequestControl), Async Search (AsqRequestControl), Directory Notification, and Virtual List View (VlvRequestControl).
  2. Use LDAP V3 Controls

    master

    ldap4net supports several LDAP V3 controls to extend search functionality:

    • PageResultRequestControl: Implements simple paged results for large datasets.
    • DirSyncRequestControl: Enables directory synchronization (requires DS-Replication-Get-Changes rights).
    • SortRequestControl: Enables server-side sorting.
    • AsqRequestControl: Used to retrieve group members.
    • DirectoryNotificationControl: Provides real-time notifications from the server.
    • VlvRequestControl: Implements Virtual List View for efficient large result set navigation.
    var directoryRequest = new SearchRequest("dc=example,dc=com", "(objectclass=top)", LdapSearchScope.LDAP_SCOPE_SUB);
    var resultRequestControl = new PageResultRequestControl(3); // Page size of 3
    directoryRequest.Controls.Add(resultRequestControl);
    
    var response = (SearchResponse)cn.SendRequest(directoryRequest);
    // ... iterate using response.Controls and the Cookie ...
  3. Configure ldap4net for Linux and OSX

    master

    When running on Linux or OSX, ldap4net relies on the OpenLDAP client libraries. You must ensure the following:

    1. Install the latest OpenLDAP client libraries from openldap.org.
    2. For Linux, ensure that the appropriate symlinks for libldap.so.2 and liblber.so.2 exist in your library path.
  4. Install ldap4net via NuGet or dotnet CLI

    master

    You can install ldap4net using the standard NuGet package manager or the .NET CLI.

    NuGet Package Manager:

    Install-Package LdapForNet

    dotnet CLI:

    dotnet add package LdapForNet
    dotnet add package LdapForNet
  5. Use Kerberos authentication with LdapConnection

    master

    To perform LDAP operations using Kerberos authentication (supported via SASL GSSAPI on Linux/OSX), use the LdapConnection class to connect and bind using the system's credential cache.

    using (var cn = new LdapConnection())
    {
    	// connect
    	cn.Connect();
    	// bind using kerberos credential cache file
    	cn.Bind();
    	// call ldap op
    	var entries = cn.Search("<<basedn>>", "(objectClass=*)");
    }
    using (var cn = new LdapConnection())
    {
    	// connect
    	cn.Connect();
    	// bind using kerberos credential cache file
    	cn.Bind();
    	// call ldap op
    	var entries = cn.Search("<<basedn>>", "(objectClass=*)");
    }
  6. Perform low-level LDAP requests with SendRequest

    master

    For advanced operations not covered by high-level methods, use SendRequest() or SendRequestAsync(). This allows you to send any LdapRequest (like SearchRequest, AddRequest, ModifyRequest, DeleteRequest, or ExtendedRequest) and receive the corresponding response.

    var res = await cn.SendRequestAsync(new ExtendedRequest("1.3.6.1.4.1.4203.1.11.3"), cancellationToken.Token);
    var extendedResponse = (ExtendedResponse)res;
    var name = Encoding.UTF8.GetString(extendedResponse.ResponseValue);
  7. Add, Modify, and Delete LDAP entries

    master

    Manage directory entries using the following methods:

    • Add(LdapEntry): Creates a new entry. Supports binary values via DirectoryAttribute.
    • Modify(LdapModifyEntry): Updates an existing entry. Supports operations like LDAP_MOD_REPLACE, LDAP_MOD_ADD, and LDAP_MOD_DELETE.
    • Delete(dn): Removes an entry.
    • Rename(dn, newDn, ...): Renames an entry.

    All these methods have Async counterparts (e.g., AddAsync, ModifyAsync, DeleteAsync, RenameAsync).

    cn.Add(new LdapEntry
    {
        Dn = "cn=test,dc=example,dc=com",
        Attributes = new Dictionary<string, List<string>>
        {
            {"sn", new List<string> {"Winston"}},
            {"objectclass", new List<string> {"inetOrgPerson"}}
        }
    });
    
    // Modify an entry
    cn.Modify(new LdapModifyEntry
    {
        Dn = "cn=test,dc=example,dc=com",
        Attributes = new List<LdapModifyAttribute>
        {
            new LdapModifyAttribute { LdapModOperation = LdapModOperation.LDAP_MOD_REPLACE, Type = "givenName", Values = new List<string> {"new_name"} }
        }
    });
  8. Bind to an LDAP server (Authentication)

    master

    Use Bind() or BindAsync() to authenticate. Supported mechanisms include:

    • Kerberos: Call Bind() without arguments to use the Kerberos credential cache.
    • Simple: Use Bind(LdapAuthMechanism.SIMPLE, "userdn", "password").
    • Anonymous: Use Bind(LdapAuthType.Anonymous, new LdapCredential()).
    • Digest-MD5: Use Bind(LdapAuthType.Digest, new LdapCredential { UserName = "...", Password = "..." }).
    • SASL External (Client Certificate): Use SetClientCertificate(cert) followed by Bind(LdapAuthType.External, ...).
    • SASL External (Active Directory): Use Bind(LdapAuthType.ExternalAd, ...).
    • SASL Proxy (UNIX): Use Bind(LdapAuthType.Digest, ...) or Bind(LdapAuthType.GssApi, ...) with an AuthorizationId.
    • Negotiate (Windows): Use Bind(LdapAuthType.Negotiate, ...).
    cn.Bind(LdapAuthMechanism.SIMPLE, "cn=read-only-admin,dc=example,dc=com", "password");
    
    // Digest-MD5 Bind
    cn.Bind(LdapAuthType.Digest, new LdapCredential
    {
        UserName = "username",
        Password = "clearTextPassword"
    });
    
    // SASL External with Client Certificate
    var cert = new X509Certificate2("yourcert.pfx", "password");
    cn.SetClientCertificate(cert);
    cn.Bind(LdapAuthType.External, new LdapCredential());
  9. Get and Set LDAP options

    master

    Use GetOption<T>(LdapOption) and SetOption(LdapOption, ref T) to manage LDAP protocol settings like LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_HOST_NAME, or LDAP_OPT_REFERRALS.

    var ldapVersion = cn.GetOption<int>(LdapOption.LDAP_OPT_PROTOCOL_VERSION);
    
    // Set protocol version
    var version = (int)LdapVersion.LDAP_VERSION3;
    cn.SetOption(LdapOption.LDAP_OPT_PROTOCOL_VERSION, ref version);
  10. Set connection timeout

    master

    Set the Timeout property on the LdapConnection instance using a TimeSpan to control how long the connection attempt or operation should wait.

    using (var cn = new LdapConnection())
    {
    	cn.Timeout = new TimeSpan(0, 1, 0); // 1 minute
    }
  11. Search for LDAP entries

    master

    Perform searches using Search() or SearchAsync(). You can specify a base DN, a filter, and a LdapSearchScope (e.g., LdapSearchScope.LDAP_SCOPE_SUBTREE or LdapSearchScope.LDAP_SCOPE_ONELEVEL).

    Specialized search methods include:

    • SearchByCn(baseDn, cn, scope): Search by Common Name.
    • SearchBySid(baseDn, sid, scope): Search by Security Identifier.
    var entries = cn.Search("dc=example,dc=com", "(objectClass=*)");
    
    // Search with specific scope
    var entries = cn.Search("dc=example,dc=com", "(objectClass=*)", LdapSearchScope.LDAP_SCOPE_ONELEVEL);
    
    // Async search
    var entries = cn.SearchAsync("dc=example,dc=com", "(objectClass=*)").Result;
  12. Configure TLS and SSL connections

    master

    For secure connections, you can use StartTransportLayerSecurity for TLS or specify LdapSchema.LDAPS for SSL. If working with self-signed certificates in a development environment, use TrustAllCertificates() or set the TLS parameter to true.

    using (var cn = new LdapConnection())
    {
    	cn.Connect("dc.example.com", 389);
    	cn.StartTransportLayerSecurity(true); 
    }
    
    // Connect with SSL (LDAPS) and trust all certificates
    using (var LdapConnection cn = new LdapConnection())
    {
    	cn.Connect("dc.example.com", 636, LdapSchema.LDAPS);
    	cn.TrustAllCertificates();
    }