Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: add support for authorization in OIDC #10

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/resources/hosts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
127.0.0.1 public.example.com
127.0.0.1 app1.example.com
127.0.0.1 app2.example.com
127.0.0.1 auth.example.com # Used for the redirect callback ending the OAuth2 transaction
127.0.0.1 app3.example.com
127.0.0.1 dex.example.com # An OIDC server implementation
10 changes: 10 additions & 0 deletions .github/scripts/build_and_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/bash

go run .github/scripts/prepare/main.go
sleep 20

go test tests/*.go
result=$?

go run .github/scripts/cleanup/main.go
exit $result
18 changes: 17 additions & 1 deletion .github/scripts/cleanup/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,23 @@ func execute(command string, arg ...string) error {
}

func cleanup() error {
err := execute("docker-compose", "down", "-v")
err := execute("docker-compose", "logs", "spoe")
if err != nil {
return err
}
err = execute("docker-compose", "logs", "haproxy")
if err != nil {
return err
}
err = execute("docker-compose", "logs", "dex")
if err != nil {
return err
}
err = execute("docker-compose", "logs", "ldap")
if err != nil {
return err
}
err = execute("docker-compose", "down", "-v")
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/build_and_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ jobs:
chromedriver --url-base=/wd/hub &
sudo Xvfb -ac :99 -screen 0 1280x1024x24 > /dev/null 2>&1 & # optional
- run: cat .github/resources/hosts | sudo tee -a /etc/hosts
- run: go run .github/scripts/prepare/main.go && sleep 20 && go test tests/*.go && go run .github/scripts/cleanup/main.go
- run: .github/scripts/build_and_test.sh
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
haproxy-ldap-auth

.vscode/
.config.yml
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Now, add the two following lines to your /etc/hosts to fake the domains:
127.0.0.1 public.example.com
127.0.0.1 app1.example.com
127.0.0.1 app2.example.com
127.0.0.1 auth.example.com # Used for the redirect callback ending the OAuth2 transaction
127.0.0.1 app3.example.com
127.0.0.1 dex.example.com # An OIDC server implementation

And then run
Expand All @@ -39,9 +39,13 @@ Now you can test the following commands
curl -u "john:badpassword" http://app1.example.com:9080/

# This domain is protected by OpenID Connect. This should redirect you to the authorization server where you can provide the same credentials as above.
Visit http://app2.example.com:9080/ in a browser
# Visit http://app2.example.com:9080/ or http://app3.example.com:9080/ in a browser. They are two different applications
in order to test SSO. Note: Dex seems not to provide this feature though but Okta does for instance.

# Once authenticated and consent granted, your redirected to app2.
# Once authenticated and consent granted, your redirected to the app.

# One can also visit http://app2.example.com:9080/secret.html or http://app3.example.com:9080/secret.html to verify the
user is properly redirected as requested before authentication.

Trying to visit the website protected by LDAP in a browser will display a basic auth form that you should fill
before being granted the rights to visit the page. With OpenID Connect, you should be redirected to the Dex
Expand Down
66 changes: 38 additions & 28 deletions cmd/haproxy-spoe-auth/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,34 +41,44 @@ func main() {

logrus.SetLevel(LogLevelFromLogString(viper.GetString("server.log_level")))

ldapAuthentifier := auth.NewLDAPAuthenticator(auth.LDAPConnectionDetails{
Hostname: viper.GetString("ldap.hostname"),
Port: viper.GetInt("ldap.port"),
UserDN: viper.GetString("ldap.user_dn"),
Password: viper.GetString("ldap.password"),
BaseDN: viper.GetString("ldap.base_dn"),
UserFilter: viper.GetString("ldap.user_filter"),
})
authenticators := map[string]auth.Authenticator{}

oidcAuthenticator := auth.NewOIDCAuthenticator(auth.OIDCAuthenticatorOptions{
OAuth2AuthenticatorOptions: auth.OAuth2AuthenticatorOptions{
ClientID: viper.GetString("oidc.client_id"),
ClientSecret: viper.GetString("oidc.client_secret"),
RedirectURL: viper.GetString("oidc.redirect_url"),
CallbackAddr: viper.GetString("oidc.callback_addr"),
CookieName: viper.GetString("oidc.cookie_name"),
CookieDomain: viper.GetString("oidc.cookie_domain"),
CookieSecure: viper.GetBool("oidc.cookie_secure"),
CookieTTL: viper.GetDuration("oidc.cookie_ttl_seconds") * time.Second,
SignatureSecret: viper.GetString("oidc.signature_secret"),
Scopes: viper.GetStringSlice("oidc.scopes"),
},
ProviderURL: viper.GetString("oidc.provider_url"),
EncryptionSecret: viper.GetString("oidc.encryption_secret"),
})
if viper.IsSet("ldap") {
ldapAuthentifier := auth.NewLDAPAuthenticator(auth.LDAPConnectionDetails{
Hostname: viper.GetString("ldap.hostname"),
Port: viper.GetInt("ldap.port"),
UserDN: viper.GetString("ldap.user_dn"),
Password: viper.GetString("ldap.password"),
BaseDN: viper.GetString("ldap.base_dn"),
UserFilter: viper.GetString("ldap.user_filter"),
})
authenticators["try-auth-ldap"] = ldapAuthentifier
}

if viper.IsSet("oidc") {
// TODO: watch the config file to update the list of clients dynamically
var clientsConfig map[string]auth.OIDCClientConfig
err := viper.UnmarshalKey("oidc.clients", &clientsConfig)
if err != nil {
logrus.Panic(err)
}

oidcAuthenticator := auth.NewOIDCAuthenticator(auth.OIDCAuthenticatorOptions{
OAuth2AuthenticatorOptions: auth.OAuth2AuthenticatorOptions{
RedirectCallbackPath: viper.GetString("oidc.oauth2_callback_path"),
LogoutPath: viper.GetString("oidc.oauth2_logout_path"),
CallbackAddr: viper.GetString("oidc.callback_addr"),
CookieName: viper.GetString("oidc.cookie_name"),
CookieSecure: viper.GetBool("oidc.cookie_secure"),
CookieTTL: viper.GetDuration("oidc.cookie_ttl_seconds") * time.Second,
SignatureSecret: viper.GetString("oidc.signature_secret"),
ClientsStore: auth.NewStaticOIDCClientStore(clientsConfig),
},
ProviderURL: viper.GetString("oidc.provider_url"),
EncryptionSecret: viper.GetString("oidc.encryption_secret"),
})
authenticators["try-auth-oidc"] = oidcAuthenticator
}

agent.StartAgent(viper.GetString("server.addr"), map[string]auth.Authenticator{
"try-auth-ldap": ldapAuthentifier,
"try-auth-oidc": oidcAuthenticator,
})
agent.StartAgent(viper.GetString("server.addr"), authenticators)
}
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ services:
depends_on:
- spoe
- dex
- protected-backend
- unprotected-backend
- unauthorized-backend
networks:
haproxy-spoe-net:
aliases:
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ require (
github.com/spf13/viper v1.8.1
github.com/stretchr/testify v1.7.0
github.com/tebeka/selenium v0.9.9
github.com/vmihailenco/msgpack/v5 v5.3.4
golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e // indirect
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect
gopkg.in/ldap.v3 v3.0.3
)
7 changes: 6 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,10 @@ github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tebeka/selenium v0.9.9 h1:cNziB+etNgyH/7KlNI7RMC1ua5aH1+5wUlFQyzeMh+w=
github.com/tebeka/selenium v0.9.9/go.mod h1:5Fr8+pUvU6B1OiPfkdCKdXZyr5znvVkxuPd0NOdZCQc=
github.com/vmihailenco/msgpack/v5 v5.3.4 h1:qMKAwOV+meBw2Y8k9cVwAy7qErtYCwBzZ2ellBfvnqc=
github.com/vmihailenco/msgpack/v5 v5.3.4/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
Expand Down Expand Up @@ -449,8 +453,9 @@ golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e h1:WUoyKPm6nCo1BnNUvPGnFG3T5DUVem42yDJZZ4CNxMA=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand Down
27 changes: 17 additions & 10 deletions internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,24 @@ var AuthenticatedMessage = spoe.ActionSetVar{
}

// StartAgent start the agent
func StartAgent(interfaceAddr string, authentifiers map[string]auth.Authenticator) {
func StartAgent(interfaceAddr string, authenticators map[string]auth.Authenticator) {
agent := spoe.New(func(messages *spoe.MessageIterator) ([]spoe.Action, error) {
var actions []spoe.Action

var authenticated bool = false
var hasError bool = false

for messages.Next() {
msg := messages.Message
logrus.Debugf("New message with name %s received", msg.Name)
logrus.Debugf("new message with name %s received", msg.Name)

authentifier, ok := authentifiers[msg.Name]
authentifier, ok := authenticators[msg.Name]
if ok {
isAuthenticated, replyActions, err := authentifier.Authenticate(&msg)
if err != nil {
logrus.Errorf("Unable to authenticate user: %v", err)
continue
logrus.Errorf("unable to authenticate user: %v", err)
hasError = true
break
}
actions = append(actions, replyActions...)

Expand All @@ -47,16 +50,20 @@ func StartAgent(interfaceAddr string, authentifiers map[string]auth.Authenticato
}
}

if authenticated {
actions = append(actions, AuthenticatedMessage)
if hasError {
actions = append(actions, auth.BuildHasErrorMessage())
} else {
actions = append(actions, NotAuthenticatedMessage)
}
if authenticated {
actions = append(actions, AuthenticatedMessage)
} else {
actions = append(actions, NotAuthenticatedMessage)
}

}
return actions, nil
})

logrus.Infof("Agent starting and listening on %s", interfaceAddr)
logrus.Infof("agent starting and listening on %s with %d authenticators", interfaceAddr, len(authenticators))
if err := agent.ListenAndServe(interfaceAddr); err != nil {
log.Fatal(err)
}
Expand Down
14 changes: 10 additions & 4 deletions internal/auth/authenticator_ldap.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func verifyCredentials(ldapDetails *LDAPConnectionDetails, username, password st

sr, err := l.Search(searchRequest)
if err != nil {
return err
return fmt.Errorf("search request failed: %w", err)
}

if len(sr.Entries) == 0 {
Expand All @@ -72,7 +72,10 @@ func verifyCredentials(ldapDetails *LDAPConnectionDetails, username, password st
// Bind as the user to verify their password
err = l.Bind(userdn, password)
if err != nil {
return err
if e, ok := err.(*ldap.Error); ok && e.ResultCode == 49 { // Invalid credentials
return ErrWrongCredentials
}
return fmt.Errorf("unable to bind user: %w", err)
}

return nil
Expand Down Expand Up @@ -105,7 +108,7 @@ func (la *LDAPAuthenticator) Authenticate(msg *spoe.Message) (bool, []spoe.Actio
var ok bool
authorization, ok = arg.Value.(string)
if !ok {
return false, nil, ErrNoCredential
return false, nil, nil
}
}
}
Expand All @@ -125,7 +128,10 @@ func (la *LDAPAuthenticator) Authenticate(msg *spoe.Message) (bool, []spoe.Actio

if err != nil {
if err == ErrUserDoesntExist {
logrus.Debugf("User %s does not exist", username)
logrus.Debugf("user %s does not exist", username)
return false, nil, nil
} else if err == ErrWrongCredentials {
logrus.Debug("wrong credentials")
return false, nil, nil
}
return false, nil, err
Expand Down
Loading