clean up LDAP connector

* Remove some unlikely to be used fields to help configurability.
  * Combined "serverHost" and "serverPort" into "host"
  * Remove "timeout" (just default to 30 seconds).
  * Remove "maxIdleConn" will add it back if users feel the need
    to control the number of cached connections.
  * Remove "trustedEmailProvider" (just always trust).
  * Remove "skipCertVerification" you can't make this connector
    ingore TLS errors.
* Fix configs that don't search before bind (previously broken).
* Add more examples to Documentation
* Refactor LDAPPool Acquire() and Put() into a Do() function which
  always does the flow correctly.
* Added more comments and renamed some functions.
* Moved methods on LDAPIdentityProvider to the LDAPConnector
This commit is contained in:
Eric Chiang 2016-06-21 16:41:04 -07:00 committed by Eric Chiang
parent 3b8d704c9c
commit 5a78e89807
9 changed files with 356 additions and 308 deletions

View file

@ -12,6 +12,7 @@ go:
env:
- DEX_TEST_DSN="postgres://postgres@127.0.0.1:15432/postgres?sslmode=disable" ISOLATED=true
DEX_TEST_LDAP_HOST="tlstest.local:1389"
DEX_TEST_LDAPS_HOST="tlstest.local:1636"
DEX_TEST_LDAP_BINDNAME="cn=admin,dc=example,dc=org"
DEX_TEST_LDAP_BINDPASS="admin"

View file

