/
main.go
350 lines (282 loc) · 8.79 KB
/
main.go
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package main
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"net/http/httputil"
"strconv"
"strings"
"time"
"github.com/kekru/forward-proxy-auth/authenticator"
"github.com/kekru/forward-proxy-auth/jwtutil"
"github.com/kekru/forward-proxy-auth/model"
"github.com/go-yaml/yaml"
log "github.com/sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/kelseyhightower/envconfig"
)
type Authenticator interface {
Authenticate(username string, password string) (user *model.User, err error)
}
type LoginFormData struct {
LoginUri string
}
type ForwardAuthConfig struct {
Version string `yaml:"Version"`
Server struct {
Uri string `yaml:"Uri"`
Port int `yaml:"Port"`
Loglevel string `yaml:"Loglevel"`
} `yaml:"Server"`
Header struct {
ForwardedUri string `yaml:"ForwardedUri"`
TokenCookie struct {
Names []string `yaml:"Names"`
Domain string `yaml:"Domain"`
Path string `yaml:"Path"`
Secure bool `yaml:"Secure"`
HttpOnly bool `yaml:"HttpOnly"`
SameSite bool `yaml:"SameSite"`
Persistent bool `yaml:"Persistent"`
} `yaml:"TokenCookie"`
TokenHeaders []string `yaml:"TokenHeaders"`
AuthenticatedUser []string `yaml:"AuthenticatedUser"`
AuthenticatedEMail []string `yaml:"AuthenticatedEMail"`
AuthenticatedGroups []string `yaml:"AuthenticatedGroups"`
} `yaml:"Header"`
Jwt struct {
ExpireSeconds int `yaml:"ExpireSeconds"`
HmacSigningKey string `yaml:"HmacSigningKey"`
Issuer string `yaml:"Issuer"`
} `yaml:"Jwt"`
Authenticator struct {
Method string `yaml:"Method"`
Ldap *authenticator.LdapAuth `yaml:"Ldap"`
Textfile *authenticator.TextfileAuth `yaml:"Textfile"`
} `yaml:"Authenticator"`
}
var jwtUtil *jwtutil.JwtUtil
var authenticators []Authenticator
var config *ForwardAuthConfig
func main() {
log.SetLevel(log.DebugLevel)
config = &ForwardAuthConfig{}
bytes, err := ioutil.ReadFile("config.yml")
if err != nil {
log.Fatal(err)
}
err = yaml.Unmarshal(bytes, config)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Println(*config)
err = envconfig.Process("fpa", config)
if err != nil {
log.Fatal(err.Error())
}
fmt.Println(*config)
jwtUtil = &jwtutil.JwtUtil{
ExpireSeconds: config.Jwt.ExpireSeconds,
HmacSigningKey: []byte(config.Jwt.HmacSigningKey),
Issuer: config.Jwt.Issuer,
}
authenticators = append(authenticators, config.Authenticator.Ldap)
log.SetLevel(log.DebugLevel)
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/auth", handleAuth)
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(config.Server.Port), router))
}
func writeAuthenticationResponseHeaders(w http.ResponseWriter, user *model.User) {
for _, header := range config.Header.AuthenticatedUser {
w.Header().Set(header, user.Name)
}
for _, header := range config.Header.AuthenticatedEMail {
w.Header().Set(header, user.Email)
}
for _, header := range config.Header.AuthenticatedGroups {
w.Header().Set(header, strings.Join(user.Groups, ","))
}
}
func writeUserResponse(w http.ResponseWriter, user *model.User, expiryTime time.Time) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
userResponse := &model.UserResponse{
User: user,
ExpiryTime: expiryTime.Format(time.RFC3339),
}
json.NewEncoder(w).Encode(userResponse)
}
func getForwardedUri(r *http.Request) string {
forwardedUri := ""
headers := strings.Split(config.Header.ForwardedUri, "+")
for _, h := range headers {
forwardedUri += r.Header.Get(h)
}
forwardedUri = strings.TrimSpace(forwardedUri)
forwardedUriLower := strings.ToLower(forwardedUri)
if !strings.HasPrefix(forwardedUriLower, "http://") && !strings.HasPrefix(forwardedUriLower, "https://") {
scheme := r.Header.Get("X-Forwarded-Proto")
if scheme == "" {
scheme = "http"
}
if !strings.HasSuffix(scheme, "://") {
scheme = scheme + "://"
}
forwardedUri = scheme + forwardedUri
}
return forwardedUri
}
func extractUserFromToken(r *http.Request) (user *model.User, expiryTime time.Time, err error) {
for _, cookieName := range config.Header.TokenCookie.Names {
cookieToken, err := r.Cookie(cookieName)
if err == nil {
user, expiryTime, err := jwtUtil.ValidateToken(cookieToken.Value)
if err == nil {
return user, expiryTime, err
}
}
}
for _, headerName := range config.Header.TokenHeaders {
headerValue := r.Header.Get(headerName)
if len(headerValue) > 0 {
user, expiryTime, err := jwtUtil.ValidateToken(headerValue)
if err == nil {
return user, expiryTime, err
}
}
}
return nil, time.Time{}, errors.New("No valid token found")
}
func writeResponseToken(token string, expiryTime time.Time, w http.ResponseWriter) {
cookieMaxAge := 0
if config.Header.TokenCookie.Persistent {
cookieMaxAge = int(expiryTime.Unix() - time.Now().Unix())
}
var sameSite http.SameSite
if config.Header.TokenCookie.SameSite {
sameSite = http.SameSiteStrictMode
} else {
sameSite = http.SameSiteLaxMode
}
for _, cookieName := range config.Header.TokenCookie.Names {
cookie := http.Cookie{
Name: cookieName,
Value: token,
SameSite: sameSite,
MaxAge: cookieMaxAge,
HttpOnly: config.Header.TokenCookie.HttpOnly,
Secure: config.Header.TokenCookie.Secure,
Domain: config.Header.TokenCookie.Domain,
Path: config.Header.TokenCookie.Path,
}
http.SetCookie(w, &cookie)
}
for _, headerName := range config.Header.TokenHeaders {
w.Header().Set(headerName, token)
}
}
func handleAuth(w http.ResponseWriter, r *http.Request) {
// try to extraxct user from token
user, expiryTime, err := extractUserFromToken(r)
if err == nil {
writeAuthenticationResponseHeaders(w, user)
writeUserResponse(w, user, expiryTime)
return
} else {
log.Debug(err)
}
requestDump, err := httputil.DumpRequest(r, true)
if err == nil {
log.Debugf("Request\n%s", string(requestDump))
}
// try to login by basic auth credentials
user, err = login(r)
forwardedUri := strings.TrimSpace(r.URL.Query().Get("redirect"))
if len(forwardedUri) == 0 {
forwardedUri = getForwardedUri(r)
}
if err != nil {
// no valid credentials, show new basic auth dialog
log.Debugf("Could not login. %s", err)
method := config.Authenticator.Method
if method == "basic" {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted Area"`)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
} else if method == "htmlform" {
writeLoginpage(w, forwardedUri)
} else {
log.Errorf("Unknown authentication method: %s", method)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
return
}
// create token for authenticated user
token, expiryTime, err := jwtUtil.CreateToken(user)
if err != nil {
log.Errorf("Could not create token for User %s, %s", user.Name, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
// return token in cookie
writeResponseToken(token, expiryTime, w)
// redirect on the originally requested uri
if len(forwardedUri) > 0 {
log.Debugf("Sending redirect to %s for user %s ", forwardedUri, user.Name)
http.Redirect(w, r, forwardedUri, http.StatusSeeOther)
} else {
writeUserResponse(w, user, expiryTime)
}
}
func login(r *http.Request) (user *model.User, err error) {
var username, password string
method := config.Authenticator.Method
if method == "basic" {
var authOK bool
username, password, authOK = r.BasicAuth()
if !authOK {
err = errors.New("no basic auth credentials")
return
}
} else if method == "htmlform" {
err = r.ParseForm()
if err != nil {
return
}
username = strings.TrimSpace(r.Form.Get("username"))
password = strings.TrimSpace(r.Form.Get("password"))
if len(username) == 0 && len(password) == 0 {
err = errors.New("username or password of html form was empty")
return
}
} else {
err = errors.New("Unknown authentication method: " + method)
return
}
for _, auth := range authenticators {
user, err = auth.Authenticate(username, password)
if err == nil {
return
} else {
log.Debug(err)
}
}
err = errors.New("No user with given username and password found. Username: " + username)
return
}
func writeLoginpage(w http.ResponseWriter, forwardedUri string) {
t, err := template.ParseFiles("static/login.html")
if err != nil {
log.Errorf("could not read static/login.html, %s", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusUnauthorized)
templateData := &LoginFormData{
LoginUri: config.Server.Uri + "/auth?redirect=" + forwardedUri,
}
t.Execute(w, templateData)
}