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

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

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

ale's avatar
ale committed
101
102
	entry := result.Entries[0]

ale's avatar
ale committed
103
104
105
	// Apply the attribute map. We don't care if an attribute is
	// not defined in the map, as the get* functions will silently
	// ignore an empty attribute name.
ale's avatar
ale committed
106
107
108
	u := User{
		Name:                 username,
		Email:                getStringFromLDAPEntry(entry, c.Attrs["email"]),
ale's avatar
ale committed
109
		Shard:                getStringFromLDAPEntry(entry, c.Attrs["shard"]),
110
		EncryptedPassword:    []byte(dropCryptPrefix(getStringFromLDAPEntry(entry, c.Attrs["password"]))),
ale's avatar
ale committed
111
112
113
114
115
116
117
		TOTPSecret:           getStringFromLDAPEntry(entry, c.Attrs["totp_secret"]),
		AppSpecificPasswords: decodeAppSpecificPasswordList(getListFromLDAPEntry(entry, c.Attrs["app_specific_password"])),
	}

	return &u, true
}

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

ale's avatar
ale committed
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
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"`
164
	BindPw     string `yaml:"bind_pw"`
ale's avatar
ale committed
165
166
167
168
169
170
171
172
173
174
175
	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")
	}
176
177
	if (c.BindPwFile == "" && c.BindPw == "") || (c.BindPwFile != "" && c.BindPw != "") {
		return errors.New("only one of bind_pw_file or bind_pw must be set")
ale's avatar
ale committed
178
179
180
181
182
183
	}
	return nil
}

type ldapBackend struct {
	config *LDAPConfig
184
	pool   *ldaputil.ConnectionPool
ale's avatar
ale committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
}

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.
ale's avatar
ale committed
208
209
210
211
212
	var bindPw []byte
	if config.LDAPConfig.BindPw != "" {
		bindPw = []byte(config.LDAPConfig.BindPw)
	} else {
		var err error
213
214
215
216
		bindPw, err = ioutil.ReadFile(config.LDAPConfig.BindPwFile)
		if err != nil {
			return nil, err
		}
ale's avatar
ale committed
217
218
219
	}

	// Initialize the connection pool.
220
	pool, err := ldaputil.NewConnectionPool(config.LDAPConfig.URI, config.LDAPConfig.BindDN, strings.TrimSpace(string(bindPw)), 5)
ale's avatar
ale committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
	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
	}

ale's avatar
ale committed
241
	result, err := b.pool.Search(ctx, serviceConfig.searchRequest(name))
ale's avatar
ale committed
242
243
244
245
246
	if err != nil {
		return nil, false
	}
	return serviceConfig.userFromResponse(name, result)
}