-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
269 lines (232 loc) · 7.27 KB
/
server.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
package main
import (
"errors"
"fmt"
"html/template"
"net/http"
"time"
"github.com/gorilla/csrf"
"go.uber.org/zap"
)
type Context struct {
FormData *FormData
User *User
UserCookie *http.Cookie
GeneratedCookie *http.Cookie
Claims *Claims
HttpReturnCode int
CsrfToken string
Ip string
State string
Url string
ErrorMessage string
}
// set handler for and start listening
func LoadServer() error {
CSRF := csrf.Protect(
[]byte(configuration.CsrfSecretKey),
csrf.Secure(true),
csrf.Path("/"),
csrf.CookieName(configuration.CookieName+"_csrf"),
csrf.Domain(configuration.CookieDomain),
)
r := http.NewServeMux()
r.HandleFunc("/", ShowHomeHandler)
r.HandleFunc("/verify", VerifyHandler)
r.HandleFunc("/logout", LogoutHandler)
r.HandleFunc("/health", HealthHandler)
log.Info("Loading server...", zap.Uint("port", configuration.Port))
// transform PORT from int to string like ":<port>"
var port = ":" + fmt.Sprint(configuration.Port)
return http.ListenAndServeTLS(port, configuration.Certificate, configuration.PrivateKey, CSRF(r))
}
// health handler
func HealthHandler(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("OK"))
}
// default handler
func ShowHomeHandler(w http.ResponseWriter, r *http.Request) {
// Init ctx
ctx := &Context{
CsrfToken: csrf.Token(r),
Ip: GetIp(r),
State: "out",
Url: GetHost(r),
}
log.Sugar().Debug("server: home requested", zap.String("ip", ctx.Ip), "request", r)
// get jwt from cookie
ctx.UserCookie, _ = r.Cookie(configuration.CookieName)
ctx.Claims = GetValidJwtClaims(ctx.UserCookie, ctx.Ip, ctx.Url)
// no valid jwt (or expired, or bad domain)
if ctx.Claims == nil {
ctx.FormData = GetFormData(r)
if ctx.FormData == nil {
switch {
// first access (no form nor cookie)
case ctx.UserCookie == nil:
ctx.HttpReturnCode = http.StatusUnauthorized
ctx.State = "out"
// bad domain (only cookie)
case ctx.UserCookie != nil:
log.Error("server: bad token", zap.String("ip", ctx.Ip))
ctx.HttpReturnCode = http.StatusForbidden
ctx.State = "out"
// if cookie is still valid, it means the user is trying to access an unauthorized Domain
if err := ctx.UserCookie.Valid(); err == nil {
ctx.ErrorMessage = "Unauthorized access"
}
}
log.Info("Loading Template", zap.Int("status", ctx.HttpReturnCode), zap.Error(LoadTemplate(&w, ctx)))
return
}
// from here formdata is provided
ctx.User = GetValidUserFromFormData(ctx.FormData, ctx.Url)
switch {
// bad credentials
case ctx.User == nil:
time.Sleep(500 * time.Millisecond)
ctx.HttpReturnCode = http.StatusUnauthorized
ctx.State = "out"
ctx.ErrorMessage = "Bad credentials"
// data provided are valid
case ctx.User != nil:
log.Info("server: new jwt", zap.String("ip", ctx.Ip))
ctx.HttpReturnCode = http.StatusMultipleChoices
ctx.State = "in"
// set MagicIp if user allow connection from anyip
claimsIp := ctx.Ip
if ctx.FormData.AnyIp {
claimsIp = configuration.MagicIp
}
ctx.GeneratedCookie = CreateJwtCookie(ctx.User.Username, claimsIp, ctx.User.AllowedDomains)
}
log.Info("Loading Template", zap.Int("status", ctx.HttpReturnCode), zap.Error(LoadTemplate(&w, ctx)))
return
}
// from here, we have a valid Jwt
// refresh needed
if time.Until(ctx.Claims.ExpiresAt.Time) < (configuration.TokenRefresh * time.Minute) {
ctx.User = GetUser(ctx.Claims.Subject)
switch {
// bad user
case ctx.User == nil:
log.Error("server: user not found", zap.String("user", ctx.Claims.Subject))
ctx.HttpReturnCode = http.StatusForbidden
ctx.State = "out"
ctx.GeneratedCookie = &http.Cookie{
Name: configuration.CookieName,
Value: "",
Expires: time.Now(),
Domain: configuration.CookieDomain,
MaxAge: -1,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
// refreshed user
case ctx.User != nil:
log.Info("server: renew jwt", zap.String("ip", ctx.Ip))
ctx.HttpReturnCode = http.StatusMultipleChoices
ctx.State = "in"
ctx.GeneratedCookie = CreateJwtCookie(ctx.User.Username, ctx.Ip, ctx.User.AllowedDomains)
// validate new cookie domain is allowed
if GetValidJwtClaims(ctx.GeneratedCookie, ctx.Ip, ctx.Url) == nil {
ctx.ErrorMessage = "Restricted Area"
}
}
log.Info("Loading Template", zap.Int("status", ctx.HttpReturnCode), zap.Error(LoadTemplate(&w, ctx)))
return
}
// all validations passed
ctx.HttpReturnCode = http.StatusOK
ctx.State = "in"
log.Debug("Loading Template", zap.Int("status", ctx.HttpReturnCode), zap.Error(LoadTemplate(&w, ctx)))
}
// remove cookie and redirect to home
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
ip := GetIp(r)
log.Sugar().Debug("server: logout requested", zap.String("ip", ip), "request", r)
// remove cookie if exists
if c, _ := r.Cookie(configuration.CookieName); c != nil {
log.Info("server: delete jwt", zap.String("ip", ip))
http.SetCookie(w, &http.Cookie{
Name: configuration.CookieName,
Value: "",
Expires: time.Now(),
Domain: configuration.CookieDomain,
MaxAge: -1,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
} else {
// no cookie, prevent bruteforce with sleeptime
time.Sleep(500 * time.Millisecond)
}
// return to home
http.Redirect(w, r, "/", http.StatusFound)
}
// remove cookie and redirect to home
func VerifyHandler(w http.ResponseWriter, r *http.Request) {
// Init ctx
ctx := &Context{
Ip: GetIp(r),
Url: GetHost(r),
}
log.Sugar().Debug("server: verify requested", zap.String("ip", ctx.Ip), "request", r)
// get jwt from cookie
ctx.UserCookie, _ = r.Cookie(configuration.CookieName)
ctx.Claims = GetValidJwtClaims(ctx.UserCookie, ctx.Ip, ctx.Url)
// if no valid claims
if ctx.Claims == nil {
w.WriteHeader(http.StatusForbidden)
// no cookie, prevent bruteforce with sleeptime
time.Sleep(500 * time.Millisecond)
}
w.WriteHeader(http.StatusOK)
return
}
// load template and return http code and html
func LoadTemplate(w *http.ResponseWriter, ctx *Context) error {
if w == nil || ctx == nil {
return errors.New("server: responsewriter and context are mandatory")
}
log.Sugar().Debug("server: final context", zap.String("ip", ctx.Ip), "context", ctx)
if ctx.HttpReturnCode < 100 || ctx.HttpReturnCode > 599 {
(*w).WriteHeader(http.StatusNotImplemented)
return errors.New("server: bad http return code")
}
if ctx.GeneratedCookie != nil {
http.SetCookie(*w, ctx.GeneratedCookie)
}
if ctx.State == "in" {
(*w).Header().Add("Remote-User", ctx.GetUsername())
}
(*w).WriteHeader(ctx.HttpReturnCode)
tplData := ctx.ToMap()
// parse data in template
parsedTemplate, _ := template.ParseFiles(configuration.HtmlFile)
// return http code and html
return parsedTemplate.Execute(*w, tplData)
}
func (ctx *Context) ToMap() map[string]interface{} {
return map[string]interface{}{
"username": ctx.GetUsername(),
"state": ctx.State,
"csrf": ctx.CsrfToken,
"ip": ctx.Ip,
"error": ctx.ErrorMessage,
}
}
func (ctx *Context) GetUsername() string {
switch {
case ctx.User != nil:
return ctx.User.Username
case ctx.Claims != nil:
return ctx.Claims.Subject
case ctx.FormData != nil:
return ctx.FormData.Username
default:
return ""
}
}