authserver.go 8.02 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
219
220
221
222
223
224
225
226
227
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
315
316
317
318
319
320
321
322
323
324
325
326
327
package server

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"path/filepath"
	"strings"

	scrypt "github.com/elithrar/simple-scrypt"
	"github.com/pquerna/otp/totp"
	"github.com/tstranex/u2f"
	"gopkg.in/yaml.v2"

	"git.autistici.org/id/auth"
)

// User contains the attributes of a user account as relevant to the
// authentication server. It is only used internally, to communicate
// between the authserver and its storage backends.
type User struct {
	Name                 string
	Email                string
	EncryptedPassword    []byte
	TOTPSecret           string
	U2FRegistrations     []u2f.Registration
	AppSpecificPasswords []*AppSpecificPassword
	Groups               []string
}

// AppSpecificPassword is a password tied to a single service.
type AppSpecificPassword struct {
	Service           string
	EncryptedPassword []byte
}

// Has2FA returns true if the user supports any 2FA method.
func (u *User) Has2FA() bool {
	return u.HasU2F() || u.HasOTP()
}

// HasOTP returns true if the user supports (T)OTP.
func (u *User) HasOTP() bool {
	return u.TOTPSecret != ""
}

// HasU2F returns true if the user supports U2F.
func (u *User) HasU2F() bool {
	return len(u.U2FRegistrations) > 0
}

// UserInfo returns extra user information in the format required by
// the auth wire protocol.
func (u *User) UserInfo() *auth.UserInfo {
	return &auth.UserInfo{
		Email:  u.Email,
		Groups: u.Groups,
	}
}

// UserBackend provides us with per-service user information.
type UserBackend interface {
	Close()
	GetUser(context.Context, *BackendSpec, string) (*User, bool)
}

// U2FShortTermStorage stores short-term u2f challenges.
type U2FShortTermStorage interface {
	SetUserChallenge(string, *u2f.Challenge) error
	GetUserChallenge(string) (*u2f.Challenge, bool)
}

// BackendSpec specifies backend-specific configuration for a service.
type BackendSpec struct {
	LDAPSpec *LDAPServiceConfig `yaml:"ldap"`
	FileSpec string             `yaml:"file"`
}

// ServiceConfig configures authentication backends for a service.
type ServiceConfig struct {
	BackendSpecs      []*BackendSpec `yaml:"backends"`
	ChallengeResponse bool           `yaml:"challenge_response"`
}

// Config for the authentication server.
type Config struct {
	// Global configuration for backends.
	LDAPConfig *LDAPConfig `yaml:"ldap_config"`

	// List of enabled backends.
	EnabledBackends []string `yaml:"enabled_backends"`

	// Service-specific configuration.
	Services map[string]*ServiceConfig `yaml:"services"`

	path string
}

func (c *Config) walkBackendSpecs(f func(*BackendSpec) error) error {
	for _, svc := range c.Services {
		for _, spec := range svc.BackendSpecs {
			if err := f(spec); err != nil {
				return err
			}
		}
	}
	return nil
}

func (c *Config) relativePath(path string) string {
	if strings.HasPrefix(path, "/") {
		return path
	}
	return filepath.Join(filepath.Dir(c.path), path)
}

// LoadConfig loads the configuration from a YAML-encoded file.
func LoadConfig(path string) (*Config, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	config := Config{path: path}
	if err := yaml.Unmarshal(data, &config); err != nil {
		return nil, err
	}
	return &config, nil
}

// Server is the main authentication server object.
type Server struct {
	backends     []UserBackend
	config       *Config
	u2fShortTerm U2FShortTermStorage
}

func newError() *auth.Response {
	return &auth.Response{Status: auth.StatusError}
}

func newOK() *auth.Response {
	return &auth.Response{Status: auth.StatusOK}
}

// NewServer creates a Server using the given configuration.
func NewServer(config *Config, u2fShortTerm U2FShortTermStorage) (*Server, error) {
	s := &Server{
		config:       config,
		u2fShortTerm: u2fShortTerm,
	}
	for _, name := range config.EnabledBackends {
		var b UserBackend
		var err error
		switch name {
		case "file":
			b, err = newFileBackend(config)
		case "ldap":
			b, err = newLDAPBackend(config)
		default:
			err = fmt.Errorf("unknown backend %s", name)
		}
		if err != nil {
			return nil, err
		}
		s.backends = append(s.backends, b)
	}
	return s, nil
}

// Close the authentication server and release all associated resources.
func (s *Server) Close() {
	for _, b := range s.backends {
		b.Close()
	}
}

