ldap.go 7.15 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package server

import (
	"context"
	"errors"
	"io/ioutil"
	"net/url"
	"strings"
	"time"

	"gopkg.in/ldap.v2"
)

// LDAPServiceConfig defines a search to be performed when looking up
// a user for a service.
type LDAPServiceConfig struct {
	// SearchBase, SearchFilter and Scope define parameters for
	// the LDAP search. The search should return a single object.
	SearchBase   string `yaml:"search_base"`
	SearchFilter string `yaml:"search_filter"`
	Scope        string `yaml:"scope"`

	// Attrs tells us which LDAP attributes to query to find user
	// attributes. It is encoded as a {user_attribute:
	// ldap_attribute} map, where user attributes include 'email',
	// 'password', 'app_specific_password', 'totp_secret', and
	// more).
	Attrs map[string]string `yaml:"attrs"`
}

// Valid returns an error if the configuration is invalid.
func (c *LDAPServiceConfig) Valid() error {
	if c.SearchBase == "" {
		return errors.New("empty search_base")
	}
	if c.SearchFilter == "" {
		return errors.New("empty search_filter")
	}
	if c.Scope != "one" && c.Scope != "sub" {
		return errors.New("unknown scope")
	}
	return nil
}

func (c *LDAPServiceConfig) attributes() []string {
	var attrs []string
	for _, attrSrc := range c.Attrs {
		attrs = append(attrs, attrSrc)
	}
	return attrs
}

var defaultLDAPAttributeMap = map[string]string{
	"password":              "userPassword",
	"totp_secret":           "totpSecret",
	"app_specific_password": "appSpecificPassword",
}

func (c *LDAPServiceConfig) compile() error {
	// Merge in attributes from the default map if unset.
	for attrDst, attrSrc := range defaultLDAPAttributeMap {
		if _, ok := c.Attrs[attrDst]; !ok {
			c.Attrs[attrDst] = attrSrc
		}
	}
	return nil
}

func (c *LDAPServiceConfig) searchRequest(username string) *ldap.SearchRequest {
	filter := strings.Replace(c.SearchFilter, "%s", ldap.EscapeFilter(username), -1)
	scope := ldap.ScopeWholeSubtree
	if c.Scope == "one" {
		scope = ldap.ScopeSingleLevel
	}
	return ldap.NewSearchRequest(
		c.SearchBase,
		scope,
		ldap.NeverDerefAliases,
		0,
		0,
		false,
		filter,
		c.attributes(),
		nil,
	)
}

// Build a User object from a LDAP response.
func (c *LDAPServiceConfig) userFromResponse(username string, result *ldap.SearchResult) (*User, bool) {
	if len(result.Entries) < 1 {
		return nil, false
	}
	entry := result.Entries[0]

	// Apply the attribute map.
	u := User{
		Name:                 username,
		Email:                getStringFromLDAPEntry(entry, c.Attrs["email"]),
		EncryptedPassword:    []byte(getStringFromLDAPEntry(entry, c.Attrs["password"])),
		TOTPSecret:           getStringFromLDAPEntry(entry, c.Attrs["totp_secret"]),
		AppSpecificPasswords: decodeAppSpecificPasswordList(getListFromLDAPEntry(entry, c.Attrs["app_specific_password"])),
	}

	return &u, true
}

func getStringFromLDAPEntry(entry *ldap.Entry, attr string) string {
	if attr == "" {
		return ""
	}
	return entry.GetAttributeValue(attr)
}

func getListFromLDAPEntry(entry *ldap.Entry, attr string) []string {
	if attr == "" {
		return nil
	}
	return entry.GetAttributeValues(attr)
}

func decodeAppSpecificPasswordList(encodedAsps []string) []*AppSpecificPassword {
	var out []*AppSpecificPassword
	for _, enc := range encodedAsps {
		if p, err := decodeAppSpecificPassword(enc); err == nil {
			out = append(out, p)
		}
	}
	return out
}

func decodeAppSpecificPassword(enc string) (*AppSpecificPassword, error) {
	parts := strings.SplitN(enc, ":", 2)
	if len(parts) != 2 {
		return nil, errors.New("bad encoding")
	}
	return &AppSpecificPassword{
		Service:           parts[0],
		EncryptedPassword: []byte(parts[1]),
	}, nil
}

// LDAPConfig holds the global configuration for the LDAP user backend.
type LDAPConfig struct {
	URI        string `yaml:"uri"`
	BindDN     string `yaml:"bind_dn"`
	BindPwFile string `yaml:"bind_pw_file"`
}

