├── .devcontainer ├── Dockerfile ├── devcontainer.json └── docker-compose.yml ├── .github ├── dependabot.yml └── workflows │ ├── codeql-analysis.yml │ ├── docker.yml │ ├── linter.yml │ └── tests.yml ├── .gitignore ├── CONTRIBUTING.md ├── Gatekeeper.LdapServerLibrary.Tests ├── Gatekeeper.LdapServerLibrary.Tests.csproj ├── Parser │ └── RdnParserTest.cs └── Session │ └── LdapEventsTest.cs ├── Gatekeeper.LdapServerLibrary ├── Engine │ ├── DecisionEngine.cs │ ├── Handler │ │ ├── BindRequestHandler.cs │ │ ├── ExtendedRequestHandler.cs │ │ ├── HandlerReply.cs │ │ ├── IRequestHandler.cs │ │ ├── SearchRequestHandler.cs │ │ └── UnbindRequestHandler.cs │ └── HandlerMapper.cs ├── Gatekeeper.LdapServerLibrary.csproj ├── ILogger.cs ├── LdapServer.cs ├── Models │ ├── LdapMessage.cs │ └── Operations │ │ ├── IProtocolOp.cs │ │ └── Response │ │ ├── BindResponse.cs │ │ ├── ExtendedOperationResponse.cs │ │ ├── LdapResult.cs │ │ ├── SearchResultDone.cs │ │ ├── SearchResultEntry.cs │ │ └── UnbindDummyResponse.cs ├── Network │ ├── ClientSession.cs │ ├── ConnectionManager.cs │ └── NetworkListener.cs ├── Parser │ ├── Encoder │ │ ├── BindResponseEncoder.cs │ │ ├── ExtendedOperationResponseEncoder.cs │ │ ├── IApplicationEncoder.cs │ │ ├── SearchResultDoneEncoder.cs │ │ └── SearchResultEntryEncoder.cs │ ├── OperationMapper.cs │ ├── PacketParser.cs │ └── RdnParser.cs ├── Session │ ├── ClientContext.cs │ ├── Events │ │ ├── AuthenticationEvent.cs │ │ ├── IAuthenticationEvent.cs │ │ ├── ISearchEvent.cs │ │ └── SearchEvent.cs │ ├── LdapEvents.cs │ └── Replies │ │ └── SearchResultReply.cs └── SingletonContainer.cs ├── LICENSE ├── README.md ├── Sample.Tests ├── Integration │ ├── LdapSearchTests.cs │ └── LdapServerFixture.cs └── Sample.Tests.csproj └── Sample ├── ConsoleLogger.cs ├── LdapEventListener.cs ├── Program.cs ├── README.md ├── Sample.csproj ├── SearchExpressionBuilder.cs ├── UserDatabase.cs └── example_certificate.pfx /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/dotnet/sdk:5.0 2 | 3 | LABEL org.opencontainers.image.source https://github.com/getgatekeeper/ldapserverlibrary 4 | 5 | RUN apt-get update 6 | RUN apt-get install -y ldap-utils netcat lsof zsh tcpdump vim 7 | RUN sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended 8 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "LdapServer", 3 | "dockerComposeFile": "docker-compose.yml", 4 | "service": "ldapserver", 5 | // Set *default* container specific settings.json values on container create. 6 | "settings": {}, 7 | "runArgs": [ 8 | "--privileged" 9 | ], 10 | // Add the IDs of extensions you want installed when the container is created. 11 | "extensions": [ 12 | "ms-dotnettools.csharp", 13 | "ms-dotnettools.dotnet-interactive-vscode", 14 | "ms-azuretools.vscode-docker" 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /.devcontainer/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | ldapserver: 4 | image: ghcr.io/getgatekeeper/ldapserver-dev:sha-583a956 5 | volumes: 6 | - .:/workspace:cached 7 | - /var/run/docker.sock:/var/run/docker-host.sock 8 | command: /bin/sh -c "while sleep 1000; do :; done" 9 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | - package-ecosystem: nuget 8 | directory: "/Gatekeeper.LdapServerLibrary.Tests" 9 | schedule: 10 | interval: daily 11 | open-pull-requests-limit: 10 12 | - package-ecosystem: nuget 13 | directory: "/Sample.Tests" 14 | schedule: 15 | interval: daily 16 | open-pull-requests-limit: 10 17 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # ******** NOTE ******** 12 | 13 | name: "CodeQL" 14 | 15 | on: 16 | push: 17 | branches: [ main ] 18 | pull_request: 19 | # The branches below must be a subset of the branches above 20 | branches: [ main ] 21 | schedule: 22 | - cron: '27 10 * * 6' 23 | 24 | jobs: 25 | analyze: 26 | name: Analyze 27 | runs-on: ubuntu-latest 28 | 29 | strategy: 30 | fail-fast: false 31 | matrix: 32 | language: [ 'csharp' ] 33 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 34 | # Learn more: 35 | # https://docs.github.com/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 36 | 37 | steps: 38 | - name: Checkout repository 39 | uses: actions/checkout@v2 40 | 41 | # Initializes the CodeQL tools for scanning. 42 | - name: Initialize CodeQL 43 | uses: github/codeql-action/init@v1 44 | with: 45 | languages: ${{ matrix.language }} 46 | # If you wish to specify custom queries, you can do so here or in a config file. 47 | # By default, queries listed here will override any specified in a config file. 48 | # Prefix the list here with "+" to use these queries and those in the config file. 49 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 50 | 51 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 52 | # If this step fails, then you should remove it and run the build manually (see below) 53 | # - name: Autobuild 54 | # uses: github/codeql-action/autobuild@v1 55 | 56 | # ℹ️ Command-line programs to run using the OS shell. 57 | # 📚 https://git.io/JvXDl 58 | 59 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 60 | # and modify them (or add more) to build your code if your project 61 | # uses a compiled language 62 | 63 | #- run: | 64 | # make bootstrap 65 | # make release 66 | 67 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 68 | # and modify them (or add more) to build your code if your project 69 | # uses a compiled language 70 | - name: Setup .NET 5.0.100 71 | uses: actions/setup-dotnet@v1 72 | with: 73 | dotnet-version: 5.0.100 74 | - name: Build 75 | run: dotnet build --configuration Release Gatekeeper.LdapServerLibrary/Gatekeeper.LdapServerLibrary.csproj 76 | 77 | - name: Perform CodeQL Analysis 78 | uses: github/codeql-action/analyze@v1 79 | -------------------------------------------------------------------------------- /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | name: Publish Docker images 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - '.devcontainer/Dockerfile' 9 | - '.github/workflows/docker.yml' 10 | 11 | jobs: 12 | build-dev: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - 16 | name: Checkout 17 | uses: actions/checkout@v2 18 | - 19 | name: Docker meta 20 | id: docker_meta 21 | uses: crazy-max/ghaction-docker-meta@v1.11.0 22 | with: 23 | images: ghcr.io/getgatekeeper/ldapserver-dev 24 | tag-sha: true 25 | - 26 | name: Set up QEMU 27 | uses: docker/setup-qemu-action@v1 28 | - 29 | name: Set up Docker Buildx 30 | uses: docker/setup-buildx-action@v1 31 | - 32 | name: Login to GitHub Container Registry 33 | uses: docker/login-action@v1 34 | with: 35 | registry: ghcr.io 36 | username: lukasreschke 37 | password: ${{ secrets.CR_PAT }} 38 | - 39 | name: Build and push 40 | uses: docker/build-push-action@v2 41 | with: 42 | context: . 43 | file: .devcontainer/Dockerfile 44 | platforms: linux/amd64,linux/arm64 45 | push: true 46 | tags: ${{ steps.docker_meta.outputs.tags }} 47 | labels: ${{ steps.docker_meta.outputs.labels }} 48 | -------------------------------------------------------------------------------- /.github/workflows/linter.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ########################### 3 | ########################### 4 | ## Linter GitHub Actions ## 5 | ########################### 6 | ########################### 7 | name: Lint Code Base 8 | 9 | # 10 | # Documentation: 11 | # https://help.github.com/en/articles/workflow-syntax-for-github-actions 12 | # 13 | 14 | ############################# 15 | # Start the job on all push # 16 | ############################# 17 | on: 18 | push: 19 | branches-ignore: [main] 20 | # Remove the line above to run when pushing to main 21 | pull_request: 22 | branches: [main] 23 | 24 | ############### 25 | # Set the Job # 26 | ############### 27 | jobs: 28 | build: 29 | # Name the Job 30 | name: Lint Code Base 31 | # Set the agent to run on 32 | runs-on: ubuntu-latest 33 | 34 | ################## 35 | # Load all steps # 36 | ################## 37 | steps: 38 | ########################## 39 | # Checkout the code base # 40 | ########################## 41 | - name: Checkout Code 42 | uses: actions/checkout@v2 43 | with: 44 | # Full git history is needed to get a proper list of changed files within `super-linter` 45 | fetch-depth: 0 46 | 47 | ################################ 48 | # Run Linter against code base # 49 | ################################ 50 | - name: Lint Code Base 51 | uses: github/super-linter@v3.15.1 52 | env: 53 | VALIDATE_ALL_CODEBASE: false 54 | DEFAULT_BRANCH: main 55 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 56 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Setup .NET Core 17 | uses: actions/setup-dotnet@v1 18 | with: 19 | dotnet-version: 5.0.100 20 | - name: Build Sample 21 | run: dotnet build --configuration Release Sample/Sample.csproj 22 | - name: Install ldapsearch 23 | run: sudo apt-get update && sudo apt-get -y install ldap-utils 24 | - name: Test Sample 25 | run: dotnet test Sample.Tests/ --collect:"XPlat Code Coverage" -r TestResults/ 26 | - name: Test Gatekeeper.LdapServerLibrary.Tests 27 | run: dotnet test Gatekeeper.LdapServerLibrary.Tests/ --collect:"XPlat Code Coverage" -r TestResults/ 28 | - uses: codecov/codecov-action@v1 29 | with: 30 | directory: TestResults/ 31 | fail_ci_if_error: true 32 | verbose: true 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *.*~ 3 | project.lock.json 4 | .DS_Store 5 | *.pyc 6 | nupkg/ 7 | 8 | # Visual Studio Code 9 | .vscode 10 | 11 | # Rider 12 | .idea 13 | 14 | # User-specific files 15 | *.suo 16 | *.user 17 | *.userosscache 18 | *.sln.docstates 19 | 20 | # Build results 21 | [Dd]ebug/ 22 | [Dd]ebugPublic/ 23 | [Rr]elease/ 24 | [Rr]eleases/ 25 | x64/ 26 | x86/ 27 | build/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Oo]ut/ 32 | msbuild.log 33 | msbuild.err 34 | msbuild.wrn 35 | 36 | # Visual Studio 2015 37 | .vs/ 38 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to the LDAP Server Library 2 | 3 | We generally appreciate any contributions to the LDAP Server Library. Please note, that whilst this aims to be a general-purpose library, this library was ultimately created to implement an LDAP Server in the [Gatekeeper application](https://github.com/GetGatekeeper/Server). 4 | 5 | ## Setup Dev Environment 6 | 7 | The repository includes a dev container that ships all the required dependencies to set this up. Either use [GitHub Codespaces](https://github.com/codespaces) or [Visual Studio Code Remote Containers](https://code.visualstudio.com/docs/remote/containers#_quick-start-open-a-git-repository-or-github-pr-in-an-isolated-container-volume). 8 | 9 | ## Using Wireshark to analyze the traffic 10 | 11 | The sample application provided in the "Sample" folder can easily be intercepted with tcpdump: 12 | 13 | ```bash 14 | cd Sample/ && dotnet run 15 | ldapsearch -w test -H ldap://localhost:3389 -b "dc=example,dc=com" -D "cn=Manager,dc=example,dc=com" "cn=test1" 16 | tcpdump -i lo -w output.dump port 3389 17 | ``` 18 | 19 | Once done, download "output.dump" and open it in Wireshark. This will give you a good overview of the behaviour. 20 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary.Tests/Gatekeeper.LdapServerLibrary.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | all 17 | 18 | 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | all 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary.Tests/Parser/RdnParserTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Xunit; 3 | using Gatekeeper.LdapServerLibrary.Parser; 4 | 5 | namespace Gatekeeper.LdapServerLibrary.Tests.Parser 6 | { 7 | public class RdnParserTest 8 | { 9 | [Theory] 10 | [MemberData(nameof(GetData))] 11 | public void TestParseRdnString(string rdn, Dictionary> expected) 12 | { 13 | Assert.Equal(expected, RdnParser.ParseRdnString(rdn)); 14 | } 15 | 16 | public static IEnumerable GetData() 17 | { 18 | return new List 19 | { 20 | new object[] { "uid=test1,ou=People,dc=example,dc=com", new Dictionary> { { "uid", new List { "test1" }}, {"ou", new List {"People"}}, {"dc", new List{"example", "com"}} }}, 21 | new object[] { "InvalidRn", new Dictionary>() }, 22 | }; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary.Tests/Session/LdapEventsTest.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | using Gatekeeper.LdapServerLibrary.Session.Events; 3 | using Moq; 4 | using System.Threading.Tasks; 5 | using System.Collections.Generic; 6 | using Gatekeeper.LdapServerLibrary.Session.Replies; 7 | using System.Net; 8 | 9 | namespace Gatekeeper.LdapServerLibrary.Tests.Session 10 | { 11 | public class LdapEventsTest 12 | { 13 | [Fact] 14 | public async Task TestOnAuthenticationRequest() 15 | { 16 | LdapEvents events = new LdapEvents(); 17 | 18 | IAuthenticationEvent authEventMock = new Mock().Object; 19 | bool result = await events.OnAuthenticationRequest(new ClientContext(IPAddress.Parse("127.0.0.1")), authEventMock); 20 | 21 | Assert.False(result); 22 | } 23 | 24 | [Fact] 25 | public async Task TestOnSearchRequest() 26 | { 27 | LdapEvents events = new LdapEvents(); 28 | 29 | ISearchEvent searchEventMock = new Mock().Object; 30 | 31 | List result = await events.OnSearchRequest(new ClientContext(IPAddress.Parse("127.0.0.1")), searchEventMock); 32 | 33 | Assert.Empty(result); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Engine/DecisionEngine.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Runtime.Serialization; 6 | using System.Threading.Tasks; 7 | using Gatekeeper.LdapServerLibrary.Engine.Handler; 8 | using Gatekeeper.LdapServerLibrary.Models; 9 | using Gatekeeper.LdapServerLibrary.Models.Operations; 10 | using Gatekeeper.LdapPacketParserLibrary.Models.Operations.Request; 11 | using Gatekeeper.LdapServerLibrary.Models.Operations.Response; 12 | 13 | namespace Gatekeeper.LdapServerLibrary.Engine 14 | { 15 | internal class DecisionEngine 16 | { 17 | private readonly ClientContext _clientContext; 18 | 19 | public DecisionEngine(ClientContext clientContext) 20 | { 21 | _clientContext = clientContext; 22 | } 23 | 24 | internal async Task> GenerateReply(LdapPacketParserLibrary.Models.LdapMessage message) 25 | { 26 | // Authentication check 27 | List publicOperations = new List{ 28 | typeof(BindRequest), 29 | typeof(UnbindRequest), 30 | typeof(ExtendedRequest), 31 | }; 32 | if (!_clientContext.IsAuthenticated && !publicOperations.Contains(message.ProtocolOp.GetType())) 33 | { 34 | return new List(){ 35 | new LdapMessage(message.MessageId, new BindResponse(new LdapResult(LdapResult.ResultCodeEnum.InappropriateAuthentication, null, null))) 36 | }; 37 | } 38 | 39 | LdapEvents eventListener = SingletonContainer.GetLdapEventListener(); 40 | 41 | Type protocolType = message.ProtocolOp.GetType(); 42 | Type handlerType = SingletonContainer.GetHandlerMapper().GetHandlerForType(protocolType); 43 | 44 | var parameters = new object[] { _clientContext, eventListener, message.ProtocolOp }; 45 | object? invokableClass = FormatterServices.GetUninitializedObject(handlerType); 46 | 47 | if (invokableClass != null) 48 | { 49 | MethodInfo? method = handlerType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Single(x => x.Name.EndsWith("Handle")); 50 | 51 | if (method != null) 52 | { 53 | Task resultTask = (Task)method.Invoke(invokableClass, parameters); 54 | await resultTask; 55 | PropertyInfo? propertInfo = resultTask.GetType().GetProperty("Result"); 56 | object result = propertInfo.GetValue(resultTask); 57 | 58 | if (result != null) 59 | { 60 | List messages = new List(); 61 | 62 | HandlerReply handlerReply = (HandlerReply)result; 63 | foreach (IProtocolOp op in handlerReply._protocolOps) 64 | { 65 | messages.Add(new LdapMessage(message.MessageId, op)); 66 | } 67 | 68 | return messages; 69 | } 70 | } 71 | } 72 | 73 | throw new System.Exception(); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Engine/Handler/BindRequestHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using Gatekeeper.LdapServerLibrary.Models.Operations; 4 | using Gatekeeper.LdapServerLibrary.Models.Operations.Response; 5 | using Gatekeeper.LdapPacketParserLibrary.Models.Operations.Request; 6 | using Gatekeeper.LdapServerLibrary.Parser; 7 | using Gatekeeper.LdapServerLibrary.Session.Events; 8 | 9 | namespace Gatekeeper.LdapServerLibrary.Engine.Handler 10 | { 11 | internal class BindRequestHandler : IRequestHandler 12 | { 13 | async Task IRequestHandler.Handle(ClientContext context, LdapEvents eventListener, BindRequest operation) 14 | { 15 | Dictionary> rdn = RdnParser.ParseRdnString(operation.Name); 16 | AuthenticationEvent authEvent = new AuthenticationEvent(rdn, operation.Authentication); 17 | bool success = await eventListener.OnAuthenticationRequest(context, authEvent); 18 | 19 | if (success) 20 | { 21 | context.IsAuthenticated = true; 22 | context.Rdn = rdn; 23 | 24 | LdapResult ldapResult = new LdapResult(LdapResult.ResultCodeEnum.Success, null, null); 25 | BindResponse bindResponse = new BindResponse(ldapResult); 26 | return new HandlerReply(new List { bindResponse }); 27 | } 28 | else 29 | { 30 | context.IsAuthenticated = false; 31 | context.Rdn = new Dictionary>(); 32 | 33 | LdapResult ldapResult = new LdapResult(LdapResult.ResultCodeEnum.InappropriateAuthentication, null, null); 34 | BindResponse bindResponse = new BindResponse(ldapResult); 35 | return new HandlerReply(new List { bindResponse }); 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Engine/Handler/ExtendedRequestHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using Gatekeeper.LdapServerLibrary.Models.Operations; 4 | using Gatekeeper.LdapServerLibrary.Models.Operations.Response; 5 | using Gatekeeper.LdapPacketParserLibrary.Models.Operations.Request; 6 | 7 | namespace Gatekeeper.LdapServerLibrary.Engine.Handler 8 | { 9 | internal class ExtendedRequestHandler : IRequestHandler 10 | { 11 | internal const string StartTLS = "1.3.6.1.4.1.1466.20037"; 12 | 13 | async Task IRequestHandler.Handle(ClientContext context, LdapEvents eventListener, ExtendedRequest operation) 14 | { 15 | if (operation.RequestName == StartTLS && SingletonContainer.GetCertificate() != null) 16 | { 17 | context.HasEncryptedConnection = true; 18 | return new HandlerReply(new List{ 19 | new ExtendedOperationResponse( 20 | new LdapResult(LdapResult.ResultCodeEnum.Success, null, null), 21 | StartTLS, 22 | null 23 | ), 24 | }); 25 | } 26 | 27 | LdapResult ldapResult = new LdapResult(LdapResult.ResultCodeEnum.ProtocolError, null, null); 28 | BindResponse bindResponse = new BindResponse(ldapResult); 29 | return new HandlerReply(new List { bindResponse }); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Engine/Handler/HandlerReply.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Gatekeeper.LdapServerLibrary.Models.Operations; 3 | 4 | namespace Gatekeeper.LdapServerLibrary.Engine.Handler 5 | { 6 | internal class HandlerReply 7 | { 8 | internal readonly List _protocolOps; 9 | 10 | public HandlerReply(List protocolOps) 11 | { 12 | _protocolOps = protocolOps; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Engine/Handler/IRequestHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Gatekeeper.LdapPacketParserLibrary.Models.Operations; 3 | 4 | namespace Gatekeeper.LdapServerLibrary.Engine.Handler 5 | { 6 | internal interface IRequestHandler where T : IProtocolOp 7 | { 8 | internal Task Handle(ClientContext context, LdapEvents eventListener, T operation); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Engine/Handler/SearchRequestHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using Gatekeeper.LdapServerLibrary.Models.Operations; 4 | using Gatekeeper.LdapServerLibrary.Models.Operations.Response; 5 | using Gatekeeper.LdapPacketParserLibrary.Models.Operations.Request; 6 | using Gatekeeper.LdapServerLibrary.Session.Events; 7 | using Gatekeeper.LdapServerLibrary.Session.Replies; 8 | 9 | namespace Gatekeeper.LdapServerLibrary.Engine.Handler 10 | { 11 | internal class SearchRequestHandler : IRequestHandler 12 | { 13 | async Task IRequestHandler.Handle(ClientContext context, LdapEvents eventListener, SearchRequest operation) 14 | { 15 | SearchEvent searchEvent = new SearchEvent 16 | { 17 | SearchRequest = operation, 18 | }; 19 | List replies = await eventListener.OnSearchRequest(context, searchEvent); 20 | 21 | List opReply = new List(); 22 | 23 | foreach (SearchResultReply reply in replies) 24 | { 25 | SearchResultEntry entry = new SearchResultEntry(reply); 26 | opReply.Add(entry); 27 | } 28 | 29 | var resultCode = (replies.Count > 0) ? LdapResult.ResultCodeEnum.Success : LdapResult.ResultCodeEnum.NoSuchObject; 30 | 31 | LdapResult ldapResult = new LdapResult(resultCode, null, null); 32 | SearchResultDone searchResultDone = new SearchResultDone(ldapResult); 33 | opReply.Add(searchResultDone); 34 | 35 | return new HandlerReply(opReply); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Engine/Handler/UnbindRequestHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using Gatekeeper.LdapServerLibrary.Models.Operations; 4 | using Gatekeeper.LdapServerLibrary.Models.Operations.Response; 5 | using Gatekeeper.LdapPacketParserLibrary.Models.Operations.Request; 6 | 7 | namespace Gatekeeper.LdapServerLibrary.Engine.Handler 8 | { 9 | internal class UnbindRequestHandler : IRequestHandler 10 | { 11 | Task IRequestHandler.Handle(ClientContext context, LdapEvents eventListener, UnbindRequest operation) 12 | { 13 | context.IsAuthenticated = false; 14 | context.Rdn = new Dictionary>(); 15 | return Task.FromResult(new HandlerReply(new List { 16 | new UnbindDummyResponse() 17 | })); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Engine/HandlerMapper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Gatekeeper.LdapServerLibrary.Engine.Handler; 3 | using Gatekeeper.LdapPacketParserLibrary.Models.Operations.Request; 4 | 5 | namespace Gatekeeper.LdapServerLibrary.Engine 6 | { 7 | internal class HandlerMapper 8 | { 9 | internal Type GetHandlerForType(Type type) 10 | { 11 | if (type == typeof(BindRequest)) 12 | { 13 | return typeof(BindRequestHandler); 14 | } 15 | 16 | if (type == typeof(ExtendedRequest)) 17 | { 18 | return typeof(ExtendedRequestHandler); 19 | } 20 | 21 | if (type == typeof(SearchRequest)) 22 | { 23 | return typeof(SearchRequestHandler); 24 | } 25 | 26 | if (type == typeof(UnbindRequest)) 27 | { 28 | return typeof(UnbindRequestHandler); 29 | } 30 | 31 | throw new NotImplementedException("Type " + type + " is not implemented"); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Gatekeeper.LdapServerLibrary.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | enable 6 | true 7 | snupkg 8 | 0.0.10-alpha 9 | Lukas Reschke 10 | Gatekeeper 11 | 12 | This library implements a simple LDAP Server written in C#, which can be embedded into your applications. 13 | 14 | API reference can be found at https://github.com/GetGatekeeper/LdapServerLibrary 15 | 16 | AGPL-3.0-or-later 17 | https://github.com/GetGatekeeper/LdapServerLibrary 18 | https://github.com/GetGatekeeper/LdapServerLibrary.git 19 | Allow specifying listening IP address 20 | git 21 | Gatekeeper.LdapServerLibrary 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/ILogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Gatekeeper.LdapServerLibrary { 4 | public interface ILogger 5 | { 6 | void LogException(Exception e); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/LdapServer.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Security.Cryptography.X509Certificates; 3 | using System.Threading.Tasks; 4 | using Gatekeeper.LdapServerLibrary.Network; 5 | 6 | namespace Gatekeeper.LdapServerLibrary 7 | { 8 | public class LdapServer 9 | { 10 | public int Port = 339; 11 | public IPAddress IPAddress = IPAddress.Parse("127.0.0.1"); 12 | 13 | public void RegisterEventListener(LdapEvents ldapEvents) 14 | { 15 | SingletonContainer.SetLdapEventListener(ldapEvents); 16 | } 17 | 18 | public void RegisterLogger(ILogger logger) 19 | { 20 | SingletonContainer.SetLogger(logger); 21 | } 22 | 23 | public void RegisterCertificate(X509Certificate2 certificate) 24 | { 25 | SingletonContainer.SetCertificate(certificate); 26 | } 27 | 28 | public async Task Start() 29 | { 30 | ConnectionManager manager = new ConnectionManager(); 31 | NetworkListener listener = new NetworkListener( 32 | manager, 33 | IPAddress, 34 | Port 35 | ); 36 | await listener.Start(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Models/LdapMessage.cs: -------------------------------------------------------------------------------- 1 | using System.Numerics; 2 | using Gatekeeper.LdapServerLibrary.Models.Operations; 3 | 4 | namespace Gatekeeper.LdapServerLibrary.Models 5 | { 6 | internal class LdapMessage 7 | { 8 | internal readonly BigInteger MessageId; 9 | internal readonly IProtocolOp ProtocolOp; 10 | 11 | internal LdapMessage( 12 | BigInteger messageId, 13 | IProtocolOp protocolOp 14 | ) 15 | { 16 | MessageId = messageId; 17 | ProtocolOp = protocolOp; 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Models/Operations/IProtocolOp.cs: -------------------------------------------------------------------------------- 1 | using System.Formats.Asn1; 2 | 3 | namespace Gatekeeper.LdapServerLibrary.Models.Operations 4 | { 5 | internal interface IProtocolOp 6 | { 7 | internal int GetTag(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Models/Operations/Response/BindResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Gatekeeper.LdapServerLibrary.Models.Operations.Response 2 | { 3 | internal class BindResponse : IProtocolOp 4 | { 5 | internal readonly LdapResult LdapResult; 6 | 7 | internal BindResponse(LdapResult ldapResult) 8 | { 9 | LdapResult = ldapResult; 10 | } 11 | 12 | int IProtocolOp.GetTag() 13 | { 14 | return 1; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Models/Operations/Response/ExtendedOperationResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Gatekeeper.LdapServerLibrary.Models.Operations.Response 2 | { 3 | internal class ExtendedOperationResponse : IProtocolOp 4 | { 5 | internal readonly string? ResponseName; 6 | internal readonly string? ResponseValue; 7 | internal readonly LdapResult LdapResult; 8 | 9 | internal ExtendedOperationResponse(LdapResult ldapResult, string? responseName, string? responseValue) 10 | { 11 | LdapResult = ldapResult; 12 | ResponseName = responseName; 13 | ResponseValue = responseValue; 14 | } 15 | 16 | int IProtocolOp.GetTag() 17 | { 18 | return 24; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Models/Operations/Response/LdapResult.cs: -------------------------------------------------------------------------------- 1 | namespace Gatekeeper.LdapServerLibrary.Models.Operations.Response 2 | { 3 | internal class LdapResult 4 | { 5 | internal readonly ResultCodeEnum ResultCode; 6 | internal readonly string? MatchedDN; 7 | internal readonly string? ErrorMessage; 8 | 9 | internal LdapResult( 10 | ResultCodeEnum resultCode, 11 | string? matchedDn, 12 | string? errorMessage 13 | ) 14 | { 15 | ResultCode = resultCode; 16 | MatchedDN = matchedDn; 17 | ErrorMessage = errorMessage; 18 | } 19 | 20 | internal enum ResultCodeEnum 21 | { 22 | Success = 0, 23 | OperationsError = 1, 24 | ProtocolError = 2, 25 | NoSuchObject = 32, 26 | InappropriateAuthentication = 48, 27 | InvalidCredentials = 49, 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Models/Operations/Response/SearchResultDone.cs: -------------------------------------------------------------------------------- 1 | namespace Gatekeeper.LdapServerLibrary.Models.Operations.Response 2 | { 3 | internal class SearchResultDone : IProtocolOp 4 | { 5 | internal readonly LdapResult LdapResult; 6 | 7 | internal SearchResultDone(LdapResult ldapResult) 8 | { 9 | LdapResult = ldapResult; 10 | } 11 | 12 | int IProtocolOp.GetTag() 13 | { 14 | return 5; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Models/Operations/Response/SearchResultEntry.cs: -------------------------------------------------------------------------------- 1 | using Gatekeeper.LdapServerLibrary.Session.Replies; 2 | 3 | namespace Gatekeeper.LdapServerLibrary.Models.Operations.Response 4 | { 5 | internal class SearchResultEntry : IProtocolOp 6 | { 7 | internal readonly SearchResultReply SearchResultReply; 8 | 9 | internal SearchResultEntry( 10 | SearchResultReply searchResultReply 11 | ) 12 | { 13 | SearchResultReply = searchResultReply; 14 | } 15 | 16 | int IProtocolOp.GetTag() 17 | { 18 | return 4; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Models/Operations/Response/UnbindDummyResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Gatekeeper.LdapServerLibrary.Models.Operations.Response 2 | { 3 | internal class UnbindDummyResponse : IProtocolOp 4 | { 5 | int IProtocolOp.GetTag() 6 | { 7 | return -1; 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Network/ClientSession.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Net.Security; 5 | using System.Net.Sockets; 6 | using System.Threading.Tasks; 7 | using Gatekeeper.LdapServerLibrary.Engine; 8 | using Gatekeeper.LdapServerLibrary.Models; 9 | using Gatekeeper.LdapServerLibrary.Engine.Handler; 10 | using System.Net; 11 | 12 | namespace Gatekeeper.LdapServerLibrary.Network 13 | { 14 | internal class ClientSession 15 | { 16 | internal readonly TcpClient Client; 17 | private bool _useStartTls; 18 | private bool _clientIsConnected = true; 19 | 20 | private const int ASN_LENGTH_INDICATOR = 1; 21 | private const int ASN_MAX_SINGLE_BYTE_LENGTH = 127; 22 | private const int ASN_LENGTH_PREFIX_COUNT = 2; 23 | 24 | internal ClientSession(TcpClient client) 25 | { 26 | Client = client; 27 | } 28 | 29 | private int GetMultiByteLength(byte lengthIndicator) 30 | { 31 | return (lengthIndicator >> 0) & 127; 32 | } 33 | 34 | public async Task ReadFullyAsync(Stream stream) 35 | { 36 | using (MemoryStream ms = new MemoryStream()) 37 | { 38 | List PacketLength = new List(); 39 | Byte[] LengthBuffer = new byte[10]; 40 | int streamPosition = 0; 41 | int? packetSize = null; 42 | bool isMultiByteSize = false; 43 | int? multiByteSize = null; 44 | 45 | while (true) 46 | { 47 | byte[] buffer = new byte[1]; 48 | int read = await stream.ReadAsync(buffer, 0, buffer.Length); 49 | 50 | if (streamPosition == ASN_LENGTH_INDICATOR) 51 | { 52 | int number = Convert.ToInt32(buffer[0]); 53 | if (number <= ASN_MAX_SINGLE_BYTE_LENGTH) 54 | { 55 | packetSize = number + ASN_LENGTH_PREFIX_COUNT; 56 | } 57 | else 58 | { 59 | isMultiByteSize = true; 60 | multiByteSize = GetMultiByteLength(buffer[0]); 61 | } 62 | } 63 | else 64 | { 65 | if (isMultiByteSize && (streamPosition - ASN_LENGTH_PREFIX_COUNT) < multiByteSize) 66 | { 67 | PacketLength.Add(buffer[0]); 68 | } 69 | else if (isMultiByteSize && (streamPosition - ASN_LENGTH_PREFIX_COUNT) == multiByteSize) 70 | { 71 | string hexValue = BitConverter.ToString(PacketLength.ToArray()).Replace("-", ""); 72 | packetSize = Convert.ToInt32(hexValue, 16) + ASN_LENGTH_PREFIX_COUNT + PacketLength.Count; 73 | } 74 | } 75 | 76 | ms.Write(buffer, 0, read); 77 | streamPosition++; 78 | 79 | if (read <= 0 || streamPosition == packetSize) 80 | { 81 | return ms.ToArray(); 82 | } 83 | } 84 | } 85 | } 86 | 87 | internal void StartReceiving() 88 | { 89 | Task networkTask = new Task(async () => 90 | { 91 | NetworkStream unencryptedStream = Client.GetStream(); 92 | SslStream sslStream = new SslStream(unencryptedStream); 93 | 94 | IPEndPoint? endpoint = (IPEndPoint?)Client.Client.RemoteEndPoint; 95 | if (endpoint == null) 96 | { 97 | throw new Exception("IP address is null"); 98 | } 99 | 100 | ClientContext clientContext = new ClientContext(endpoint.Address); 101 | DecisionEngine engine = new DecisionEngine(clientContext); 102 | 103 | bool _initializedTls = false; 104 | 105 | while (_clientIsConnected) 106 | { 107 | Stream rawOrSslStream = (_useStartTls) ? sslStream : unencryptedStream; 108 | 109 | try 110 | { 111 | if (_useStartTls && !_initializedTls) 112 | { 113 | await sslStream.AuthenticateAsServerAsync(new SslServerAuthenticationOptions 114 | { 115 | ServerCertificate = SingletonContainer.GetCertificate(), 116 | }); 117 | _initializedTls = true; 118 | } 119 | 120 | Byte[] data = await ReadFullyAsync(rawOrSslStream); 121 | 122 | await HandleAsync(data, rawOrSslStream, engine); 123 | } 124 | catch (Exception e) 125 | { 126 | ILogger? logger = SingletonContainer.GetLogger(); 127 | if (logger != null) 128 | { 129 | logger.LogException(e); 130 | } 131 | 132 | break; 133 | } 134 | } 135 | 136 | Client.Close(); 137 | }); 138 | 139 | networkTask.Start(); 140 | } 141 | 142 | private async Task HandleAsync(byte[] bytes, Stream stream, DecisionEngine engine) 143 | { 144 | Gatekeeper.LdapPacketParserLibrary.Parser parser = new Gatekeeper.LdapPacketParserLibrary.Parser(); 145 | LdapPacketParserLibrary.Models.LdapMessage message = parser.TryParsePacket(bytes); 146 | 147 | List replies = await engine.GenerateReply(message); 148 | foreach (LdapMessage outMsg in replies) 149 | { 150 | if (outMsg.ProtocolOp.GetType() == typeof(Gatekeeper.LdapServerLibrary.Models.Operations.Response.UnbindDummyResponse)) 151 | { 152 | _clientIsConnected = false; 153 | break; 154 | } 155 | byte[] msg = (new Parser.PacketParser()).TryEncodePacket(outMsg); 156 | stream.Write(msg, 0, msg.Length); 157 | 158 | if (outMsg.ProtocolOp.GetType() == typeof(Gatekeeper.LdapServerLibrary.Models.Operations.Response.ExtendedOperationResponse)) 159 | { 160 | var response = ((Gatekeeper.LdapServerLibrary.Models.Operations.Response.ExtendedOperationResponse)outMsg.ProtocolOp); 161 | if (response.ResponseName == ExtendedRequestHandler.StartTLS) 162 | { 163 | _useStartTls = true; 164 | } 165 | } 166 | } 167 | } 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Network/ConnectionManager.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Sockets; 2 | 3 | namespace Gatekeeper.LdapServerLibrary.Network 4 | { 5 | internal class ConnectionManager 6 | { 7 | internal void AddClient(TcpClient client) 8 | { 9 | ClientSession session = new ClientSession(client); 10 | session.StartReceiving(); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Network/NetworkListener.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Sockets; 4 | using System.Threading.Tasks; 5 | 6 | namespace Gatekeeper.LdapServerLibrary.Network 7 | { 8 | internal class NetworkListener 9 | { 10 | private readonly ConnectionManager _connectionManager; 11 | private readonly int _port; 12 | private readonly IPAddress _ipAddress; 13 | 14 | internal NetworkListener( 15 | ConnectionManager connectionManager, 16 | IPAddress ipAddress, 17 | int port) 18 | { 19 | _connectionManager = connectionManager; 20 | _ipAddress = ipAddress; 21 | _port = port; 22 | } 23 | 24 | internal async Task Start() 25 | { 26 | TcpListener? server = null; 27 | try 28 | { 29 | server = new TcpListener(_ipAddress, _port); 30 | server.Start(); 31 | 32 | while (true) 33 | { 34 | TcpClient client = await server.AcceptTcpClientAsync(); 35 | _connectionManager.AddClient(client); 36 | } 37 | } 38 | finally 39 | { 40 | if (server != null) 41 | { 42 | server.Stop(); 43 | } 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Parser/Encoder/BindResponseEncoder.cs: -------------------------------------------------------------------------------- 1 | using System.Formats.Asn1; 2 | using Gatekeeper.LdapServerLibrary.Models.Operations.Response; 3 | 4 | namespace Gatekeeper.LdapServerLibrary.Parser.Encoder 5 | { 6 | internal class BindResponseEncoder : IApplicationEncoder 7 | { 8 | public AsnWriter TryEncode(AsnWriter writer, BindResponse message) 9 | { 10 | Asn1Tag bindResponseApplication = new Asn1Tag(TagClass.Application, 1); 11 | using (writer.PushSequence(bindResponseApplication)) 12 | { 13 | writer.WriteEnumeratedValue(message.LdapResult.ResultCode); 14 | writer.WriteOctetString(System.Text.Encoding.ASCII.GetBytes("")); 15 | writer.WriteOctetString(System.Text.Encoding.ASCII.GetBytes("")); 16 | } 17 | 18 | return writer; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Parser/Encoder/ExtendedOperationResponseEncoder.cs: -------------------------------------------------------------------------------- 1 | using System.Formats.Asn1; 2 | using System.Text; 3 | using Gatekeeper.LdapServerLibrary.Models.Operations.Response; 4 | 5 | namespace Gatekeeper.LdapServerLibrary.Parser.Encoder 6 | { 7 | internal class ExtendedOperationResponseEncoder : IApplicationEncoder 8 | { 9 | public AsnWriter TryEncode(AsnWriter writer, ExtendedOperationResponse message) 10 | { 11 | Asn1Tag responseApplicationTag = new Asn1Tag(TagClass.Application, 24); 12 | using (writer.PushSequence(responseApplicationTag)) 13 | { 14 | writer.WriteEnumeratedValue(message.LdapResult.ResultCode); 15 | writer.WriteOctetString(System.Text.Encoding.ASCII.GetBytes("")); 16 | writer.WriteOctetString(System.Text.Encoding.ASCII.GetBytes("")); 17 | 18 | if (message.ResponseName != null) 19 | { 20 | using (writer.PushOctetString(new Asn1Tag(TagClass.ContextSpecific, 10))) 21 | { 22 | writer.WriteOctetString(Encoding.ASCII.GetBytes(message.ResponseName)); 23 | } 24 | } 25 | if (message.ResponseValue != null) 26 | { 27 | using (writer.PushOctetString(new Asn1Tag(TagClass.ContextSpecific, 11))) 28 | { 29 | writer.WriteOctetString(Encoding.ASCII.GetBytes(message.ResponseValue)); 30 | } 31 | } 32 | } 33 | 34 | return writer; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Parser/Encoder/IApplicationEncoder.cs: -------------------------------------------------------------------------------- 1 | using System.Formats.Asn1; 2 | using Gatekeeper.LdapServerLibrary.Models.Operations; 3 | 4 | namespace Gatekeeper.LdapServerLibrary.Parser.Encoder 5 | { 6 | internal interface IApplicationEncoder where T : IProtocolOp 7 | { 8 | AsnWriter TryEncode(AsnWriter writer, T message); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Parser/Encoder/SearchResultDoneEncoder.cs: -------------------------------------------------------------------------------- 1 | using System.Formats.Asn1; 2 | using Gatekeeper.LdapServerLibrary.Models.Operations.Response; 3 | 4 | namespace Gatekeeper.LdapServerLibrary.Parser.Encoder 5 | { 6 | internal class SearchResultDoneEncoder : IApplicationEncoder 7 | { 8 | public AsnWriter TryEncode(AsnWriter writer, SearchResultDone message) 9 | { 10 | Asn1Tag bindResponseApplication = new Asn1Tag(TagClass.Application, 5); 11 | 12 | using (writer.PushSequence(bindResponseApplication)) 13 | { 14 | writer.WriteEnumeratedValue(message.LdapResult.ResultCode); 15 | writer.WriteOctetString(System.Text.Encoding.ASCII.GetBytes("")); 16 | writer.WriteOctetString(System.Text.Encoding.ASCII.GetBytes("")); 17 | } 18 | 19 | return writer; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Parser/Encoder/SearchResultEntryEncoder.cs: -------------------------------------------------------------------------------- 1 | using System.Formats.Asn1; 2 | using Gatekeeper.LdapServerLibrary.Models.Operations.Response; 3 | using static Gatekeeper.LdapServerLibrary.Session.Replies.SearchResultReply; 4 | 5 | namespace Gatekeeper.LdapServerLibrary.Parser.Encoder 6 | { 7 | internal class SearchResultEntryEncoder : IApplicationEncoder 8 | { 9 | public AsnWriter TryEncode(AsnWriter writer, SearchResultEntry message) 10 | { 11 | Asn1Tag searchResultEntryApplication = new Asn1Tag(TagClass.Application, 4); 12 | 13 | using (writer.PushSequence(searchResultEntryApplication)) 14 | { 15 | writer.WriteOctetString(System.Text.Encoding.ASCII.GetBytes(message.SearchResultReply.CommonName)); 16 | using (writer.PushSequence()) 17 | { 18 | foreach (Attribute attribute in message.SearchResultReply.Attributes) 19 | { 20 | using (writer.PushSequence()) 21 | { 22 | writer.WriteOctetString(System.Text.Encoding.ASCII.GetBytes(attribute.Key)); 23 | using (writer.PushSetOf()) 24 | { 25 | foreach (string value in attribute.Values) 26 | { 27 | writer.WriteOctetString(System.Text.Encoding.ASCII.GetBytes(value)); 28 | } 29 | } 30 | } 31 | } 32 | } 33 | } 34 | 35 | return writer; 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Parser/OperationMapper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Runtime.Serialization; 6 | using Gatekeeper.LdapServerLibrary.Models.Operations; 7 | using Gatekeeper.LdapServerLibrary.Parser.Encoder; 8 | 9 | namespace Gatekeeper.LdapServerLibrary.Parser 10 | { 11 | internal class OperationMapper 12 | { 13 | private Dictionary OperationTypeMapper = new Dictionary(); 14 | private Dictionary DecoderTypeMapper = new Dictionary(); 15 | private Dictionary EncoderTypeMapper = new Dictionary(); 16 | 17 | internal OperationMapper() 18 | { 19 | PopulateOperationTypeMapper(); 20 | PopulateEncoderTypeMapper(); 21 | } 22 | 23 | private void PopulateEncoderTypeMapper() 24 | { 25 | IEnumerable types = from t in Assembly.GetExecutingAssembly().GetTypes() 26 | where t.GetInterfaces().Any(i => 27 | i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IApplicationEncoder<>) 28 | ) 29 | select t; 30 | 31 | types.ToList().ForEach(t => 32 | { 33 | Type operationType = t.GetInterfaces()[0].GenericTypeArguments[0]; 34 | KeyValuePair mappedOperation = OperationTypeMapper.First(x => x.Value == operationType); 35 | 36 | EncoderTypeMapper.Add(mappedOperation.Key, t); 37 | }); 38 | } 39 | 40 | private void PopulateOperationTypeMapper() 41 | { 42 | IEnumerable types = from t in Assembly.GetExecutingAssembly().GetTypes() 43 | where t.IsClass 44 | where typeof(IProtocolOp).IsAssignableFrom(t) 45 | select t; 46 | 47 | types.ToList().ForEach(t => 48 | { 49 | IProtocolOp protocolOp = (IProtocolOp)FormatterServices.GetUninitializedObject(t); 50 | int tag = protocolOp.GetTag(); 51 | OperationTypeMapper.Add(tag, t); 52 | }); 53 | } 54 | 55 | internal Type GetDecoderForTag(int tag) 56 | { 57 | return DecoderTypeMapper.Single(t => t.Key == tag).Value; 58 | } 59 | 60 | internal Type GetEncoderForTag(int tag) 61 | { 62 | return EncoderTypeMapper.Single(t => t.Key == tag).Value; 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Parser/PacketParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Formats.Asn1; 3 | using System.Reflection; 4 | using System.Runtime.Serialization; 5 | using Gatekeeper.LdapServerLibrary.Models; 6 | using Gatekeeper.LdapServerLibrary.Models.Operations; 7 | 8 | namespace Gatekeeper.LdapServerLibrary.Parser 9 | { 10 | internal class PacketParser 11 | { 12 | internal Byte[] TryEncodePacket(LdapMessage message) 13 | { 14 | OperationMapper mapper = SingletonContainer.GetOperationMapper(); 15 | Type encoder = mapper.GetEncoderForTag(message.ProtocolOp.GetTag()); 16 | 17 | AsnWriter writer = new AsnWriter(AsnEncodingRules.BER); 18 | 19 | object? result = null; 20 | using (writer.PushSequence()) 21 | { 22 | writer.WriteInteger(message.MessageId); 23 | 24 | var parameters = new object[] { writer, message.ProtocolOp }; 25 | object? invokableClass = FormatterServices.GetUninitializedObject(encoder); 26 | 27 | if (invokableClass != null) 28 | { 29 | MethodInfo? method = encoder.GetMethod("TryEncode"); 30 | if (method != null) 31 | { 32 | result = method.Invoke(invokableClass, parameters); 33 | } 34 | } 35 | } 36 | 37 | if(result != null) { 38 | Byte[] data = writer.Encode(); 39 | return data; 40 | } 41 | 42 | throw new NotImplementedException("The encoder for " + message.ProtocolOp.GetTag() + " is not implemented."); 43 | } 44 | 45 | private IProtocolOp DecodeApplicationData(int tagValue, AsnReader reader) 46 | { 47 | OperationMapper mapper = SingletonContainer.GetOperationMapper(); 48 | Type decoder = mapper.GetDecoderForTag(tagValue); 49 | 50 | var parameters = new object[] { reader }; 51 | object? invokableClass = FormatterServices.GetUninitializedObject(decoder); 52 | 53 | if (invokableClass != null) 54 | { 55 | MethodInfo? method = decoder.GetMethod("TryDecode"); 56 | if (method != null) 57 | { 58 | object result = method.Invoke(invokableClass, parameters); 59 | if (result != null) 60 | { 61 | return (IProtocolOp)result; 62 | } 63 | } 64 | } 65 | 66 | throw new NotImplementedException("The decoder for " + tagValue + " is not implemented."); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Parser/RdnParser.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Runtime.CompilerServices; 3 | 4 | [assembly:InternalsVisibleTo("Gatekeeper.LdapServerLibrary.Tests")] 5 | namespace Gatekeeper.LdapServerLibrary.Parser 6 | { 7 | internal class RdnParser 8 | { 9 | internal static Dictionary> ParseRdnString(string rdn) 10 | { 11 | string[] rdnAttributePairs = rdn.Split(','); 12 | 13 | Dictionary> parsedRdn = new Dictionary>(); 14 | 15 | foreach (string rdnAttribute in rdnAttributePairs) 16 | { 17 | string[] rdnAttributePair = rdnAttribute.Split('='); 18 | if (rdnAttributePair.Length == 2) 19 | { 20 | if (parsedRdn.ContainsKey(rdnAttributePair[0])) 21 | { 22 | parsedRdn[rdnAttributePair[0]].Add(rdnAttributePair[1]); 23 | } 24 | else 25 | { 26 | parsedRdn.Add(rdnAttributePair[0], new List { rdnAttributePair[1] }); 27 | } 28 | } 29 | } 30 | 31 | return parsedRdn; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Session/ClientContext.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Net; 3 | 4 | namespace Gatekeeper.LdapServerLibrary 5 | { 6 | public class ClientContext 7 | { 8 | public bool IsAuthenticated { get; set; } 9 | public bool HasEncryptedConnection { get; set; } 10 | public Dictionary> Rdn { get; set; } = new Dictionary>(); 11 | public readonly IPAddress IpAddress; 12 | 13 | public ClientContext(IPAddress ipAddress) 14 | { 15 | IpAddress = ipAddress; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Session/Events/AuthenticationEvent.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Gatekeeper.LdapServerLibrary.Session.Events 4 | { 5 | internal class AuthenticationEvent : IAuthenticationEvent 6 | { 7 | public Dictionary> Rdn { get; } 8 | public string Password { get; } 9 | 10 | public AuthenticationEvent( 11 | Dictionary> rdn, 12 | string password 13 | ) 14 | { 15 | Rdn = rdn; 16 | Password = password; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Session/Events/IAuthenticationEvent.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Gatekeeper.LdapServerLibrary.Session.Events 4 | { 5 | public interface IAuthenticationEvent 6 | { 7 | public Dictionary> Rdn { get; } 8 | public string Password { get; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Session/Events/ISearchEvent.cs: -------------------------------------------------------------------------------- 1 | using Gatekeeper.LdapPacketParserLibrary.Models.Operations.Request; 2 | 3 | namespace Gatekeeper.LdapServerLibrary.Session.Events 4 | { 5 | public interface ISearchEvent 6 | { 7 | SearchRequest SearchRequest { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Session/Events/SearchEvent.cs: -------------------------------------------------------------------------------- 1 | using Gatekeeper.LdapPacketParserLibrary.Models.Operations.Request; 2 | 3 | namespace Gatekeeper.LdapServerLibrary.Session.Events 4 | { 5 | public class SearchEvent : ISearchEvent 6 | { 7 | public SearchRequest SearchRequest { get; set; } = null!; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Session/LdapEvents.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using Gatekeeper.LdapServerLibrary.Session.Events; 4 | using Gatekeeper.LdapServerLibrary.Session.Replies; 5 | 6 | namespace Gatekeeper.LdapServerLibrary 7 | { 8 | public class LdapEvents 9 | { 10 | /// 11 | /// Override this for authentication requests. 12 | /// 13 | /// 14 | /// 15 | /// Whether the authentication should succeed or not 16 | public virtual Task OnAuthenticationRequest(ClientContext context, IAuthenticationEvent authenticationEvent) 17 | { 18 | return Task.FromResult(false); 19 | } 20 | 21 | /// 22 | /// Override this for search request support. 23 | /// 24 | /// 25 | /// 26 | /// List of search replies 27 | public virtual Task> OnSearchRequest(ClientContext context, ISearchEvent searchEvent) 28 | { 29 | return Task.FromResult(new List()); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/Session/Replies/SearchResultReply.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Gatekeeper.LdapServerLibrary.Session.Replies 4 | { 5 | public class SearchResultReply 6 | { 7 | internal readonly string CommonName; 8 | internal readonly List Attributes; 9 | 10 | public SearchResultReply( 11 | string commonName, 12 | List attributes) 13 | { 14 | CommonName = commonName; 15 | Attributes = attributes; 16 | } 17 | 18 | public class Attribute 19 | { 20 | internal readonly string Key; 21 | internal List Values; 22 | 23 | public Attribute(string key, List values) 24 | { 25 | Key = key; 26 | Values = values; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Gatekeeper.LdapServerLibrary/SingletonContainer.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography.X509Certificates; 2 | using Gatekeeper.LdapServerLibrary.Engine; 3 | using Gatekeeper.LdapServerLibrary.Parser; 4 | 5 | namespace Gatekeeper.LdapServerLibrary 6 | { 7 | internal class SingletonContainer 8 | { 9 | private static LdapEvents LdapEventListener = new LdapEvents(); 10 | private static OperationMapper OperationMapper = new OperationMapper(); 11 | private static HandlerMapper HandlerMapper = new HandlerMapper(); 12 | private static ILogger? Logger; 13 | private static X509Certificate2? Certificate; 14 | 15 | static internal void SetLogger(ILogger logger) 16 | { 17 | Logger = logger; 18 | } 19 | 20 | static internal ILogger? GetLogger() 21 | { 22 | return Logger; 23 | } 24 | 25 | static internal void SetLdapEventListener(LdapEvents listener) 26 | { 27 | LdapEventListener = listener; 28 | } 29 | 30 | static internal LdapEvents GetLdapEventListener() 31 | { 32 | return LdapEventListener; 33 | } 34 | 35 | static internal void SetCertificate(X509Certificate2 certificate) 36 | { 37 | Certificate = certificate; 38 | } 39 | 40 | static internal X509Certificate? GetCertificate() 41 | { 42 | return Certificate; 43 | } 44 | 45 | static internal OperationMapper GetOperationMapper() 46 | { 47 | return OperationMapper; 48 | } 49 | 50 | static internal HandlerMapper GetHandlerMapper() 51 | { 52 | return HandlerMapper; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LDAP Server Library for .NET 2 | 3 | This is a LDAP server library written in C#. It aims to implement basic LDAP functionalities required for lookups and authentication, and is used by [Gatekeeper](https://github.com/getgatekeeper/server). 4 | 5 | ## Supported 6 | 7 | - BindRequest 8 | - UnbindRequest 9 | - SearchRequest 10 | - ExtendedRequest 11 | 12 | ## Get via NuGet 13 | 14 | You can get this library via Nuget: https://www.nuget.org/packages/Gatekeeper.LdapServerLibrary 15 | 16 | ## Sample 17 | 18 | See the "Sample" folder for a sample on how to use this library. 19 | -------------------------------------------------------------------------------- /Sample.Tests/Integration/LdapSearchTests.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using Xunit; 3 | 4 | namespace Sample.Tests.Integration 5 | { 6 | public class LdapSearchTests : IClassFixture 7 | { 8 | private string ExecuteLdapSearch(string search) 9 | { 10 | return ExecuteLdapSearch(search, "dc=example,dc=com"); 11 | } 12 | 13 | private string ExecuteLdapSearch(string search, string baseDn) 14 | { 15 | return ExecuteLdapSearch(search, baseDn, "cn=Manager,dc=example,dc=com", "ValidManagerPassword"); 16 | } 17 | 18 | private string ExecuteLdapSearch(string search, string baseDn, string bindUser, string password) 19 | { 20 | string arguments = ""; 21 | 22 | if (password != null) 23 | { 24 | arguments += "-w " + password + " "; 25 | } 26 | 27 | arguments += "-H ldap://localhost:3389 -b \"" + baseDn + "\" "; 28 | 29 | if (bindUser != null) 30 | { 31 | arguments += "-D \"" + bindUser + "\" "; 32 | } 33 | arguments += search; 34 | 35 | ProcessStartInfo startInfo = new ProcessStartInfo() 36 | { 37 | FileName = "/usr/bin/ldapsearch", 38 | Arguments = arguments, 39 | RedirectStandardError = true, 40 | RedirectStandardOutput = true, 41 | }; 42 | 43 | Process p = new Process { StartInfo = startInfo }; 44 | p.Start(); 45 | p.WaitForExit(); 46 | 47 | string error = p.StandardError.ReadToEnd(); 48 | if (error != "") 49 | { 50 | return error; 51 | } 52 | 53 | startInfo = new ProcessStartInfo() 54 | { 55 | FileName = "/usr/bin/ldapsearch", 56 | Arguments = arguments + " -ZZ", 57 | RedirectStandardError = true, 58 | RedirectStandardOutput = true, 59 | }; 60 | startInfo.EnvironmentVariables.Add("LDAPTLS_REQCERT", "never"); 61 | 62 | Process tlsProcess = new Process { StartInfo = startInfo }; 63 | tlsProcess.Start(); 64 | tlsProcess.WaitForExit(); 65 | 66 | error = tlsProcess.StandardError.ReadToEnd(); 67 | if (error != "") 68 | { 69 | return error; 70 | } 71 | 72 | string standardOut = p.StandardOutput.ReadToEnd(); 73 | string tlsStandardOut = tlsProcess.StandardOutput.ReadToEnd(); 74 | 75 | 76 | Assert.Equal(standardOut.Replace("\nsearch: 2\n", "\nsearch: 3\n"), tlsStandardOut); 77 | 78 | return standardOut; 79 | } 80 | 81 | [Fact] 82 | public void TestSimpleEqualCnSearch() 83 | { 84 | string output = ExecuteLdapSearch("\"cn=test1\""); 85 | string expected = @"# extended LDIF 86 | # 87 | # LDAPv3 88 | # base with scope subtree 89 | # filter: cn=test1 90 | # requesting: ALL 91 | # 92 | 93 | # test1, example.com 94 | dn: cn=test1,dc=example,dc=com 95 | email: test1@example.com 96 | role: Administrator 97 | objectclass: inetOrgPerson 98 | displayname: Test User 1 99 | uid: test1 100 | 101 | # search result 102 | search: 2 103 | result: 0 Success 104 | 105 | # numResponses: 2 106 | # numEntries: 1 107 | ".Replace("\r", ""); 108 | 109 | Assert.Equal(expected, output); 110 | } 111 | 112 | [Fact] 113 | public void TestSimpleEqualAttributeSearch() 114 | { 115 | string output = ExecuteLdapSearch("\"(email=test2-alias@example.com)\""); 116 | string expected = @"# extended LDIF 117 | # 118 | # LDAPv3 119 | # base with scope subtree 120 | # filter: (email=test2-alias@example.com) 121 | # requesting: ALL 122 | # 123 | 124 | # test2, example.com 125 | dn: cn=test2,dc=example,dc=com 126 | email: test2@example.com 127 | email: test2-alias@example.com 128 | role: Employee 129 | objectclass: inetOrgPerson 130 | displayname: Test User 2 131 | uid: test2 132 | 133 | # search result 134 | search: 2 135 | result: 0 Success 136 | 137 | # numResponses: 2 138 | # numEntries: 1 139 | ".Replace("\r", ""); 140 | 141 | Assert.Equal(expected, output); 142 | } 143 | 144 | [Fact] 145 | public void TestPresenceObjectclassSearch() 146 | { 147 | string output = ExecuteLdapSearch("\"(objectclass=*)\""); 148 | string expected = @"# extended LDIF 149 | # 150 | # LDAPv3 151 | # base with scope subtree 152 | # filter: (objectclass=*) 153 | # requesting: ALL 154 | # 155 | 156 | # test1, example.com 157 | dn: cn=test1,dc=example,dc=com 158 | email: test1@example.com 159 | role: Administrator 160 | objectclass: inetOrgPerson 161 | displayname: Test User 1 162 | uid: test1 163 | 164 | # test2, example.com 165 | dn: cn=test2,dc=example,dc=com 166 | email: test2@example.com 167 | email: test2-alias@example.com 168 | role: Employee 169 | objectclass: inetOrgPerson 170 | displayname: Test User 2 171 | uid: test2 172 | 173 | # test3, example.com 174 | dn: cn=test3,dc=example,dc=com 175 | email: test3@example.com 176 | objectclass: inetOrgPerson 177 | displayname: Test User 3 178 | uid: test3 179 | 180 | # benutzer4, example.com 181 | dn: cn=benutzer4,dc=example,dc=com 182 | email: benutzer4@example.com 183 | objectclass: inetOrgPerson 184 | displayname: Benutzer 4 185 | uid: test4 186 | 187 | # search result 188 | search: 2 189 | result: 0 Success 190 | 191 | # numResponses: 5 192 | # numEntries: 4 193 | ".Replace("\r", ""); 194 | 195 | Assert.Equal(expected, output); 196 | } 197 | 198 | [Fact] 199 | public void TestSimpleAndFilter() 200 | { 201 | string output = ExecuteLdapSearch("\"(&(objectclass=*)(email=test1@example.com))\""); 202 | string expected = @"# extended LDIF 203 | # 204 | # LDAPv3 205 | # base with scope subtree 206 | # filter: (&(objectclass=*)(email=test1@example.com)) 207 | # requesting: ALL 208 | # 209 | 210 | # test1, example.com 211 | dn: cn=test1,dc=example,dc=com 212 | email: test1@example.com 213 | role: Administrator 214 | objectclass: inetOrgPerson 215 | displayname: Test User 1 216 | uid: test1 217 | 218 | # search result 219 | search: 2 220 | result: 0 Success 221 | 222 | # numResponses: 2 223 | # numEntries: 1 224 | ".Replace("\r", ""); 225 | 226 | Assert.Equal(expected, output); 227 | } 228 | 229 | [Fact] 230 | public void TestSimpleOrFilter() 231 | { 232 | string output = ExecuteLdapSearch("\"(|(email=test1@example.com)(email=test2@example.com))\""); 233 | string expected = @"# extended LDIF 234 | # 235 | # LDAPv3 236 | # base with scope subtree 237 | # filter: (|(email=test1@example.com)(email=test2@example.com)) 238 | # requesting: ALL 239 | # 240 | 241 | # test1, example.com 242 | dn: cn=test1,dc=example,dc=com 243 | email: test1@example.com 244 | role: Administrator 245 | objectclass: inetOrgPerson 246 | displayname: Test User 1 247 | uid: test1 248 | 249 | # test2, example.com 250 | dn: cn=test2,dc=example,dc=com 251 | email: test2@example.com 252 | email: test2-alias@example.com 253 | role: Employee 254 | objectclass: inetOrgPerson 255 | displayname: Test User 2 256 | uid: test2 257 | 258 | # search result 259 | search: 2 260 | result: 0 Success 261 | 262 | # numResponses: 3 263 | # numEntries: 2 264 | ".Replace("\r", ""); 265 | 266 | Assert.Equal(expected, output); 267 | } 268 | 269 | [Fact] 270 | public void TestNoSuchObject() 271 | { 272 | string output = ExecuteLdapSearch("\"(email=test99@example.com)\""); 273 | string expected = @"# extended LDIF 274 | # 275 | # LDAPv3 276 | # base with scope subtree 277 | # filter: (email=test99@example.com) 278 | # requesting: ALL 279 | # 280 | 281 | # search result 282 | search: 2 283 | result: 32 No such object 284 | 285 | # numResponses: 1 286 | ".Replace("\r", ""); 287 | 288 | Assert.Equal(expected, output); 289 | } 290 | 291 | [Fact] 292 | public void TestCnSubstringSearch() 293 | { 294 | string output = ExecuteLdapSearch("\"(cn=t*st*)\""); 295 | string expected = @"# extended LDIF 296 | # 297 | # LDAPv3 298 | # base with scope subtree 299 | # filter: (cn=t*st*) 300 | # requesting: ALL 301 | # 302 | 303 | # test1, example.com 304 | dn: cn=test1,dc=example,dc=com 305 | email: test1@example.com 306 | role: Administrator 307 | objectclass: inetOrgPerson 308 | displayname: Test User 1 309 | uid: test1 310 | 311 | # test2, example.com 312 | dn: cn=test2,dc=example,dc=com 313 | email: test2@example.com 314 | email: test2-alias@example.com 315 | role: Employee 316 | objectclass: inetOrgPerson 317 | displayname: Test User 2 318 | uid: test2 319 | 320 | # test3, example.com 321 | dn: cn=test3,dc=example,dc=com 322 | email: test3@example.com 323 | objectclass: inetOrgPerson 324 | displayname: Test User 3 325 | uid: test3 326 | 327 | # search result 328 | search: 2 329 | result: 0 Success 330 | 331 | # numResponses: 4 332 | # numEntries: 3 333 | ".Replace("\r", ""); 334 | 335 | Assert.Equal(expected, output); 336 | } 337 | 338 | [Fact] 339 | public void TestDisplaynameSubstringSearch() 340 | { 341 | string output = ExecuteLdapSearch("\"(displayname=T*st*)\""); 342 | string expected = @"# extended LDIF 343 | # 344 | # LDAPv3 345 | # base with scope subtree 346 | # filter: (displayname=T*st*) 347 | # requesting: ALL 348 | # 349 | 350 | # test1, example.com 351 | dn: cn=test1,dc=example,dc=com 352 | email: test1@example.com 353 | role: Administrator 354 | objectclass: inetOrgPerson 355 | displayname: Test User 1 356 | uid: test1 357 | 358 | # test2, example.com 359 | dn: cn=test2,dc=example,dc=com 360 | email: test2@example.com 361 | email: test2-alias@example.com 362 | role: Employee 363 | objectclass: inetOrgPerson 364 | displayname: Test User 2 365 | uid: test2 366 | 367 | # test3, example.com 368 | dn: cn=test3,dc=example,dc=com 369 | email: test3@example.com 370 | objectclass: inetOrgPerson 371 | displayname: Test User 3 372 | uid: test3 373 | 374 | # search result 375 | search: 2 376 | result: 0 Success 377 | 378 | # numResponses: 4 379 | # numEntries: 3 380 | ".Replace("\r", ""); 381 | 382 | Assert.Equal(expected, output); 383 | } 384 | 385 | [Fact] 386 | public void TestSingleSearchWithStrictBaseDn() 387 | { 388 | string output = ExecuteLdapSearch("\"(objectClass=*)\"", "cn=benutzer4,dc=example,dc=com"); 389 | string expected = @"# extended LDIF 390 | # 391 | # LDAPv3 392 | # base with scope subtree 393 | # filter: (objectClass=*) 394 | # requesting: ALL 395 | # 396 | 397 | # benutzer4, example.com 398 | dn: cn=benutzer4,dc=example,dc=com 399 | email: benutzer4@example.com 400 | objectclass: inetOrgPerson 401 | displayname: Benutzer 4 402 | uid: test4 403 | 404 | # search result 405 | search: 2 406 | result: 0 Success 407 | 408 | # numResponses: 2 409 | # numEntries: 1 410 | ".Replace("\r", ""); 411 | 412 | Assert.Equal(expected, output); 413 | } 414 | 415 | [Fact] 416 | public void TestSingleSearchWithUserThatIsNotAllowedToBind() 417 | { 418 | string output = ExecuteLdapSearch("\"(objectClass=*)\"", "cn=benutzer4,dc=example,dc=com", "cn=OnlyBindUser", "OnlyBindUserPassword"); 419 | string expected = @"# extended LDIF 420 | # 421 | # LDAPv3 422 | # base with scope subtree 423 | # filter: (objectClass=*) 424 | # requesting: ALL 425 | # 426 | 427 | # search result 428 | search: 2 429 | result: 32 No such object 430 | 431 | # numResponses: 1 432 | ".Replace("\r", ""); 433 | 434 | Assert.Equal(expected, output); 435 | } 436 | 437 | [Fact] 438 | public void TestSearchWithInvalidPassword() 439 | { 440 | string output = ExecuteLdapSearch("\"(objectClass=*)\"", "cn=benutzer4,dc=example,dc=com", "cn=OnlyBindUser", "NotACorrectBindUserPassword"); 441 | string expected = @"ldap_bind: Inappropriate authentication (48) 442 | ".Replace("\r", ""); 443 | 444 | Assert.Equal(expected, output); 445 | } 446 | 447 | [Fact] 448 | public void TestSearchWithoutPasswordAndBindUser() 449 | { 450 | string output = ExecuteLdapSearch("\"(objectClass=*)\"", "cn=benutzer4,dc=example,dc=com", null, null); 451 | string expected = @"ldap_sasl_interactive_bind_s: Inappropriate authentication (48) 452 | ".Replace("\r", ""); 453 | 454 | Assert.Equal(expected, output); 455 | } 456 | } 457 | } 458 | -------------------------------------------------------------------------------- /Sample.Tests/Integration/LdapServerFixture.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | 3 | namespace Sample.Tests.Integration 4 | { 5 | public class LdapServerFixture 6 | { 7 | public LdapServerFixture() 8 | { 9 | StartServer(); 10 | } 11 | 12 | private void StartServer() 13 | { 14 | Sample.Program program = new Sample.Program(); 15 | new Thread(async () => 16 | { 17 | Thread.CurrentThread.IsBackground = true; 18 | await Sample.Program.Main(new string[0]); 19 | }).Start(); 20 | Thread.Sleep(1000); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Sample.Tests/Sample.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | all 16 | 17 | 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | all 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Sample/ConsoleLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Gatekeeper.LdapServerLibrary; 3 | 4 | namespace Sample 5 | { 6 | class ConsoleLogger : ILogger 7 | { 8 | public void LogException(Exception e) 9 | { 10 | System.Console.WriteLine(e.ToString()); 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Sample/LdapEventListener.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Threading.Tasks; 6 | using Gatekeeper.LdapServerLibrary; 7 | using Gatekeeper.LdapServerLibrary.Session.Events; 8 | using Gatekeeper.LdapServerLibrary.Session.Replies; 9 | 10 | namespace Sample 11 | { 12 | class LdapEventListener : LdapEvents 13 | { 14 | public override Task OnAuthenticationRequest(ClientContext context, IAuthenticationEvent authenticationEvent) 15 | { 16 | List cnValue = null; 17 | authenticationEvent.Rdn.TryGetValue("cn", out cnValue); 18 | List dcValue = null; 19 | authenticationEvent.Rdn.TryGetValue("dc", out dcValue); 20 | 21 | if (cnValue.Contains("Manager") && dcValue.Contains("example") && dcValue.Contains("com")) 22 | { 23 | return Task.FromResult(true); 24 | } 25 | else if (cnValue.Contains("OnlyBindUser") && authenticationEvent.Password == "OnlyBindUserPassword") 26 | { 27 | return Task.FromResult(true); 28 | } 29 | 30 | return Task.FromResult(false); 31 | } 32 | 33 | public override Task> OnSearchRequest(ClientContext context, ISearchEvent searchEvent) 34 | { 35 | System.Console.WriteLine(System.Convert.ToBase64String(searchEvent.SearchRequest.RawPacket)); 36 | if (context.Rdn["cn"][0] == "OnlyBindUser") 37 | { 38 | return Task.FromResult(new List()); 39 | } 40 | 41 | int? limit = searchEvent.SearchRequest.SizeLimit; 42 | 43 | // Load the user database that queries will be executed against 44 | UserDatabase dbContainer = new UserDatabase(); 45 | IQueryable userDb = dbContainer.GetUserDatabase().AsQueryable(); 46 | 47 | var itemExpression = Expression.Parameter(typeof(UserDatabase.User)); 48 | SearchExpressionBuilder searchExpressionBuilder = new SearchExpressionBuilder(searchEvent); 49 | var conditions = searchExpressionBuilder.Build(searchEvent.SearchRequest.Filter, itemExpression); 50 | var queryLambda = Expression.Lambda>(conditions, itemExpression); 51 | var predicate = queryLambda.Compile(); 52 | 53 | var results = userDb.Where(predicate).ToList(); 54 | 55 | List replies = new List(); 56 | foreach (UserDatabase.User user in results) 57 | { 58 | List attributes = new List(); 59 | SearchResultReply reply = new SearchResultReply( 60 | user.Dn, 61 | attributes 62 | ); 63 | 64 | foreach (KeyValuePair> attribute in user.Attributes) 65 | { 66 | SearchResultReply.Attribute attributeClass = new SearchResultReply.Attribute(attribute.Key, attribute.Value); 67 | attributes.Add(attributeClass); 68 | } 69 | 70 | replies.Add(reply); 71 | } 72 | 73 | return Task.FromResult(replies); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Sample/Program.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Security.Cryptography.X509Certificates; 3 | using System.Threading.Tasks; 4 | using Gatekeeper.LdapServerLibrary; 5 | 6 | namespace Sample 7 | { 8 | public class Program 9 | { 10 | public static async Task Main(string[] args) 11 | { 12 | LdapServer server = new LdapServer 13 | { 14 | Port = 3389, 15 | }; 16 | server.RegisterEventListener(new LdapEventListener()); 17 | server.RegisterLogger(new ConsoleLogger()); 18 | server.RegisterCertificate(new X509Certificate2(GetTlsCertificatePath())); 19 | await server.Start(); 20 | } 21 | 22 | private static string GetTlsCertificatePath() 23 | { 24 | var certificateStream = System.Reflection.Assembly.GetAssembly(typeof(Sample.Program)).GetManifestResourceStream("Sample.example_certificate.pfx"); 25 | string path = Path.GetTempFileName(); 26 | var fileStream = File.Create(path); 27 | certificateStream.Seek(0, SeekOrigin.Begin); 28 | certificateStream.CopyTo(fileStream); 29 | fileStream.Close(); 30 | return path; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Sample/README.md: -------------------------------------------------------------------------------- 1 | # LDAP Server Library Sample 2 | 3 | This sample implements a simple LDAP server using the LDAP Server Library. 4 | 5 | ## Code pointers 6 | 7 | - `Program.cs` 8 | - Startup of the LDAP server and registration of the event listener, and the TLS certificate used for STARTTLS 9 | - `LdapEventListener.cs` 10 | - Contains the callbacks executed by the LDAP Server Library. 11 | - `SearchExpressionBuilder.cs` 12 | - Builds the LINQ queries for the search expressions passed by the server. 13 | - `UserDatabase.cs` 14 | - Contains the UserDatabase that the custom logic in `LdapEventListener.cs` is listening for. 15 | - `ConsoleLogger.cs` 16 | - Logs exceptions from the LDAP server. 17 | 18 | ## Running the server 19 | 20 | ```bash 21 | dotnet run 22 | ``` 23 | 24 | The server will then listen on port 3389. 25 | -------------------------------------------------------------------------------- /Sample/Sample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Sample/SearchExpressionBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | using System.Text.RegularExpressions; 7 | using Gatekeeper.LdapServerLibrary.Session.Events; 8 | using static Gatekeeper.LdapPacketParserLibrary.Models.Operations.Request.SearchRequest; 9 | 10 | namespace Sample 11 | { 12 | internal class SearchExpressionBuilder 13 | { 14 | private readonly ISearchEvent _searchEvent; 15 | 16 | public SearchExpressionBuilder(ISearchEvent searchEvent) 17 | { 18 | _searchEvent = searchEvent; 19 | } 20 | 21 | public Expression Build(IFilterChoice filter, Expression itemExpression) 22 | { 23 | 24 | Expression? filterExpr = null; 25 | switch (filter) 26 | { 27 | case AndFilter af: 28 | filterExpr = BuildAndFilter(af, itemExpression); 29 | break; 30 | case OrFilter of: 31 | filterExpr = BuildOrFilter(of, itemExpression); 32 | break; 33 | case PresentFilter pf: 34 | filterExpr = BuildPresentFilter(pf, itemExpression); 35 | break; 36 | case EqualityMatchFilter eq: 37 | filterExpr = BuildEqualityFilter(eq, itemExpression); 38 | break; 39 | case SubstringFilter sf: 40 | filterExpr = BuildSubstringFilter(sf, itemExpression); 41 | break; 42 | default: 43 | throw new NotImplementedException("Filter for " + filter.GetType() + " is not implemented"); 44 | } 45 | 46 | return BuildWithBaseFilter(filterExpr, itemExpression); 47 | } 48 | 49 | private Expression BuildWithBaseFilter(Expression filterExpr, Expression itemExpr) 50 | { 51 | if (_searchEvent.SearchRequest.BaseObject == "") 52 | { 53 | return filterExpr; 54 | } 55 | else if (_searchEvent.SearchRequest.BaseObject.StartsWith("dc=")) 56 | { 57 | MemberExpression dnExpr = Expression.Property(itemExpr, "Dn"); 58 | MethodCallExpression valueExprEndsWith = Expression.Call(dnExpr, typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) }), Expression.Constant(_searchEvent.SearchRequest.BaseObject)); 59 | 60 | return Expression.And(valueExprEndsWith, filterExpr); 61 | } 62 | else 63 | { 64 | MemberExpression left = Expression.Property(itemExpr, "Dn"); 65 | ConstantExpression right = Expression.Constant(_searchEvent.SearchRequest.BaseObject); 66 | BinaryExpression equalExpr = Expression.Equal(left, right); 67 | 68 | return Expression.And(equalExpr, filterExpr); 69 | } 70 | 71 | } 72 | 73 | private Expression BuildOrFilter(OrFilter filter, Expression itemExpression) 74 | { 75 | List expressions = new List(); 76 | 77 | Expression orFilterExpr = null; 78 | foreach (IFilterChoice subFilter in filter.Filters) 79 | { 80 | Expression subExpr = Build(subFilter, itemExpression); 81 | if (orFilterExpr == null) 82 | { 83 | orFilterExpr = subExpr; 84 | } 85 | else 86 | { 87 | orFilterExpr = Expression.Or(orFilterExpr, subExpr); 88 | } 89 | } 90 | 91 | return orFilterExpr; 92 | } 93 | 94 | private Expression BuildAndFilter(AndFilter filter, Expression itemExpression) 95 | { 96 | List expressions = new List(); 97 | 98 | Expression andFilterExpr = null; 99 | foreach (IFilterChoice subFilter in filter.Filters) 100 | { 101 | Expression subExpr = Build(subFilter, itemExpression); 102 | if (andFilterExpr == null) 103 | { 104 | andFilterExpr = subExpr; 105 | } 106 | else 107 | { 108 | andFilterExpr = Expression.And(andFilterExpr, subExpr); 109 | } 110 | } 111 | 112 | return andFilterExpr; 113 | } 114 | 115 | private Expression BuildPresentFilter(PresentFilter filter, Expression itemExpression) 116 | { 117 | Expression attributeExpr = Expression.Property(itemExpression, "Attributes"); 118 | Expression attributeContainsKey = Expression.Call(attributeExpr, typeof(Dictionary>).GetMethod("ContainsKey", new Type[] { typeof(string) }), Expression.Constant(filter.Value.ToLower())); 119 | 120 | return attributeContainsKey; 121 | } 122 | 123 | private Expression BuildSubstringFilter(SubstringFilter filter, Expression itemExpression) 124 | { 125 | string suppliedRegex = ""; 126 | 127 | if (filter.Initial != null) 128 | { 129 | suppliedRegex = Regex.Escape(filter.Initial); 130 | } 131 | else 132 | { 133 | suppliedRegex = ".*"; 134 | } 135 | 136 | foreach (string anyString in filter.Any) 137 | { 138 | suppliedRegex = suppliedRegex + ".*" + Regex.Escape(anyString) + ".*"; 139 | } 140 | 141 | if (filter.Final != null) 142 | { 143 | suppliedRegex = suppliedRegex + Regex.Escape(filter.Final); 144 | } 145 | else 146 | { 147 | suppliedRegex = suppliedRegex + ".*"; 148 | } 149 | 150 | if (filter.AttributeDesc == "cn") 151 | { 152 | MemberExpression dnProperty = Expression.Property(itemExpression, "Dn"); 153 | string baseObj = (_searchEvent.SearchRequest.BaseObject == "") ? "" : "," + _searchEvent.SearchRequest.BaseObject; 154 | 155 | Regex regex = new Regex("^cn=" + suppliedRegex + Regex.Escape(baseObj) + "$", RegexOptions.Compiled); 156 | ConstantExpression regexConst = Expression.Constant(regex); 157 | 158 | MethodInfo methodInfo = typeof(Regex).GetMethod("IsMatch", new Type[] { typeof(string) }); 159 | Expression[] callExprs = new Expression[] { dnProperty }; 160 | 161 | return Expression.Call(regexConst, methodInfo, callExprs); 162 | } 163 | else 164 | { 165 | Expression attributeExpr = Expression.Property(itemExpression, "Attributes"); 166 | 167 | // Pair to search for 168 | ParameterExpression keyValuePair = Expression.Parameter(typeof(KeyValuePair>), "a"); 169 | 170 | // rsl 171 | ParameterExpression regexStringList = Expression.Parameter(typeof(string), "rsl"); 172 | 173 | // regex.IsMatch(rsl) 174 | Regex regex = new Regex("^" + suppliedRegex + "$", RegexOptions.Compiled); 175 | ConstantExpression regexConst = Expression.Constant(regex); 176 | MethodInfo methodInfo = typeof(Regex).GetMethod("IsMatch", new Type[] { typeof(string) }); 177 | Expression[] callExprs = new Expression[] { regexStringList }; 178 | MethodCallExpression regexMatchExpr = Expression.Call(regexConst, methodInfo, callExprs); 179 | 180 | // {rsl => regex.IsMatch(rsl)} 181 | var regexLambda = Expression.Lambda>(regexMatchExpr, regexStringList); 182 | 183 | // a.Value.Any(rsl => regex.IsMatch(rsl)) 184 | Expression subExprValue = Expression.Property(keyValuePair, "Value"); 185 | MethodInfo regexAnyMethodInfo = typeof(Enumerable).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).First(m => m.Name == "Any" && m.GetParameters().Count() == 2).MakeGenericMethod(typeof(string)); 186 | MethodCallExpression regexAnyCallExpr = Expression.Call(regexAnyMethodInfo, subExprValue, regexLambda); 187 | 188 | // (a.Key == attributeName) 189 | Expression subExprLeftAttributeName = Expression.Property(keyValuePair, "Key"); 190 | Expression subExprRightAttributeName = Expression.Constant(filter.AttributeDesc.ToLower()); 191 | Expression subExprAttributeName = Expression.Equal(subExprLeftAttributeName, subExprRightAttributeName); 192 | 193 | // ((a.Key == attributeName) && a.Value.Any(rsl => regex.IsMatch(rsl))) 194 | Expression attributeExprMatch = Expression.And(subExprAttributeName, regexAnyCallExpr); 195 | 196 | // {a => ((a.Key == attributeName) And a.Value.Any(rsl => regex.IsMatch(rsl)))} 197 | var lambda = Expression.Lambda>, bool>>(attributeExprMatch, keyValuePair); 198 | 199 | MethodInfo anyMethod = typeof(Enumerable).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).First(m => m.Name == "Any" && m.GetParameters().Count() == 2).MakeGenericMethod(typeof(KeyValuePair>)); 200 | return Expression.Call(anyMethod, attributeExpr, lambda); 201 | } 202 | } 203 | 204 | private Expression BuildEqualityFilter(EqualityMatchFilter filter, Expression itemExpression) 205 | { 206 | if (filter.AttributeDesc == "cn") 207 | { 208 | Expression left = Expression.Property(itemExpression, "Dn"); 209 | string baseObj = (_searchEvent.SearchRequest.BaseObject == "") ? "" : "," + _searchEvent.SearchRequest.BaseObject; 210 | Expression right = Expression.Constant("cn=" + filter.AssertionValue + baseObj); 211 | return Expression.Equal(left, right); 212 | } 213 | else 214 | { 215 | Expression attributeExpr = Expression.Property(itemExpression, "Attributes"); 216 | 217 | // Pair to search for 218 | ParameterExpression keyValuePair = Expression.Parameter(typeof(KeyValuePair>), "a"); 219 | 220 | // (a.Key == attributeName) 221 | Expression subExprLeftAttributeName = Expression.Property(keyValuePair, "Key"); 222 | Expression subExprRightAttributeName = Expression.Constant(filter.AttributeDesc.ToLower()); 223 | Expression subExprAttributeName = Expression.Equal(subExprLeftAttributeName, subExprRightAttributeName); 224 | 225 | // a.Value.Contains(attributeValue) 226 | Expression subExprValue = Expression.Property(keyValuePair, "Value"); 227 | Expression subExprContains = Expression.Call(subExprValue, typeof(List).GetMethod("Contains", new Type[] { typeof(string) }), Expression.Constant(filter.AssertionValue)); 228 | 229 | // ((a.Key == attributeName) && a.Value.Contains(attributeValue)) 230 | Expression attributeExprMatch = Expression.And(subExprAttributeName, subExprContains); 231 | 232 | // {a => ((a.Key == attributeName) And a.Value.Contains(attributeValue))} 233 | var lambda = Expression.Lambda>, bool>>(attributeExprMatch, keyValuePair); 234 | 235 | MethodInfo anyMethod = typeof(Enumerable).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).First(m => m.Name == "Any" && m.GetParameters().Count() == 2).MakeGenericMethod(typeof(KeyValuePair>)); 236 | return Expression.Call(anyMethod, attributeExpr, lambda); 237 | } 238 | } 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /Sample/UserDatabase.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Sample 4 | { 5 | internal class UserDatabase 6 | { 7 | private readonly List Users = new List{ 8 | new User{ 9 | Dn = "cn=test1,dc=example,dc=com", 10 | Attributes = new Dictionary>(){ 11 | {"email", new List(){"test1@example.com"}}, 12 | {"role", new List(){"Administrator"}}, 13 | {"objectclass", new List(){"inetOrgPerson"}}, 14 | {"displayname", new List() {"Test User 1"}}, 15 | {"uid", new List() {"test1"}}, 16 | }, 17 | }, 18 | new User{ 19 | Dn = "cn=test2,dc=example,dc=com", 20 | Attributes = new Dictionary>(){ 21 | {"email", new List(){"test2@example.com", "test2-alias@example.com"}}, 22 | {"role", new List(){"Employee"}}, 23 | {"objectclass", new List(){"inetOrgPerson"}}, 24 | {"displayname", new List() {"Test User 2"}}, 25 | {"uid", new List() {"test2"}}, 26 | }, 27 | }, 28 | new User{ 29 | Dn = "cn=test3,dc=example,dc=com", 30 | Attributes = new Dictionary>(){ 31 | {"email", new List(){"test3@example.com"}}, 32 | {"objectclass", new List(){"inetOrgPerson"}}, 33 | {"displayname", new List() {"Test User 3"}}, 34 | {"uid", new List() {"test3"}}, 35 | }, 36 | }, 37 | new User{ 38 | Dn = "cn=benutzer4,dc=example,dc=com", 39 | Attributes = new Dictionary>(){ 40 | {"email", new List(){"benutzer4@example.com"}}, 41 | {"objectclass", new List(){"inetOrgPerson"}}, 42 | {"displayname", new List() {"Benutzer 4"}}, 43 | {"uid", new List() {"test4"}}, 44 | }, 45 | }, 46 | }; 47 | 48 | internal List GetUserDatabase() 49 | { 50 | return Users; 51 | } 52 | 53 | internal class User 54 | { 55 | internal string Dn { get; set; } 56 | internal Dictionary> Attributes { get; set; } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Sample/example_certificate.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Authentick/LdapServerLibrary/95aaef56e34652f53abf7f5b135f1b1dbf9331c2/Sample/example_certificate.pfx --------------------------------------------------------------------------------