File ldap-sebin-0.2.1.obscpio of Package ldap-sebin
07070100000000000041ED00000000000000000000000368C2895000000000000000000000000000000000000000000000001900000000ldap-sebin-0.2.1/.github07070100000001000041ED00000000000000000000000268C2895000000000000000000000000000000000000000000000002300000000ldap-sebin-0.2.1/.github/workflows07070100000002000081A400000000000000000000000168C289500000052B000000000000000000000000000000000000003000000000ldap-sebin-0.2.1/.github/workflows/pipeline.yml---
name: feature tests
# About security when running the tests and NOT exposing
# the secrets to externals. Currently Github Actions does
# NOT expose the secrets if the branch is coming from a forked
# repository.
# See: https://github.blog/2020-08-03-github-actions-improvements-for-fork-and-pull-request-workflows/
# See: https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions
#
# An alternate would be to set, pull_request_target but this takes the CI code
# from master removing the ability to change the code in a PR easily.
#
# Aditionally, since 2021 pull requests from new contributors will not
# trigger workflows automatically but will wait for approval from somebody
# with write access.
# See: https://docs.github.com/en/actions/managing-workflow-runs/approving-workflow-runs-from-public-forks
on:
- pull_request
- push
jobs:
unit-tests:
runs-on: ubuntu-latest
container:
image: registry.suse.com/bci/golang:1.25
options: --user root --privileged
steps:
- uses: actions/checkout@v4
- name: lint
run: |
if [[ ! -z $(gofmt -e -l cmd/ldap-sebin/) ]];
then
echo "Lint failed"
gofmt -e -d cmd/ldap-sebin/
exit 1
fi
- name: test
run: go test -v ./...
07070100000003000081A400000000000000000000000168C2895000000241000000000000000000000000000000000000001C00000000ldap-sebin-0.2.1/.gitignore# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Code coverage profiles and other test artifacts
*.out
coverage.*
*.coverprofile
profile.cov
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
go.work.sum
# env file
.env
# Editor/IDE
# .idea/
# .vscode/
config.yaml
out/
07070100000004000081A400000000000000000000000168C2895000002C4E000000000000000000000000000000000000001900000000ldap-sebin-0.2.1/LICENSE Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 José Gómez
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
07070100000005000081A400000000000000000000000168C28950000000CB000000000000000000000000000000000000001A00000000ldap-sebin-0.2.1/Makefilebuild:
mkdir -p out/bin/
go build -o out/bin/ldap-sebin ./cmd/ldap-sebin/
mod-tidy:
go mod tidy
test:
go test -v ./cmd/...
go test -v ./internal/...
fmt:
go fmt ./cmd/...
go fmt ./internal/...
07070100000006000081A400000000000000000000000168C289500000002F000000000000000000000000000000000000001B00000000ldap-sebin-0.2.1/README.md# ldap-sebin
LDAP Search & Bind middleware
07070100000007000041ED00000000000000000000000368C2895000000000000000000000000000000000000000000000001500000000ldap-sebin-0.2.1/cmd07070100000008000041ED00000000000000000000000268C2895000000000000000000000000000000000000000000000002000000000ldap-sebin-0.2.1/cmd/ldap-sebin07070100000009000081A400000000000000000000000168C28950000015D2000000000000000000000000000000000000002800000000ldap-sebin-0.2.1/cmd/ldap-sebin/main.gopackage main
import (
"fmt"
"log"
"net"
"os"
"os/signal"
"syscall"
"errors"
"flag"
"github.com/josegomezr/ldap-sebin/internal/handler"
"github.com/merlinz01/ldapserver"
"gopkg.in/yaml.v3"
"strconv"
"sync"
)
type Cfg struct {
Verbose bool `yaml:"verbose"`
Upstream string `yaml:"upstream-server-url"`
ListenAddr string `yaml:"listen-address"`
ListenPort string `yaml:"listen-port"`
Certificate string `yaml:"certificate"`
Key string `yaml:"key"`
BaseDn string `yaml:"base-dn"`
FilterTemplate string `yaml:"filter-template"`
AllowedBindDn string `yaml:"allowed-bind-dn"`
}
func newHandler(cfg *Cfg) *handler.Handler {
return &handler.Handler{
AllowedBindDn: cfg.AllowedBindDn,
Verbose: cfg.Verbose,
Sessions: make(map[string]handler.Session),
LdapUrl: cfg.Upstream,
BaseDn: cfg.BaseDn,
FilterTemplate: cfg.FilterTemplate,
Mutex: &sync.Mutex{},
}
}
func newServer(cfg *Cfg) *ldapserver.LDAPServer {
handler := newHandler(cfg)
return ldapserver.NewLDAPServer(handler)
}
var ReadFile func(string) ([]byte, error) = os.ReadFile
var ErrBadConfigFile error = errors.New("Bad config file")
var ErrMissingRequired error = errors.New("Bad config file")
func enrichConfigFromFile(path string, cfg *Cfg) error {
data, err := ReadFile(path)
if err != nil {
return errors.Join(ErrBadConfigFile, err)
}
err = yaml.Unmarshal([]byte(data), cfg)
if err != nil {
return errors.Join(ErrBadConfigFile, err)
}
return nil
}
func enrichConfigFromEnv(cfg *Cfg) {
if val, found := os.LookupEnv("LDAP_SEBIN_UPSTREAM_SERVER_URL"); found {
if val == "" {
log.Printf("Ignoring empty LDAP_SEBIN_UPSTREAM_SERVER_URL value %q", val)
} else {
cfg.Upstream = val
}
}
if val, found := os.LookupEnv("LDAP_SEBIN_LISTEN_ADDRESS"); found {
if val == "" {
log.Printf("Ignoring empty LDAP_SEBIN_LISTEN_ADDRESS value %q", val)
} else {
cfg.ListenAddr = val
}
}
if val, found := os.LookupEnv("LDAP_SEBIN_CERTIFICATE"); found {
if val == "" {
log.Printf("Ignoring empty LDAP_SEBIN_CERTIFICATE value %q", val)
} else {
cfg.Certificate = val
}
}
if val, found := os.LookupEnv("LDAP_SEBIN_KEY"); found {
if val == "" {
log.Printf("Ignoring empty LDAP_SEBIN_KEY value %q", val)
} else {
cfg.Key = val
}
}
if val, found := os.LookupEnv("LDAP_SEBIN_BASE_DN"); found {
if val == "" {
log.Printf("Ignoring empty LDAP_SEBIN_BASE_DN value %q", val)
} else {
cfg.BaseDn = val
}
}
if val, found := os.LookupEnv("LDAP_SEBIN_FILTER_TEMPLATE"); found {
if val == "" {
log.Printf("Ignoring empty LDAP_SEBIN_FILTER_TEMPLATE value %q", val)
} else {
cfg.FilterTemplate = val
}
}
if val, found := os.LookupEnv("LDAP_SEBIN_LISTEN_PORT"); found {
if val == "" {
log.Printf("Ignoring empty LDAP_SEBIN_LISTEN_PORT value %q", val)
} else {
if _, err := strconv.Atoi(val); err == nil {
cfg.ListenPort = val
} else {
log.Printf("Ignoring invalid LDAP_SEBIN_LISTEN_PORT value %q", val)
}
}
}
if val, found := os.LookupEnv("LDAP_SEBIN_VERBOSE"); found {
if val == "" {
log.Printf("Ignoring empty LDAP_SEBIN_VERBOSE value")
} else {
if boolval, err := strconv.ParseBool(val); err == nil {
cfg.Verbose = boolval
} else {
log.Printf("Ignoring invalid LDAP_SEBIN_VERBOSE value %q", val)
}
}
}
}
func validateCfg(cfg *Cfg) error {
if cfg.Upstream == "" || cfg.BaseDn == "" {
return errors.Join(ErrMissingRequired, fmt.Errorf("Incomplete upstream configuration."))
}
return nil
}
var (
Version = "dev"
CommitHash = "n/a"
BuildTimestamp = "n/a" // If we wanna make it reproduceable, this should be commit date
)
func main() {
var nFlag = flag.Bool("v", false, "version")
flag.Parse()
if *nFlag {
fmt.Printf("ldap-sebin/%s\nCommit Hash: %s\nCommit Date: %s", Version, CommitHash, BuildTimestamp)
os.Exit(0)
}
cfg := &Cfg{}
if err := enrichConfigFromFile("./config.yaml", cfg); err != nil {
log.Printf("error reading config file: %+v. IGNORING", err)
}
enrichConfigFromEnv(cfg)
if err := validateCfg(cfg); err != nil {
log.Fatalf("Invalid config: %s", err)
}
if cfg.Verbose {
log.Printf("Parsed configuration")
log.Printf("---")
enc := yaml.NewEncoder(os.Stdout)
enc.Encode(*cfg)
log.Printf("---")
}
s := newServer(cfg)
listenAddr := cfg.ListenAddr
if listenAddr == "" {
listenAddr = "localhost"
}
var srvErr error
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
go func() {
<-signals
fmt.Println()
log.Println("Shutting down.")
s.Shutdown()
}()
// TODO: make this prettier on the validation fn maybe a bool fn "tls
// enabled" on the config struct can make it easier.
listenFunc := s.ListenAndServe
var listenPort string
if !(cfg.Certificate == "" || cfg.Key == "") {
err := s.SetupTLS(cfg.Certificate, cfg.Key)
if err != nil {
log.Fatalf("TLS configuration failed: %s", err)
}
listenFunc = s.ListenAndServeTLS
if cfg.ListenPort != "" {
listenPort = cfg.ListenPort
} else {
listenPort = "636"
}
} else {
if cfg.ListenPort != "" {
listenPort = cfg.ListenPort
} else {
listenPort = "389"
}
log.Println("No certificate and/or key configured. Listening for plain text connections. This is NOT secure.")
}
serverAddr := net.JoinHostPort(listenAddr, listenPort)
log.Printf("Listening to %s", serverAddr)
srvErr = listenFunc(serverAddr)
if srvErr != nil {
log.Fatalf("Failed to start LDAP server: %s", srvErr)
}
}
0707010000000A000081A400000000000000000000000168C2895000001A2B000000000000000000000000000000000000002D00000000ldap-sebin-0.2.1/cmd/ldap-sebin/main_test.gopackage main
import (
"fmt"
ldap "github.com/go-ldap/ldap/v3"
"github.com/merlinz01/ldapserver"
"log"
"strings"
"testing"
"time"
)
var upstreamAddr = "127.254.1.1:3389"
var subjectAddr = "127.0.1.1:3389"
var upstreamServerUrl = "ldap://" + upstreamAddr
func fakeCfg() *Cfg {
return &Cfg{
Verbose: testing.Verbose(),
Upstream: upstreamServerUrl,
AllowedBindDn: "ou=Filterable OU,dc=other,dc=org",
ListenAddr: "",
ListenPort: "",
BaseDn: "ou=Translated Users,dc=example,dc=org",
FilterTemplate: "(equivalentUsername=$1)",
}
}
type fakeUpstreamHandler struct {
ldapserver.BaseHandler
baseDN string
searchResults []string
}
func (h fakeUpstreamHandler) Bind(conn *ldapserver.Conn, msg *ldapserver.Message, req *ldapserver.BindRequest) {
bindDN := req.Name
var result *ldapserver.Result
if bindDN == fmt.Sprintf("cn=AlwaysCorrect CN,%s", h.baseDN) {
result = ldapserver.ResultSuccess.AsResult("SUCCESS!")
} else {
result = ldapserver.ResultInvalidCredentials.AsResult("Failed auth")
}
conn.SendResult(msg.MessageID, nil, ldapserver.TypeBindResponseOp, result)
}
func makeSearchEntry(uid, base string) *ldapserver.SearchResultEntry {
cn := fmt.Sprintf("cn=%s CN", uid)
return &ldapserver.SearchResultEntry{
ObjectName: fmt.Sprintf("%s,%s", cn, base),
Attributes: []ldapserver.Attribute{
{Description: "cn", Values: []string{cn}},
{Description: "uid", Values: []string{uid}},
{Description: "givenname", Values: []string{fmt.Sprintf("Given Name %s", uid)}},
{Description: "sn", Values: []string{fmt.Sprintf("Last Name %s", uid)}},
},
}
}
func (h fakeUpstreamHandler) Search(conn *ldapserver.Conn, msg *ldapserver.Message, req *ldapserver.SearchRequest) {
if strings.HasSuffix(req.BaseObject, h.baseDN) {
for _, entry := range h.searchResults {
conn.SendResult(
msg.MessageID,
nil,
ldapserver.TypeSearchResultEntryOp,
makeSearchEntry(entry, h.baseDN),
)
}
}
conn.SendResult(msg.MessageID, nil, ldapserver.TypeSearchResultDoneOp, ldapserver.ResultSuccess.AsResult(""))
}
func shutdown(s *ldapserver.LDAPServer, name string) {
if testing.Verbose() {
log.Println("Stopping", name)
}
s.Shutdown()
}
func listen(s *ldapserver.LDAPServer, name, addr string, ready chan bool) {
if testing.Verbose() {
log.Println("Starting", name)
}
go func() {
time.Sleep(1 * time.Millisecond)
ready <- true
}()
s.ListenAndServe(addr)
}
func withServer(t *testing.T, handler ldapserver.Handler, fn func(*ldap.Conn)) {
t.Helper()
ready := make(chan bool, 1)
upstream := ldapserver.NewLDAPServer(handler)
go listen(upstream, "upstream", upstreamAddr, ready)
<-ready
defer shutdown(upstream, "upstream")
s := newServer(fakeCfg())
go listen(s, "local", subjectAddr, ready)
<-ready
defer shutdown(s, "local")
conn, err := ldap.DialURL("ldap://" + subjectAddr)
if err != nil {
t.Fatalf("Failed: %s", err)
}
fn(conn)
}
func TestSearchNoResults(t *testing.T) {
handler := &fakeUpstreamHandler{
baseDN: "dc=example,dc=org",
}
withServer(t, handler, func(conn *ldap.Conn) {
err := conn.Bind("uid=random,ou=Filterable OU,dc=other,dc=org", "password")
if err == nil {
t.Fatalf("expected failure")
}
if !ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
t.Fatalf("Expected LDAPResultNoSuchObject, got=%q", err)
}
})
}
func TestSearchResultsBadPW(t *testing.T) {
handler := &fakeUpstreamHandler{
baseDN: "dc=example,dc=org",
searchResults: []string{"random"},
}
withServer(t, handler, func(conn *ldap.Conn) {
err := conn.Bind("uid=random,ou=Filterable OU,dc=other,dc=org", "password")
if err == nil {
t.Fatalf("expected failure")
}
if !ldap.IsErrorWithCode(err, ldap.LDAPResultInvalidCredentials) {
t.Fatalf("Expected LDAPResultNoSuchObject, got=%q", err)
}
})
}
func TestSearchOutsideOfAllowedDN(t *testing.T) {
handler := &fakeUpstreamHandler{
baseDN: "ou=Translated Users,dc=example,dc=org",
}
withServer(t, handler, func(conn *ldap.Conn) {
err := conn.Bind("uid=who-cares-this-has-to-fail,ou=NotYourOU,dc=wooooooo,dc=org", "password")
if err == nil {
t.Fatalf("expected failure")
}
if !ldap.IsErrorWithCode(err, ldap.LDAPResultInsufficientAccessRights) {
t.Fatalf("Expected LDAPResultInsufficientAccessRights, got=%q", err)
}
})
}
func TestSearchResultsCorrectPW(t *testing.T) {
handler := &fakeUpstreamHandler{
baseDN: "ou=Translated Users,dc=example,dc=org",
searchResults: []string{"AlwaysCorrect"},
}
withServer(t, handler, func(conn *ldap.Conn) {
err := conn.Bind("uid=this-must-work,ou=Filterable OU,dc=other,dc=org", "password")
if err != nil {
t.Fatalf("failed: %s", err)
}
})
}
func TestConfigFileEmpty(t *testing.T) {
orig := ReadFile
defer func() { ReadFile = orig }()
ReadFile = func(string) ([]byte, error) {
return []byte("---"), nil
}
cfg := &Cfg{}
err := enrichConfigFromFile("", cfg)
if err != nil {
t.Fatalf("failed: %s", err)
}
}
func TestConfigFileRequired(t *testing.T) {
orig := ReadFile
defer func() { ReadFile = orig }()
ReadFile = func(string) ([]byte, error) {
return []byte(
"---" + "\n" +
`upstream-server-url: ldap://your-ldap-server.example.com` + "\n" +
`base-dn: "ou=Fun User Accounts,dc=company,dc=tld"` + "\n" +
`...` + "\n",
), nil
}
cfg := &Cfg{}
err := enrichConfigFromFile("", cfg)
if err != nil {
t.Fatalf("failed: %s", err)
}
if cfg.Upstream != "ldap://your-ldap-server.example.com" {
t.Fatalf("failed pulling cfg from yaml file. got=%q", cfg.Upstream)
}
if cfg.BaseDn != "ou=Fun User Accounts,dc=company,dc=tld" {
t.Fatalf("failed pulling cfg from yaml file. got=%q", cfg.BaseDn)
}
}
func TestConfigEnvs(t *testing.T) {
cfg := &Cfg{}
enrichConfigFromEnv(cfg)
if cfg.Upstream != "" {
t.Fatalf("failed pulling cfg from yaml file. got=%q", cfg.Upstream)
}
if cfg.BaseDn != "" {
t.Fatalf("failed pulling cfg from yaml file. got=%q", cfg.BaseDn)
}
}
func TestValidateCfg(t *testing.T) {
cfgs := []struct {
cfg Cfg
shouldError bool
}{
{
cfg: Cfg{
Upstream: "",
BaseDn: "",
},
shouldError: true,
},
{
cfg: Cfg{
Upstream: "ldap://something",
BaseDn: "",
},
shouldError: true,
},
{
cfg: Cfg{
Upstream: "ldap://something",
BaseDn: "dc=a,dc=b",
},
shouldError: false,
},
}
for _, expectation := range cfgs {
if err := validateCfg(&expectation.cfg); (err == nil) == expectation.shouldError {
if expectation.shouldError {
t.Fatalf("Failed, expected error: %+v", expectation.cfg)
} else {
t.Fatalf("Failed, unexpected error: %+v", expectation.cfg)
}
}
}
}
0707010000000B000081A400000000000000000000000168C289500000021A000000000000000000000000000000000000002500000000ldap-sebin-0.2.1/config.example.yaml---
# LDAP URI to forward requests to
upstream-server-url: ldaps://your-ldap-server.example.com
# address or name to bind on (optional, defaults to localhost)
listen-address: ipv6-localhost
# port to bind on (optional, defaults to 389 if certificate/key are not set, else 636)
listen-port: 3389
# certificate and private key to enable TLS listener (optional, defaults to plain text listener)
certificate: /etc/ssl/ldap.crt
key: /etc/ssl/ldap.key
base-dn: "ou=Fun User Accounts,dc=company,dc=tld"
filter-template: "(|(customUsername=$1))"
0707010000000C000081A400000000000000000000000168C28950000001A5000000000000000000000000000000000000001800000000ldap-sebin-0.2.1/go.modmodule github.com/josegomezr/ldap-sebin
go 1.23.0
require (
github.com/go-ldap/ldap/v3 v3.4.11
github.com/merlinz01/ldapserver v0.0.16
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
github.com/google/uuid v1.6.0 // indirect
golang.org/x/crypto v0.36.0 // indirect
)
0707010000000D000081A400000000000000000000000168C2895000000E4E000000000000000000000000000000000000001800000000ldap-sebin-0.2.1/go.sumgithub.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 h1:BP4M0CvQ4S3TGls2FvczZtj5Re/2ZzkV9VwqPHH/3Bo=
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-ldap/ldap/v3 v3.4.11 h1:4k0Yxweg+a3OyBLjdYn5OKglv18JNvfDykSoI8bW0gU=
github.com/go-ldap/ldap/v3 v3.4.11/go.mod h1:bY7t0FLK8OAVpp/vV6sSlpz3EQDGcQwc8pF0ujLgKvM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo=
github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM=
github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg=
github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo=
github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o=
github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg=
github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8=
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
github.com/merlinz01/ldapserver v0.0.16 h1:n1PUidCbTp4Q0whEGdxadJeJS++9WZQWpKkHdx4YRq4=
github.com/merlinz01/ldapserver v0.0.16/go.mod h1:HdJaCmgx5Pz4aQzjDH4Byojdl5Ztm7BotwxDRAI/FY8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
0707010000000E000041ED00000000000000000000000368C2895000000000000000000000000000000000000000000000001A00000000ldap-sebin-0.2.1/internal0707010000000F000041ED00000000000000000000000268C2895000000000000000000000000000000000000000000000002200000000ldap-sebin-0.2.1/internal/handler07070100000010000081A400000000000000000000000168C2895000000F55000000000000000000000000000000000000002D00000000ldap-sebin-0.2.1/internal/handler/handler.gopackage handler
// very shameful copy of beryju.io/ldap proxy example
import (
"crypto/sha1"
"fmt"
"log"
"strings"
"sync"
"github.com/go-ldap/ldap/v3"
"github.com/merlinz01/ldapserver"
)
type Handler struct {
ldapserver.BaseHandler
Verbose bool
AllowedBindDn string
Sessions map[string]Session
LdapUrl string
BaseDn string
FilterTemplate string
Mutex *sync.Mutex
}
type Session struct {
id string
ldap *ldap.Conn
}
func (h Handler) dial() (*ldap.Conn, error) {
if h.Verbose {
fmt.Printf("Starting connection to %s\n", h.LdapUrl)
}
return ldap.DialURL(h.LdapUrl)
}
func (h Handler) getSession(conn *ldapserver.Conn) (Session, error) {
id := connID(conn)
h.Mutex.Lock()
s, ok := h.Sessions[id] // use server connection if it exists
h.Mutex.Unlock()
if !ok { // open a new server connection if not
l, err := h.dial()
if err != nil {
if h.Verbose {
fmt.Printf("ERR: %s\n", err.Error())
}
return Session{}, err
}
// l.Debug = true
s = Session{id: id, ldap: l}
h.Mutex.Lock()
h.Sessions[s.id] = s
h.Mutex.Unlock()
}
return s, nil
}
func getFirstDNComponent(bindDN string) string {
searchFilter, _, _ := strings.Cut(bindDN, ",")
_, searchFilter, _ = strings.Cut(searchFilter, "=")
return searchFilter
}
func (h Handler) Bind(conn *ldapserver.Conn, msg *ldapserver.Message, req *ldapserver.BindRequest) {
result := ldapserver.ResultOperationsError.AsResult("Unknown Error")
defer func() {
if h.Verbose {
fmt.Printf("Bind result: %+v\n", result)
}
conn.SendResult(msg.MessageID, nil, ldapserver.TypeBindResponseOp, result)
}()
if !strings.HasSuffix(req.Name, h.AllowedBindDn) {
result = ldapserver.ResultInsufficientAccessRights.AsResult("hey! that's trespassing")
return
}
if req.Name == "" {
if h.Verbose {
log.Printf("Invalid bind with empty DN")
}
result = ldapserver.ResultInvalidCredentials.AsResult("Bind with empty DN is not allowed.")
return
}
searchFilter := strings.ReplaceAll(h.FilterTemplate, "$1", getFirstDNComponent(req.Name))
if h.Verbose {
log.Printf("input bind-dn: %+v\n", req.Name)
log.Printf("search-filter: %+v\n", searchFilter)
}
search := ldap.NewSearchRequest(
h.BaseDn,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 5, 0, false,
searchFilter,
[]string{"dn"},
nil,
)
s, err := h.getSession(conn)
if err != nil {
result = ldapserver.ResultOperationsError.AsResult("Upstream connection error")
return
}
if h.Verbose {
log.Printf("Performing search: %+v ", search)
}
sr, err := s.ldap.Search(search)
if err != nil {
result = ldapserver.ResultOperationsError.AsResult(fmt.Sprintf("error: %s", err))
return
}
if len(sr.Entries) == 0 {
result = ldapserver.ResultNoSuchObject.AsResult("Not found")
return
}
bindSimplePw := req.Credentials.(string)
for _, entry := range sr.Entries {
newDn := entry.DN
if h.Verbose {
log.Printf("Search matched DN: %+v ", newDn)
}
if err := s.ldap.Bind(newDn, bindSimplePw); err != nil {
if h.Verbose {
log.Printf("Failed auth with %s, continuing\n", newDn)
}
continue
}
if h.Verbose {
log.Printf("Auth succeeded with: %+v ", newDn)
}
result = ldapserver.ResultSuccess.AsResult("Success")
return
}
if h.Verbose {
log.Printf("Failed auth against all matched entries")
}
result = ldapserver.ResultInvalidCredentials.AsResult("Could not bind with the given password")
return
}
func (h Handler) Search(conn *ldapserver.Conn, msg *ldapserver.Message, req *ldapserver.SearchRequest) {
conn.SendResult(msg.MessageID, nil, ldapserver.TypeSearchResultDoneOp,
ldapserver.ResultSuccess.AsResult("This is a no-op, no search was actually done."))
}
func connID(conn *ldapserver.Conn) string {
h := sha1.New()
h.Write([]byte(conn.LocalAddr().String() + conn.RemoteAddr().String()))
sha := fmt.Sprintf("% x", h.Sum(nil))
return string(sha)
}
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!73 blocks