ldap.go 5.79 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
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
	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
167
	pool   *ldaputil.ConnectionPool
ale's avatar
ale committed
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
}

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.
197
	pool, err := ldaputil.NewConnectionPool(config.LDAPConfig.URI, config.LDAPConfig.BindDN, strings.TrimSpace(string(bindPw)), 5)
ale's avatar
ale committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
	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
	}

218
	conn, err := b.pool.Get(ctx)
ale's avatar
ale committed
219
220
221
222
223
224
225
226
227
228
	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))
229
	b.pool.Release(conn, err)
ale's avatar
ale committed
230
231
232
233
234
	if err != nil {
		return nil, false
	}
	return serviceConfig.userFromResponse(name, result)
}