ldap.go 6.1 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
package server

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

10
	ldaputil "git.autistici.org/ai3/go-common/ldap"
ale's avatar
ale committed
11
12
13
14
15
16
17
18
	"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.
19
20
	// SearchFilter should contain the string "%s", which will be
	// replaced with the username before performing a query.
ale's avatar
ale committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
	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")
	}
41
	if c.Scope != "base" && c.Scope != "one" && c.Scope != "sub" {
ale's avatar
ale committed
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
		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)
73
74
75
76
77
	var scope int
	switch c.Scope {
	case "base":
		scope = ldap.ScopeBaseObject
	case "one":
ale's avatar
ale committed
78
		scope = ldap.ScopeSingleLevel
79
80
	case "sub":
		scope = ldap.ScopeWholeSubtree
ale's avatar
ale committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
	}
	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
	}
100
101
	// TODO: return an error if more than one entry is returned.

ale's avatar
ale committed
102
103
104
105
106
107
	entry := result.Entries[0]

	// Apply the attribute map.
	u := User{
		Name:                 username,
		Email:                getStringFromLDAPEntry(entry, c.Attrs["email"]),
108
		EncryptedPassword:    []byte(dropCryptPrefix(getStringFromLDAPEntry(entry, c.Attrs["password"]))),
ale's avatar
ale committed
109
110
111
112
113
114
115
		TOTPSecret:           getStringFromLDAPEntry(entry, c.Attrs["totp_secret"]),
		AppSpecificPasswords: decodeAppSpecificPasswordList(getListFromLDAPEntry(entry, c.Attrs["app_specific_password"])),
	}

	return &u, true
}

116
117
118
119
120
121
122
func dropCryptPrefix(s string) string {
	if strings.HasPrefix(s, "{crypt}") || strings.HasPrefix(s, "{CRYPT}") {
		return s[7:]
	}
	return s
}

ale's avatar
ale committed
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
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
181
	pool   *ldaputil.ConnectionPool
ale's avatar
ale committed
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
}

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.
211
	pool, err := ldaputil.NewConnectionPool(config.LDAPConfig.URI, config.LDAPConfig.BindDN, strings.TrimSpace(string(bindPw)), 5)
ale's avatar
ale committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
	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
	}

232
	conn, err := b.pool.Get(ctx)
ale's avatar
ale committed
233
234
235
236
237
238
239
240
241
242
	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))
243
	b.pool.Release(conn, err)
ale's avatar
ale committed
244
245
246
247
248
	if err != nil {
		return nil, false
	}
	return serviceConfig.userFromResponse(name, result)
}