@ -15,7 +15,7 @@ The dex connector configuration format is a JSON array of objects, each with an
"id": "Google",
"type": "oidc",
...<<more config>>...
}
}
]
```
@ -45,11 +45,8 @@ The configuration for the local connector is always the same; it looks like this
This connector config lets users authenticate with other OIDC providers. In addition to `id` and `type`, the `oidc` connector takes the following additional fields:
* issuerURL: a `string`. The base URL for the OIDC provider. Should be a URL with an `https` scheme.
* clientID: a `string`. The OIDC client ID.
* clientSecret: a `string`. The OIDC client secret.
* trustedEmailProvider: a `boolean`. If true dex will trust the email address claims from this provider and not require that users verify their emails.
In order to use the `oidc` connector you must register dex as an OIDC client; this mechanism is different from provider to provider. For Google, follow the instructions at their [developer site](https://developers.google.com/identity/protocols/OpenIDConnect?hl=en). Regardless of your provider, registering your client will also provide you with the client ID and secret.
@ -80,7 +77,6 @@ Here's what a `oidc` connector looks like configured for authenticating with Goo
This connector config lets users authenticate through [GitHub](https://github.com/). In addition to `id` and `type`, the `github` connector takes the following additional fields:
* clientID: a `string`. The GitHub OAuth application client ID.
* clientSecret: a `string`. The GitHub OAuth application client secret.
To begin, register an OAuth application with GitHub through your, or your organization's [account settings](ttps://github.com/settings/applications/new). To register dex as a client of your GitHub application, enter dex's redirect URL under 'Authorization callback URL':
@ -109,10 +105,9 @@ The `github` connector requests read only access to user's email through the [`u
This connector config lets users authenticate through [Bitbucket](https://bitbucket.org/). In addition to `id` and `type`, the `bitbucket` connector takes the following additional fields:
* clientID: a `string`. The Bitbucket OAuth consumer client ID.
* clientSecret: a `string`. The Bitbucket OAuth consumer client secret.
To begin, register an OAuth consumer with Bitbucket through your, or your teams's management page. Follow the documentation at their [developer site](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html).
To begin, register an OAuth consumer with Bitbucket through your, or your teams's management page. Follow the documentation at their [developer site](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html).
__NOTE:__ When configuring a consumer through Bitbucket you _must_ configure read email permissions.
To register dex as a client of your Bitbucket consumer, enter dex's redirect URL under 'Callback URL':
@ -136,83 +131,85 @@ Here's an example of a `bitbucket` connector; the clientID and clientSecret shou
### `ldap` connector
The `ldap` connector allows email/password based authentication hosted by dex, backed by a LDAP directory.
The `ldap` connector allows email/password based authentication hosted by dex, backed by a LDAP directory. The connector can operate in two primary modes:
Authentication is performed by binding to the configured LDAP server using the user supplied credentials. Successfull bind equals authenticated user.
1. Binding against a specific directory using the end user's credentials.
2. Searching a directory for a entry using a service account then attempting to bind with the user's credentials.
Optionally the connector can be configured to search before authentication. The entryDN found will be used to bind to the LDAP server.
User entries are expected to have an email attribute (configurable through "emailAttribute"), and optionally a display name attribute (configurable through "nameAttribute").
This feature must be enabled to get supplementary information from the directory (ID, Name, Email). This feature can also be used to limit access to the service.
Example use case: Allow your users to log in with e-mail address as username instead of the identification string in your DNs (typically username).
___NOTE:___ Users must register with dex at first login. For this to work you have to run dex-worker with --enable-registration.
___NOTE:___ Dex currently requires user registration with the dex system, even if that user already has an account with the upstream LDAP system. Installations that use this connector are recommended to provide the "--enable-automatic-registration" flag.
In addition to `id` and `type`, the `ldap` connector takes the following additional fields:
* serverHost: a `string`. The hostname for the LDAP Server.
* serverPort: a `unsigned 16-bit integer`. The port for the LDAP Server.
* timeout: `duration in milliseconds`. The timeout for connecting to and reading from LDAP Server in Milliseconds. Default: `60000` (60 Seconds)
* host: a `string`. The host and port of the LDAP server in form "host:port".
* useTLS: a `boolean`. Whether the LDAP Connector should issue a StartTLS after successfully connecting to the LDAP Server.
* useSSL: a `boolean`. Whether the LDAP Connector should expect the connection to be encrypted, typically used with ldaps port (636/tcp).
* certFile: a `string`. Optional Certificate to present to LDAP server.
* keyFile: a `string`. Key associated with Certificate specified in `certFile`.
* certFile: a `string`. Optional path to x509 client certificate to present to LDAP server.
* keyFile: a `string`. Key associated with x509 client cert specified in `certFile`.
* caFile: a `string`. Filename for PEM-file containing the set of root certificate authorities that the LDAP client use when verifying the server certificates. Default: use the host's root CA set.
* skipCertVerification: a `boolean`. Skip server certificate chain verification.
* maxIdleConn: a `integer`. Maximum number of idle LDAP Connections to keep in connection pool. Default: `5`
* baseDN: a `string`. Base DN from which Bind DN is built and searches are based.
* nameAttribute: a `string`. Attribute to map to Name. Default: `cn`
* emailAttribute: a `string`. Attribute to map to Email. Default: `mail`
* nameAttribute: a `string`. Entity attribute to map to display name of users. Default: `cn`
* emailAttribute: a `string`. Required. Attribute to map to Email. Default: `mail`
* searchBeforeAuth: a `boolean`. Perform search for entryDN to be used for bind.
* searchFilter: a `string`. Filter to apply to search. Variable substititions: `%u` User supplied username/e-mail address. `%b` BaseDN.
* searchFilter: a `string`. Filter to apply to search. Variable substititions: `%u` User supplied username/e-mail address. `%b` BaseDN. Searches that return multiple entries are considered ambiguous and will return an error.
* searchScope: a `string`. Scope of the search. `base|one|sub`. Default: `one`
* searchBindDN: a `string`. DN to bind as for search operations.
* searchBindPw: a `string`. Password for bind for search operations.
* bindTemplate: a `string`. Template to build bindDN from user supplied credentials. Variable subtitutions: `%u` User supplied username/e-mail address. `%b` BaseDN. Default: `uid=%u,%b`.
* bindTemplate: a `string`. Template to build bindDN from user supplied credentials. Variable subtitutions: `%u` User supplied username/e-mail address. `%b` BaseDN. Default: `uid=%u,%b` ___NOTE:___ This is not used when searchBeforeAuth is enabled.
### Example: Authenticating against a specific directory
* trustedEmailProvider: a `boolean`. If true dex will trust the email address claims from this provider and not require that users verify their emails.
Here's an example of a `ldap` connector;
To authenticate against a specific LDAP directory level, use the "bindTemplate" field. This string describes how to map a username to a LDAP entity.
```
{
"type": "ldap",
"id": "ldap",
"serverHost": "127.0.0.1",
"serverPort": 389,
"useTLS": true,
"useSSL": false,
"skipCertVerification": false,
"baseDN": "ou=People,dc=example,dc=com",
"nameAttribute": "cn",
"emailAttribute": "mail",
"searchBeforeAuth": true,
"searchFilter": "(mail=%u)",
"searchScope": "one",
"searchBindDN": "searchuser",
"searchBindPw": "supersecret",
"bindTemplate": "uid=%u,%b",
"trustedEmailProvider": true
"host": "127.0.0.1:389",
"baseDN": "cn=users,cn=accounts,dc=auth,dc=example,dc=com",
"bindTemplate": "uid=%u,%d"
}
```
"bindTemplate" is a format string. `%d` is replaced by the value of "baseDN" and `%u` is replaced by the username attempting to login. In this case if a user "janedoe" attempts to authenticate, the bindTemplate will be expanded to:
```
uid=janedoe,cn=users,cn=accounts,dc=auth,dc=example,dc=com
```
The connector then attempts to bind as this entry using the password provided by the end user.
### Example: Searching the directory
The following configuration will search a directory using an LDAP filter. With FreeIPA
```
{
"type": "ldap",
"id": "ldap",
"host": "127.0.0.1:389",
"baseDN": "cn=auth,dc=example,dc=com",
"searchBeforeAuth": true,
"searchFilter": "(&(objectClass=person)(uid=%u))",
"searchScope": "sub",
"searchBindDN": "serviceAccountUser",
"searchBindPw": "serviceAccountPassword"
}
```
"searchFilter" is a format string expanded in a similar manner as "bindTemplate". If the user "janedoe" attempts to authenticate, the connector will run the following query using the service account credentials.
```
(&(objectClass=person)(uid=janedoe))
```
If the search finds an entry, it will attempt to use the provided password to bind as that entry.
__NOTE__: Searches that return multiple entries will return an error.
## Setting the Configuration
To set a connectors configuration in dex, put it in some temporary file, then use the dexctl command to upload it to dex:

View file

@ -3,6 +3,8 @@ package connector
import (
"crypto/tls"
"crypto/x509"
"errors"
"net"
"fmt"
@ -28,30 +30,63 @@ const (
func init() {
RegisterConnectorConfigType(LDAPConnectorType, func() ConnectorConfig { return &LDAPConnectorConfig{} })
// Set default ldap timeout.
ldap.DefaultTimeout = 30 * time.Second
}
type LDAPConnectorConfig struct {
ID string `json:"id"`
ServerHost string `json:"serverHost"`
ServerPort uint16 `json:"serverPort"`
Timeout time.Duration `json:"timeout"`
UseTLS bool `json:"useTLS"`
UseSSL bool `json:"useSSL"`
CertFile string `json:"certFile"`
KeyFile string `json:"keyFile"`
CaFile string `json:"caFile"`
SkipCertVerification bool `json:"skipCertVerification"`
MaxIdleConn int `json:"maxIdleConn"`
BaseDN string `json:"baseDN"`
NameAttribute string `json:"nameAttribute"`
EmailAttribute string `json:"emailAttribute"`
SearchBeforeAuth bool `json:"searchBeforeAuth"`
SearchFilter string `json:"searchFilter"`
SearchScope string `json:"searchScope"`
SearchBindDN string `json:"searchBindDN"`
SearchBindPw string `json:"searchBindPw"`
BindTemplate string `json:"bindTemplate"`
TrustedEmailProvider bool `json:"trustedEmailProvider"`
ID string `json:"id"`
// Host and port of ldap service in form "host:port"
Host string `json:"host"`
// UseTLS indicates that the connector should use the TLS port.
UseTLS bool `json:"useTLS"`
UseSSL bool `json:"useSSL"`
// Trusted TLS certificate when connecting to the LDAP server. If empty the
// host's root certificates will be used.
CaFile string `json:"caFile"`
// CertFile and KeyFile are used to specifiy client certificate data.
CertFile string `json:"certFile"`
KeyFile string `json:"keyFile"`
MaxIdleConn int `json:"maxIdleConn"`
NameAttribute string `json:"nameAttribute"`
EmailAttribute string `json:"emailAttribute"`
// The place to start all searches from.
BaseDN string `json:"baseDN"`
// Search fields indicate how to search for user records in LDAP.
SearchBeforeAuth bool `json:"searchBeforeAuth"`
SearchFilter string `json:"searchFilter"`
SearchScope string `json:"searchScope"`
SearchBindDN string `json:"searchBindDN"`
SearchBindPw string `json:"searchBindPw"`
SearchGroupFilter string `json:"searchGroupFilter"`
// BindTemplate is a format string that maps user names to a record to bind as.
// It's passed both the username entered by the end user and the base DN.
//
// For example the bindTemplate
//
// "uid=%u,%d"
//
// with the username "johndoe" and basename "ou=People,dc=example,dc=com" would attempt
// to bind as
//
// "uid=johndoe,ou=People,dc=example,dc=com"
//
BindTemplate string `json:"bindTemplate"`
// DEPRICATED fields that exist for backward compatibility.
// Use "host" instead of "ServerHost" and "ServerPort"
ServerHost string `json:"serverHost"`
ServerPort uint16 `json:"serverPort"`
Timeout time.Duration `json:"timeout"`
}
func (cfg *LDAPConnectorConfig) ConnectorID() string {
@ -63,14 +98,28 @@ func (cfg *LDAPConnectorConfig) ConnectorType() string {
}
type LDAPConnector struct {
id string
idp *LDAPIdentityProvider
namespace url.URL
trustedEmailProvider bool
loginFunc oidc.LoginFunc
loginTpl *template.Template
id string
namespace url.URL
loginFunc oidc.LoginFunc
loginTpl *template.Template
baseDN string
nameAttribute string
emailAttribute string
searchBeforeAuth bool
searchFilter string
searchScope int
searchBindDN string
searchBindPw string
bindTemplate string
ldapPool *LDAPPool
}
const defaultPoolCheckTimer = 7200 * time.Second
func (cfg *LDAPConnectorConfig) Connector(ns url.URL, lf oidc.LoginFunc, tpls *template.Template) (Connector, error) {
ns.Path = path.Join(ns.Path, httpPathCallback)
tpl := tpls.Lookup(LDAPLoginPageTemplateName)
@ -78,14 +127,6 @@ func (cfg *LDAPConnectorConfig) Connector(ns url.URL, lf oidc.LoginFunc, tpls *t
return nil, fmt.Errorf("unable to find necessary HTML template")
}
// defaults
const defaultNameAttribute = "cn"
const defaultEmailAttribute = "mail"
const defaultBindTemplate = "uid=%u,%b"
const defaultSearchScope = ldap.ScopeWholeSubtree
const defaultMaxIdleConns = 5
const defaultPoolCheckTimer = 7200 * time.Second
if cfg.UseTLS && cfg.UseSSL {
return nil, fmt.Errorf("Invalid configuration. useTLS and useSSL are mutual exclusive.")
}
@ -94,26 +135,23 @@ func (cfg *LDAPConnectorConfig) Connector(ns url.URL, lf oidc.LoginFunc, tpls *t
return nil, fmt.Errorf("Invalid configuration. Both certFile and keyFile must be specified.")
}
nameAttribute := defaultNameAttribute
if len(cfg.NameAttribute) > 0 {
nameAttribute = cfg.NameAttribute
// Set default values
if cfg.NameAttribute == "" {
cfg.NameAttribute = "cn"
}
emailAttribute := defaultEmailAttribute
if len(cfg.EmailAttribute) > 0 {
emailAttribute = cfg.EmailAttribute
if cfg.EmailAttribute == "" {
cfg.EmailAttribute = "mail"
}
bindTemplate := defaultBindTemplate
if len(cfg.BindTemplate) > 0 {
if cfg.SearchBeforeAuth {
log.Warningf("bindTemplate not used when searchBeforeAuth specified.")
}
bindTemplate = cfg.BindTemplate
if cfg.MaxIdleConn > 0 {
cfg.MaxIdleConn = 5
}
searchScope := defaultSearchScope
if len(cfg.SearchScope) > 0 {
if cfg.BindTemplate == "" {
cfg.BindTemplate = "uid=%u,%b"
} else if cfg.SearchBeforeAuth {
log.Warningf("bindTemplate not used when searchBeforeAuth specified.")
}
searchScope := ldap.ScopeWholeSubtree
if cfg.SearchScope != "" {
switch {
case strings.EqualFold(cfg.SearchScope, "BASE"):
searchScope = ldap.ScopeBaseObject
@ -126,15 +164,21 @@ func (cfg *LDAPConnectorConfig) Connector(ns url.URL, lf oidc.LoginFunc, tpls *t
}
}
if cfg.Timeout != 0 {
ldap.DefaultTimeout = cfg.Timeout * time.Millisecond
if cfg.Host == "" {
if cfg.ServerHost == "" {
return nil, errors.New("no host provided")
}
// For backward compatibility construct host form old fields.
cfg.Host = fmt.Sprintf("%s:%d", cfg.ServerHost, cfg.ServerPort)
}
tlsConfig := &tls.Config{
ServerName: cfg.ServerHost,
InsecureSkipVerify: cfg.SkipCertVerification,
host, _, err := net.SplitHostPort(cfg.Host)
if err != nil {
return nil, fmt.Errorf("host is not of form 'host:port': %v", err)
}
tlsConfig := &tls.Config{ServerName: host}
if (cfg.UseTLS || cfg.UseSSL) && len(cfg.CaFile) > 0 {
buf, err := ioutil.ReadFile(cfg.CaFile)
if err != nil {
@ -158,41 +202,28 @@ func (cfg *LDAPConnectorConfig) Connector(ns url.URL, lf oidc.LoginFunc, tpls *t
tlsConfig.Certificates = []tls.Certificate{cert}
}
maxIdleConn := defaultMaxIdleConns
if cfg.MaxIdleConn > 0 {
maxIdleConn = cfg.MaxIdleConn
}
ldapPool := &LDAPPool{
MaxIdleConn: maxIdleConn,
PoolCheckTimer: defaultPoolCheckTimer,
ServerHost: cfg.ServerHost,
ServerPort: cfg.ServerPort,
UseTLS: cfg.UseTLS,
UseSSL: cfg.UseSSL,
TLSConfig: tlsConfig,
}
idp := &LDAPIdentityProvider{
idpc := &LDAPConnector{
id: cfg.ID,
namespace: ns,
loginFunc: lf,
loginTpl: tpl,
baseDN: cfg.BaseDN,
nameAttribute: nameAttribute,
emailAttribute: emailAttribute,
nameAttribute: cfg.NameAttribute,
emailAttribute: cfg.EmailAttribute,
searchBeforeAuth: cfg.SearchBeforeAuth,
searchFilter: cfg.SearchFilter,
searchScope: searchScope,
searchBindDN: cfg.SearchBindDN,
searchBindPw: cfg.SearchBindPw,
bindTemplate: bindTemplate,
ldapPool: ldapPool,
}
idpc := &LDAPConnector{
id: cfg.ID,
idp: idp,
namespace: ns,
trustedEmailProvider: cfg.TrustedEmailProvider,
loginFunc: lf,
loginTpl: tpl,
bindTemplate: cfg.BindTemplate,
ldapPool: &LDAPPool{
MaxIdleConn: cfg.MaxIdleConn,
PoolCheckTimer: defaultPoolCheckTimer,
Host: cfg.Host,
UseTLS: cfg.UseTLS,
UseSSL: cfg.UseSSL,
TLSConfig: tlsConfig,
},
}
return idpc, nil
@ -203,11 +234,10 @@ func (c *LDAPConnector) ID() string {
}
func (c *LDAPConnector) Healthy() error {
ldapConn, err := c.idp.ldapPool.Acquire()
if err == nil {
c.idp.ldapPool.Put(ldapConn)
}
return err
return c.ldapPool.Do(func(c *ldap.Conn) error {
// Attempt an anonymous bind.
return c.Bind("", "")
})
}
func (c *LDAPConnector) LoginURL(sessionKey, prompt string) (string, error) {
@ -221,7 +251,7 @@ func (c *LDAPConnector) LoginURL(sessionKey, prompt string) (string, error) {
func (c *LDAPConnector) Register(mux *http.ServeMux, errorURL url.URL) {
route := path.Join(c.namespace.Path, "login")
mux.Handle(route, handleLoginFunc(c.loginFunc, c.loginTpl, c.idp, route, errorURL))
mux.Handle(route, handlePasswordLogin(c.loginFunc, c.loginTpl, c, route, errorURL))
}
func (c *LDAPConnector) Sync() chan struct{} {
@ -230,8 +260,8 @@ func (c *LDAPConnector) Sync() chan struct{} {
go func() {
for {
select {
case <-time.After(c.idp.ldapPool.PoolCheckTimer):
alive, killed := c.idp.ldapPool.CheckConnections()
case <-time.After(c.ldapPool.PoolCheckTimer):
alive, killed := c.ldapPool.CheckConnections()
if alive > 0 {
log.Infof("Connector ID=%v idle_conns=%v", c.id, alive)
}
@ -247,38 +277,41 @@ func (c *LDAPConnector) Sync() chan struct{} {
}
func (c *LDAPConnector) TrustedEmailProvider() bool {
return c.trustedEmailProvider
return true
}
// A LDAPPool is a Connection Pool for LDAP connections
// Initialize exported fields and use Acquire() to get a connection.
// Use Put() to put it back into the pool.
// A LDAPPool is a Connection Pool for LDAP connections. Use Do() to request connections
// from the pool.
type LDAPPool struct {
m sync.Mutex
conns map[*ldap.Conn]struct{}
MaxIdleConn int
PoolCheckTimer time.Duration
ServerHost string
ServerPort uint16
Host string
UseTLS bool
UseSSL bool
TLSConfig *tls.Config
}
// Acquire removes and returns a random connection from the pool. A new connection is returned
// if there are no connections available in the pool.
func (p *LDAPPool) Acquire() (*ldap.Conn, error) {
// Do runs a function which requires an LDAP connection.
//
// The connection will be unauthenticated with the server and should not be closed by f.
func (p *LDAPPool) Do(f func(conn *ldap.Conn) error) (err error) {
conn := p.removeRandomConn()
if conn != nil {
return conn, nil
if conn == nil {
conn, err = p.ldapConnect()
if err != nil {
return err
}
}
return p.ldapConnect()
defer p.put(conn)
return f(conn)
}
// Put makes a connection ready for re-use and puts it back into the pool. If the connection
// put makes a connection ready for re-use and puts it back into the pool. If the connection
// cannot be reused it is discarded. If there already are MaxIdleConn connections in the pool
// the connection is discarded.
func (p *LDAPPool) Put(c *ldap.Conn) {
func (p *LDAPPool) put(c *ldap.Conn) {
p.m.Lock()
if p.conns == nil {
// First call to Put, initialize map
@ -345,7 +378,7 @@ func (p *LDAPPool) CheckConnections() (int, int) {
if ok {
err := ldapPing(conn)
if err == nil {
p.Put(conn)
p.put(conn)
alive++
} else {
conn.Close()
@ -363,31 +396,17 @@ func ldapPing(conn *ldap.Conn) error {
return err
}
type LDAPIdentityProvider struct {
baseDN string
nameAttribute string
emailAttribute string
searchBeforeAuth bool
searchFilter string
searchScope int
searchBindDN string
searchBindPw string
bindTemplate string
ldapPool *LDAPPool
}
func (p *LDAPPool) ldapConnect() (*ldap.Conn, error) {
var err error
var ldapConn *ldap.Conn
log.Debugf("LDAPConnect()")
if p.UseSSL {
ldapConn, err = ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", p.ServerHost, p.ServerPort), p.TLSConfig)
ldapConn, err = ldap.DialTLS("tcp", p.Host, p.TLSConfig)
if err != nil {
return nil, err
}
} else {
ldapConn, err = ldap.Dial("tcp", fmt.Sprintf("%s:%d", p.ServerHost, p.ServerPort))
ldapConn, err = ldap.Dial("tcp", p.Host)
if err != nil {
return nil, err
}
@ -402,74 +421,114 @@ func (p *LDAPPool) ldapConnect() (*ldap.Conn, error) {
return ldapConn, err
}
func (m *LDAPIdentityProvider) ParseString(template, username string) string {
// invalidBindCredentials determines if a bind error was the result of invalid
// credentials.
func invalidBindCredentials(err error) bool {
ldapErr, ok := err.(*ldap.Error)
if ok {
return false
}
return ldapErr.ResultCode == ldap.LDAPResultInvalidCredentials
}
func (c *LDAPConnector) formatDN(template, username string) string {
result := template
result = strings.Replace(result, "%u", username, -1)
result = strings.Replace(result, "%b", m.baseDN, -1)
result = strings.Replace(result, "%b", c.baseDN, -1)
return result
}
func (m *LDAPIdentityProvider) Identity(username, password string) (*oidc.Identity, error) {
var err error
var bindDN, ldapUid, ldapName, ldapEmail string
var ldapConn *ldap.Conn
func (c *LDAPConnector) Identity(username, password string) (*oidc.Identity, error) {
log.Errorf("handling identity")
var (
identity *oidc.Identity
err error
)
if c.searchBeforeAuth {
err = c.ldapPool.Do(func(conn *ldap.Conn) error {
if err := conn.Bind(c.searchBindDN, c.searchBindPw); err != nil {
// Don't wrap error as it may be a specific LDAP error.
return err
}
ldapConn, err = m.ldapPool.Acquire()
if err != nil {
return nil, err
}
defer m.ldapPool.Put(ldapConn)
filter := c.formatDN(c.searchFilter, username)
req := &ldap.SearchRequest{
BaseDN: c.baseDN,
Scope: c.searchScope,
Filter: filter,
Attributes: []string{c.nameAttribute, c.emailAttribute},
}
resp, err := conn.Search(req)
if err != nil {
return fmt.Errorf("search failed: %v", err)
}
switch len(resp.Entries) {
case 0:
return errors.New("user not found by search")
case 1:
default:
// For now reject searches that return multiple entries to avoid ambiguity.
log.Errorf("LDAP search %q returned %d entries. Must disambiguate searchFilter.", filter, len(resp.Entries))
return errors.New("search returned multiple entries")
}
if m.searchBeforeAuth {
err = ldapConn.Bind(m.searchBindDN, m.searchBindPw)
if err != nil {
return nil, err
}
entry := resp.Entries[0]
email := entry.GetAttributeValue(c.emailAttribute)
if email == "" {
return fmt.Errorf("no email attribute found")
}
filter := m.ParseString(m.searchFilter, username)
identity = &oidc.Identity{
ID: entry.DN,
Name: entry.GetAttributeValue(c.nameAttribute),
Email: email,
}
attributes := []string{
m.nameAttribute,
m.emailAttribute,
}
s := ldap.NewSearchRequest(m.baseDN, m.searchScope, ldap.NeverDerefAliases, 0, 0, false, filter, attributes, nil)
sr, err := ldapConn.Search(s)
if err != nil {
return nil, err
}
if len(sr.Entries) == 0 {
err = fmt.Errorf("Search returned no match. filter='%v' base='%v'", filter, m.baseDN)
return nil, err
}
bindDN = sr.Entries[0].DN
ldapName = sr.Entries[0].GetAttributeValue(m.nameAttribute)
ldapEmail = sr.Entries[0].GetAttributeValue(m.emailAttribute)
// prepare LDAP connection for bind as user
m.ldapPool.Put(ldapConn)
ldapConn, err = m.ldapPool.Acquire()
if err != nil {
return nil, err
}
// Attempt to bind as the end user.
return conn.Bind(entry.DN, password)
})
} else {
bindDN = m.ParseString(m.bindTemplate, username)
err = c.ldapPool.Do(func(conn *ldap.Conn) error {
userBindDN := c.formatDN(c.bindTemplate, username)
if err := conn.Bind(userBindDN, password); err != nil {
// Don't wrap error as it may be a specific LDAP error.
return err
}
req := &ldap.SearchRequest{
BaseDN: userBindDN,
Scope: ldap.ScopeBaseObject, // Only attempt to
Filter: "(objectClass=*)",
}
resp, err := conn.Search(req)
if err != nil {
return fmt.Errorf("search failed: %v", err)
}
if len(resp.Entries) == 0 {
// Are there cases were a user wouldn't be able to see their own entity?
return fmt.Errorf("user not found by search")
}
entry := resp.Entries[0]
email := entry.GetAttributeValue(c.emailAttribute)
if email == "" {
return fmt.Errorf("no email attribute found")
}
identity = &oidc.Identity{
ID: entry.DN,
Name: entry.GetAttributeValue(c.nameAttribute),
Email: email,
}
return nil
})
}
// authenticate user
err = ldapConn.Bind(bindDN, password)
if err != nil {
if !invalidBindCredentials(err) {
log.Errorf("failed to connect to LDAP for search bind: %v", err)
}
return nil, err
}
ldapUid = bindDN
return &oidc.Identity{
ID: ldapUid,
Name: ldapName,
Email: ldapEmail,
}, nil
return identity, nil
}

View file

@ -21,6 +21,7 @@ func init() {
func TestLDAPConnectorConfigValidTLS(t *testing.T) {
cc := LDAPConnectorConfig{
ID: "ldap",
Host: "example.com:636",
UseTLS: true,
UseSSL: false,
}
@ -34,6 +35,7 @@ func TestLDAPConnectorConfigValidTLS(t *testing.T) {
func TestLDAPConnectorConfigInvalidSSLandTLS(t *testing.T) {
cc := LDAPConnectorConfig{
ID: "ldap",
Host: "example.com:636",
UseTLS: true,
UseSSL: true,
}
@ -47,6 +49,7 @@ func TestLDAPConnectorConfigInvalidSSLandTLS(t *testing.T) {
func TestLDAPConnectorConfigValidSearchScope(t *testing.T) {
cc := LDAPConnectorConfig{
ID: "ldap",
Host: "example.com:636",
SearchScope: "one",
}
@ -59,6 +62,7 @@ func TestLDAPConnectorConfigValidSearchScope(t *testing.T) {
func TestLDAPConnectorConfigInvalidSearchScope(t *testing.T) {
cc := LDAPConnectorConfig{
ID: "ldap",
Host: "example.com:636",
SearchScope: "three",
}
@ -71,6 +75,7 @@ func TestLDAPConnectorConfigInvalidSearchScope(t *testing.T) {
func TestLDAPConnectorConfigInvalidCertFileNoKeyFile(t *testing.T) {
cc := LDAPConnectorConfig{
ID: "ldap",
Host: "example.com:636",
CertFile: "/tmp/ldap.crt",
}
@ -83,6 +88,7 @@ func TestLDAPConnectorConfigInvalidCertFileNoKeyFile(t *testing.T) {
func TestLDAPConnectorConfigValidCertFileAndKeyFile(t *testing.T) {
cc := LDAPConnectorConfig{
ID: "ldap",
Host: "example.com:636",
CertFile: "/tmp/ldap.crt",
KeyFile: "/tmp/ldap.key",
}

View file

@ -87,7 +87,7 @@ func (c *LocalConnector) LoginURL(sessionKey, prompt string) (string, error) {
func (c *LocalConnector) Register(mux *http.ServeMux, errorURL url.URL) {
route := c.namespace.Path + "/login"
mux.Handle(route, handleLoginFunc(c.loginFunc, c.loginTpl, c.idp, route, errorURL))
mux.Handle(route, handlePasswordLogin(c.loginFunc, c.loginTpl, c.idp, route, errorURL))
}
func (c *LocalConnector) Sync() chan struct{} {

View file

@ -65,7 +65,3 @@ type ConnectorConfigRepo interface {
GetConnectorByID(repo.Transaction, string) (ConnectorConfig, error)
Set(cfgs []ConnectorConfig) error
}
type IdentityProvider interface {
Identity(email, password string) (*oidc.Identity, error)
}

View file

@ -18,7 +18,12 @@ func redirectPostError(w http.ResponseWriter, errorURL url.URL, q url.Values) {
w.WriteHeader(http.StatusSeeOther)
}
func handleLoginFunc(lf oidc.LoginFunc, tpl *template.Template, idp IdentityProvider, localErrorPath string, errorURL url.URL) http.HandlerFunc {
// passwordLoginProvider is a provider which requires a username and password to identify the user.
type passwordLoginProvider interface {
Identity(email, password string) (*oidc.Identity, error)
}
func handlePasswordLogin(lf oidc.LoginFunc, tpl *template.Template, idp passwordLoginProvider, localErrorPath string, errorURL url.URL) http.HandlerFunc {
handleGET := func(w http.ResponseWriter, r *http.Request, errMsg string) {
q := r.URL.Query()
sessionKey := q.Get("session_key")
@ -54,9 +59,7 @@ func handleLoginFunc(lf oidc.LoginFunc, tpl *template.Template, idp IdentityProv
}
ident, err := idp.Identity(userid, password)
log.Errorf("IDENTITY: err: %v", err)
if ident == nil || err != nil {
if err != nil {
handleGET(w, r, "invalid login")
return
}

View file

@ -1,12 +1,9 @@
package functional
import (
"fmt"
"html/template"
"net"
"net/url"
"os"
"strconv"
"sync"
"testing"
"time"
@ -16,45 +13,41 @@ import (
"gopkg.in/ldap.v2"
)
var (
ldapHost string
ldapPort uint16
ldapBindDN string
ldapBindPw string
)
type LDAPServer struct {
Host string
Port uint16
BindDN string
BindPw string
Host string // Address (host:port) of LDAP service.
LDAPSHost string // Address (host:port) of LDAPS service (TLS port).
BindDN string
BindPw string
}
const (
ldapEnvHost = "DEX_TEST_LDAP_HOST"
ldapEnvHost = "DEX_TEST_LDAP_HOST"
ldapsEnvHost = "DEX_TEST_LDAPS_HOST"
ldapEnvBindName = "DEX_TEST_LDAP_BINDNAME"
ldapEnvBindPass = "DEX_TEST_LDAP_BINDPASS"
)
func ldapServer(t *testing.T) LDAPServer {
host := os.Getenv(ldapEnvHost)
if host == "" {
t.Fatalf("%s not set", ldapEnvHost)
}
var port uint64 = 389
if h, p, err := net.SplitHostPort(host); err == nil {
port, err = strconv.ParseUint(p, 10, 16)
if err != nil {
t.Fatalf("failed to parse port: %v", err)
getenv := func(key string) string {
val := os.Getenv(key)
if val == "" {
t.Fatalf("%s not set", key)
}
host = h
t.Logf("%s=%v", key, val)
return val
}
return LDAPServer{
Host: getenv(ldapEnvHost),
LDAPSHost: getenv(ldapsEnvHost),
BindDN: os.Getenv(ldapEnvBindName),
BindPw: os.Getenv(ldapEnvBindPass),
}
return LDAPServer{host, uint16(port), os.Getenv(ldapEnvBindName), os.Getenv(ldapEnvBindPass)}
}
func TestLDAPConnect(t *testing.T) {
server := ldapServer(t)
l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", server.Host, server.Port))
l, err := ldap.Dial("tcp", server.Host)
if err != nil {
t.Fatal(err)
}
@ -74,39 +67,35 @@ func TestConnectorLDAPHealthy(t *testing.T) {
}{
{
config: connector.LDAPConnectorConfig{
ID: "ldap",
ServerHost: server.Host,
ServerPort: server.Port + 1,
ID: "ldap",
Host: "localhost:0",
},
wantErr: true,
},
{
config: connector.LDAPConnectorConfig{
ID: "ldap",
ServerHost: server.Host,
ServerPort: server.Port,
ID: "ldap",
Host: server.Host,
},
},
{
config: connector.LDAPConnectorConfig{
ID: "ldap",
ServerHost: server.Host,
ServerPort: server.Port,
UseTLS: true,
CertFile: "/tmp/ldap.crt",
KeyFile: "/tmp/ldap.key",
CaFile: "/tmp/openldap-ca.pem",
ID: "ldap",
Host: server.Host,
UseTLS: true,
CertFile: "/tmp/ldap.crt",
KeyFile: "/tmp/ldap.key",
CaFile: "/tmp/openldap-ca.pem",
},
},
{
config: connector.LDAPConnectorConfig{
ID: "ldap",
ServerHost: server.Host,
ServerPort: server.Port + 247, // 636
UseSSL: true,
CertFile: "/tmp/ldap.crt",
KeyFile: "/tmp/ldap.key",
CaFile: "/tmp/openldap-ca.pem",
ID: "ldap",
Host: server.LDAPSHost,
UseSSL: true,
CertFile: "/tmp/ldap.crt",
KeyFile: "/tmp/ldap.key",
CaFile: "/tmp/openldap-ca.pem",
},
},
}
@ -131,8 +120,7 @@ func TestLDAPPoolHighWatermarkAndLockContention(t *testing.T) {
server := ldapServer(t)
ldapPool := &connector.LDAPPool{
MaxIdleConn: 30,
ServerHost: server.Host,
ServerPort: server.Port,
Host: server.Host,
UseTLS: false,
UseSSL: false,
}
@ -151,17 +139,16 @@ func TestLDAPPoolHighWatermarkAndLockContention(t *testing.T) {
case <-ctx.Done():
return
default:
ldapConn, err := ldapPool.Acquire()
if err != nil {
t.Errorf("Unable to acquire LDAP Connection: %v", err)
}
s := ldap.NewSearchRequest("", ldap.ScopeBaseObject, ldap.NeverDerefAliases, 0, 0, false, "(objectClass=*)", []string{}, nil)
_, err = ldapConn.Search(s)
err := ldapPool.Do(func(conn *ldap.Conn) error {
s := &ldap.SearchRequest{
Scope: ldap.ScopeBaseObject,
Filter: "(objectClass=*)",
}
_, err := conn.Search(s)
return err
})
if err != nil {
t.Errorf("Search request failed. Dead/invalid LDAP connection from pool?: %v", err)
ldapConn.Close()
} else {
ldapPool.Put(ldapConn)
}
_, _ = ldapPool.CheckConnections()
}

View file

@ -25,8 +25,7 @@
{
"type": "ldap",
"id": "ldap",
"serverHost": "127.0.0.1",
"serverPort": 389,
"host": "127.0.0.1:389",
"useTLS": true,
"useSSL": false,
"caFile": "/etc/ssl/certs/example_com_root.crt",