func (s *Server) getServiceConfig(service string) (*ServiceConfig, bool) {
	c, ok := s.config.Services[service]
	if !ok {
		c, ok = s.config.Services["default"]
	}
	return c, ok
}

// Authenticate a user with the parameters specified in the incoming AuthRequest.
func (s *Server) Authenticate(ctx context.Context, req *auth.Request) *auth.Response {
	serviceConfig, ok := s.getServiceConfig(req.Service)
	if !ok {
		log.Printf("unknown service %s", req.Service)
		return newError()
	}

	var user *User
outer:
	for _, spec := range serviceConfig.BackendSpecs {
		for _, b := range s.backends {
			if user, ok = b.GetUser(ctx, spec, req.Username); ok {
				break outer
			}
		}
	}

	if !ok {
		// User is unknown to all backends.
		log.Printf("unknown user %s", req.Username)
		return newError()
	}

	// Verify different credentials depending on whether the user
	// has 2FA enabled or not, and on whether the service itself
	// supports challenge-response authentication.
	var resp *auth.Response
	if user.Has2FA() {
		if serviceConfig.ChallengeResponse {
			resp = s.authenticateUserWith2FA(user, req)
		} else {
			resp = s.authenticateUserWithASP(user, req)
		}
	} else {
		resp = s.authenticateUser(user, req)
	}

	// If the response is successful, augment it with user information.
	if resp.Status == auth.StatusOK {
		resp.UserInfo = user.UserInfo()
	}

	return resp
}

func (s *Server) authenticateUser(user *User, req *auth.Request) *auth.Response {
	// Ok we only need to check the password here.
	if checkPassword(req.Password, user.EncryptedPassword) {
		return newOK()
	}
	log.Printf("wrong password")
	return newError()
}

func (s *Server) authenticateUserWithASP(user *User, req *auth.Request) *auth.Response {
	for _, asp := range user.AppSpecificPasswords {
		if asp.Service == req.Service && checkPassword(req.Password, asp.EncryptedPassword) {
			return newOK()
		}
	}
	log.Printf("wrong app-specific password")
	return newError()
}

func (s *Server) authenticateUserWith2FA(user *User, req *auth.Request) *auth.Response {
	// First of all verify the password.
	if !checkPassword(req.Password, user.EncryptedPassword) {
		log.Printf("wrong password")
		return newError()
	}

	// If the request contains one of the 2FA attributes, verify
	// it. But if it contains none, we return with
	// AuthStatusInsufficientCredentials and potentially a 2FA
	// hint (for U2F).
	switch {
	case req.U2FResponse != nil:
		if user.HasU2F() && s.checkU2F(user, req.U2FResponse) {
			return newOK()
		}
		log.Printf("bad U2F response")
		return newError()
	case req.OTP != "":
		if user.HasOTP() && checkOTP(req.OTP, user.TOTPSecret) {
			return newOK()
		}
		log.Printf("bad OTP")
		return newError()
	default:
		resp := &auth.Response{
			Status: auth.StatusInsufficientCredentials,
		}
		if req.U2FAppID != "" && user.HasU2F() {
			resp.TFAMethod = auth.TFAMethodU2F
			signReq, err := s.u2fSignRequest(user, req.U2FAppID)
			if err != nil {
				return newError()
			}
			resp.U2FSignRequest = signReq
		} else if user.HasOTP() {
			resp.TFAMethod = auth.TFAMethodOTP
		}
		return resp
	}
}

func (s *Server) u2fSignRequest(user *User, appID string) (*u2f.WebSignRequest, error) {
	challenge, err := u2f.NewChallenge(appID, []string{appID})
	if err != nil {
		return nil, err
	}

	if err := s.u2fShortTerm.SetUserChallenge(user.Name, challenge); err != nil {
		return nil, err
	}

	return challenge.SignRequest(user.U2FRegistrations), nil
}

func (s *Server) checkU2F(user *User, resp *u2f.SignResponse) bool {
	challenge, ok := s.u2fShortTerm.GetUserChallenge(user.Name)
	if !ok {
		return false
	}
	for _, reg := range user.U2FRegistrations {
		_, err := reg.Authenticate(*resp, *challenge, 0)
		if err == nil {
			return true
		}
	}
	return false
}

func checkPassword(password, hash []byte) bool {
	err := scrypt.CompareHashAndPassword(hash, password)
	return err == nil
}

func checkOTP(otp, secret string) bool {
	return totp.Validate(otp, secret)
}