-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
response.go
300 lines (223 loc) · 9.29 KB
/
response.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
package handlers
import (
"fmt"
"net/url"
"path"
"time"
"github.com/google/uuid"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/authorization"
"github.com/authelia/authelia/v4/internal/middlewares"
"github.com/authelia/authelia/v4/internal/model"
"github.com/authelia/authelia/v4/internal/oidc"
"github.com/authelia/authelia/v4/internal/session"
)
// Handle1FAResponse handle the redirection upon 1FA authentication.
func Handle1FAResponse(ctx *middlewares.AutheliaCtx, targetURI, requestMethod string, username string, groups []string) {
var err error
if len(targetURI) == 0 {
defaultRedirectionURL := ctx.GetDefaultRedirectionURL()
if !ctx.Providers.Authorizer.IsSecondFactorEnabled() && defaultRedirectionURL != nil {
if err = ctx.SetJSONBody(redirectResponse{Redirect: defaultRedirectionURL.String()}); err != nil {
ctx.Logger.Errorf("Unable to set default redirection URL in body: %s", err)
}
} else {
ctx.ReplyOK()
}
return
}
var targetURL *url.URL
if targetURL, err = url.ParseRequestURI(targetURI); err != nil {
ctx.Error(fmt.Errorf("unable to parse target URL %s: %w", targetURI, err), messageAuthenticationFailed)
return
}
_, requiredLevel := ctx.Providers.Authorizer.GetRequiredLevel(
authorization.Subject{
Username: username,
Groups: groups,
IP: ctx.RemoteIP(),
},
authorization.NewObject(targetURL, requestMethod))
ctx.Logger.Debugf("Required level for the URL %s is %s", targetURI, requiredLevel)
if requiredLevel == authorization.TwoFactor {
ctx.Logger.Warnf("%s requires 2FA, cannot be redirected yet", targetURI)
ctx.ReplyOK()
return
}
if !ctx.IsSafeRedirectionTargetURI(targetURL) {
ctx.Logger.Debugf("Redirection URL %s is not safe", targetURI)
defaultRedirectionURL := ctx.GetDefaultRedirectionURL()
if !ctx.Providers.Authorizer.IsSecondFactorEnabled() && defaultRedirectionURL != nil {
if err = ctx.SetJSONBody(redirectResponse{Redirect: defaultRedirectionURL.String()}); err != nil {
ctx.Logger.Errorf("Unable to set default redirection URL in body: %s", err)
}
return
}
ctx.ReplyOK()
return
}
ctx.Logger.Debugf("Redirection URL %s is safe", targetURI)
if err = ctx.SetJSONBody(redirectResponse{Redirect: targetURI}); err != nil {
ctx.Logger.Errorf("Unable to set redirection URL in body: %s", err)
}
}
// Handle2FAResponse handle the redirection upon 2FA authentication.
func Handle2FAResponse(ctx *middlewares.AutheliaCtx, targetURI string) {
var err error
if len(targetURI) == 0 {
defaultRedirectionURL := ctx.GetDefaultRedirectionURL()
if defaultRedirectionURL == nil {
ctx.ReplyOK()
return
}
if err = ctx.SetJSONBody(redirectResponse{Redirect: defaultRedirectionURL.String()}); err != nil {
ctx.Logger.Errorf("Unable to set default redirection URL in body: %s", err)
}
return
}
var (
parsedURI *url.URL
safe bool
)
if parsedURI, err = url.ParseRequestURI(targetURI); err != nil {
ctx.Error(fmt.Errorf("unable to determine if URI '%s' is safe to redirect to: failed to parse URI '%s': %w", targetURI, targetURI, err), messageMFAValidationFailed)
return
}
safe = ctx.IsSafeRedirectionTargetURI(parsedURI)
if safe {
ctx.Logger.Debugf("Redirection URL %s is safe", targetURI)
if err = ctx.SetJSONBody(redirectResponse{Redirect: targetURI}); err != nil {
ctx.Logger.Errorf("Unable to set redirection URL in body: %s", err)
}
return
}
ctx.ReplyOK()
}
// handleOIDCWorkflowResponse handle the redirection upon authentication in the OIDC workflow.
func handleOIDCWorkflowResponse(ctx *middlewares.AutheliaCtx, userSession *session.UserSession, targetURI, workflowID string) {
switch {
case len(workflowID) != 0:
handleOIDCWorkflowResponseWithID(ctx, userSession, workflowID)
case len(targetURI) != 0:
handleOIDCWorkflowResponseWithTargetURL(ctx, userSession, targetURI)
default:
ctx.Error(fmt.Errorf("invalid post data: must contain either a target url or a workflow id"), messageAuthenticationFailed)
}
}
func handleOIDCWorkflowResponseWithTargetURL(ctx *middlewares.AutheliaCtx, userSession *session.UserSession, targetURI string) {
var (
issuerURL *url.URL
targetURL *url.URL
err error
)
if targetURL, err = url.ParseRequestURI(targetURI); err != nil {
ctx.Error(fmt.Errorf("unable to parse target URL '%s': %w", targetURI, err), messageAuthenticationFailed)
return
}
issuerURL = ctx.RootURL()
if targetURL.Host != issuerURL.Host {
ctx.Error(fmt.Errorf("unable to redirect to '%s': target host '%s' does not match expected issuer host '%s'", targetURL, targetURL.Host, issuerURL.Host), messageAuthenticationFailed)
return
}
if userSession.IsAnonymous() {
ctx.Error(fmt.Errorf("unable to redirect to '%s': user is anonymous", targetURL), messageAuthenticationFailed)
return
}
if err = ctx.SetJSONBody(redirectResponse{Redirect: targetURL.String()}); err != nil {
ctx.Logger.Errorf("Unable to set default redirection URL in body: %s", err)
}
}
func handleOIDCWorkflowResponseWithID(ctx *middlewares.AutheliaCtx, userSession *session.UserSession, id string) {
var (
workflowID uuid.UUID
client oidc.Client
consent *model.OAuth2ConsentSession
err error
)
if workflowID, err = uuid.Parse(id); err != nil {
ctx.Error(fmt.Errorf("unable to parse consent session challenge id '%s': %w", id, err), messageAuthenticationFailed)
return
}
if consent, err = ctx.Providers.StorageProvider.LoadOAuth2ConsentSessionByChallengeID(ctx, workflowID); err != nil {
ctx.Error(fmt.Errorf("unable to load consent session by challenge id '%s': %w", id, err), messageAuthenticationFailed)
return
}
if consent.Responded() {
ctx.Error(fmt.Errorf("consent has already been responded to '%s': %w", id, err), messageAuthenticationFailed)
return
}
if client, err = ctx.Providers.OpenIDConnect.GetFullClient(ctx, consent.ClientID); err != nil {
ctx.Error(fmt.Errorf("unable to get client for client with id '%s' with consent challenge id '%s': %w", id, consent.ChallengeID, err), messageAuthenticationFailed)
return
}
if userSession.IsAnonymous() {
ctx.Error(fmt.Errorf("unable to redirect for authorization/consent for client with id '%s' with consent challenge id '%s': user is anonymous", client.GetID(), consent.ChallengeID), messageAuthenticationFailed)
return
}
level := client.GetAuthorizationPolicyRequiredLevel(authorization.Subject{Username: userSession.Username, Groups: userSession.Groups, IP: ctx.RemoteIP()})
switch {
case authorization.IsAuthLevelSufficient(userSession.AuthenticationLevel, level), level == authorization.Denied:
var (
targetURL *url.URL
form url.Values
)
targetURL = ctx.RootURL()
if form, err = consent.GetForm(); err != nil {
ctx.Error(fmt.Errorf("unable to get authorization form values from consent session with challenge id '%s': %w", consent.ChallengeID, err), messageAuthenticationFailed)
return
}
form.Set(queryArgConsentID, workflowID.String())
targetURL.Path = path.Join(targetURL.Path, oidc.EndpointPathAuthorization)
targetURL.RawQuery = form.Encode()
if err = ctx.SetJSONBody(redirectResponse{Redirect: targetURL.String()}); err != nil {
ctx.Logger.Errorf("Unable to set default redirection URL in body: %s", err)
}
default:
ctx.Logger.Warnf("OpenID Connect client '%s' requires 2FA, cannot be redirected yet", client.GetID())
ctx.ReplyOK()
return
}
}
func markAuthenticationAttempt(ctx *middlewares.AutheliaCtx, successful bool, bannedUntil *time.Time, username string, authType string, errAuth error) (err error) {
// We only Mark if there was no underlying error.
ctx.Logger.Debugf("Mark %s authentication attempt made by user '%s'", authType, username)
var (
requestURI, requestMethod string
)
if referer := ctx.Request.Header.Referer(); referer != nil {
var refererURL *url.URL
if refererURL, err = url.ParseRequestURI(string(referer)); err == nil {
requestURI = refererURL.Query().Get(queryArgRD)
requestMethod = refererURL.Query().Get(queryArgRM)
}
}
if err = ctx.Providers.Regulator.Mark(ctx, successful, bannedUntil != nil, username, requestURI, requestMethod, authType); err != nil {
ctx.Logger.WithError(err).Errorf("Unable to mark %s authentication attempt by user '%s'", authType, username)
return err
}
if successful {
ctx.Logger.Debugf("Successful %s authentication attempt made by user '%s'", authType, username)
} else {
switch {
case errAuth != nil:
ctx.Logger.WithError(errAuth).Errorf("Unsuccessful %s authentication attempt by user '%s'", authType, username)
case bannedUntil != nil:
ctx.Logger.Errorf("Unsuccessful %s authentication attempt by user '%s' and they are banned until %s", authType, username, bannedUntil)
default:
ctx.Logger.Errorf("Unsuccessful %s authentication attempt by user '%s'", authType, username)
}
}
return nil
}
func respondUnauthorized(ctx *middlewares.AutheliaCtx, message string) {
ctx.SetStatusCode(fasthttp.StatusUnauthorized)
ctx.SetJSONError(message)
}
// SetStatusCodeResponse writes a response status code and an appropriate body on either a
// *fasthttp.RequestCtx or *middlewares.AutheliaCtx.
func SetStatusCodeResponse(ctx *fasthttp.RequestCtx, statusCode int) {
ctx.Response.Reset()
middlewares.SetContentTypeTextPlain(ctx)
ctx.SetStatusCode(statusCode)
ctx.SetBodyString(fmt.Sprintf("%d %s", statusCode, fasthttp.StatusMessage(statusCode)))
}