// Valid returns an error if the configuration is invalid.
func (c *LDAPConfig) Valid() error {
	if c.URI == "" {
		return errors.New("empty uri")
	}
	if c.BindDN == "" {
		return errors.New("empty bind_dn")
	}
	if c.BindPwFile == "" {
		return errors.New("empty bind_pw_file")
	}
	return nil
}

type ldapBackend struct {
	config *LDAPConfig
	pool   *ldapConnectionPool
}

type ldapConnectionPool struct {
	network string
	target  string
	bindDN  string
	bindPw  string
	c       chan *ldap.Conn
}

func (p *ldapConnectionPool) connect() (*ldap.Conn, error) {
	conn, err := ldap.Dial(p.network, p.target)
	if err != nil {
		return nil, err
	}

	if err = conn.Bind(p.bindDN, p.bindPw); err != nil {
		conn.Close()
		return nil, err
	}

	return conn, err
}

func (p *ldapConnectionPool) get(ctx context.Context) (*ldap.Conn, error) {
	select {
	case conn := <-p.c:
		return conn, nil
	case <-ctx.Done():
		return nil, ctx.Err()
	}
}

func (p *ldapConnectionPool) release(conn *ldap.Conn, err error) {
	// We assume that if we get an ErrorNetwork, then we need to reconnect.
	for err != nil && ldap.IsErrorWithCode(err, ldap.ErrorNetwork) {
		if conn != nil {
			conn.Close()
		}
		conn, err = p.connect()
	}
	p.c <- conn
}

func (p *ldapConnectionPool) Close() {}

func newLDAPConnectionPool(uri, bindDN, bindPw string, numConns int) (*ldapConnectionPool, error) {
	u, err := url.Parse(uri)
	if err != nil {
		return nil, err
	}
	network := "tcp"
	target := "localhost:389"
ale's avatar
ale committed
219
220
	switch u.Scheme {
	case "ldap":
ale's avatar
ale committed
221
222
223
		if u.Host != "" {
			target = u.Host
		}
ale's avatar
ale committed
224
	case "ldapi":
ale's avatar
ale committed
225
		target = u.Path
ale's avatar
ale committed
226
227
	default:
		return nil, errors.New("unsupported scheme")
ale's avatar
ale committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
	}

	p := &ldapConnectionPool{
		c:       make(chan *ldap.Conn, numConns),
		network: network,
		target:  target,
		bindDN:  bindDN,
		bindPw:  bindPw,
	}

	for i := 0; i < numConns; i++ {
		conn, err := p.connect()
		if err != nil {
			p.Close()
			return nil, err
		}
		p.c <- conn
	}

	return p, nil
}

func newLDAPBackend(config *Config) (*ldapBackend, error) {
	// Validate configuration.
	if err := config.LDAPConfig.Valid(); err != nil {
		return nil, err
	}

	// Check validity of all LDAP service configs, so we can
	// return an error early.
	if err := config.walkBackendSpecs(func(spec *BackendSpec) error {
		if spec.LDAPSpec == nil {
			return nil
		}
		if err := spec.LDAPSpec.Valid(); err != nil {
			return err
		}
		return spec.LDAPSpec.compile()
	}); err != nil {
		return nil, err
	}

	// Read the bind password.
	bindPw, err := ioutil.ReadFile(config.LDAPConfig.BindPwFile)
	if err != nil {
		return nil, err
	}

	// Initialize the connection pool.
	pool, err := newLDAPConnectionPool(config.LDAPConfig.URI, config.LDAPConfig.BindDN, strings.TrimSpace(string(bindPw)), 5)
	if err != nil {
		return nil, err
	}

	return &ldapBackend{
		config: config.LDAPConfig,
		pool:   pool,
	}, nil
}

func (b *ldapBackend) Close() {
	b.pool.Close()
}

func (b *ldapBackend) GetUser(ctx context.Context, spec *BackendSpec, name string) (*User, bool) {
	serviceConfig := spec.LDAPSpec
	if serviceConfig == nil {
		return nil, false
	}

	conn, err := b.pool.get(ctx)
	if err != nil {
		return nil, false
	}

	// Try to turn the context deadline into a LDAP connection timeout...
	if deadline, ok := ctx.Deadline(); ok {
		conn.SetTimeout(time.Until(deadline))
	}

	result, err := conn.Search(serviceConfig.searchRequest(name))
	b.pool.release(conn, err)
	if err != nil {
		return nil, false
	}
	return serviceConfig.userFromResponse(name, result)
}