This repository has been archived by the owner on Jun 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclientHandler.go
200 lines (178 loc) · 5.92 KB
/
clientHandler.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
package main
import (
"authelia-basic-2fa/authelia"
"authelia-basic-2fa/util"
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"github.com/labstack/echo/v4"
)
// Used to impersonate the client when interacting with Authelia
type ClientHandler struct {
ctx echo.Context
clientCookies map[string]*http.Cookie
proxyCookies map[string]*http.Cookie
}
// Creates a new ClientHandler
func NewClientHandler(ctx echo.Context) *ClientHandler {
clientCookies := map[string]*http.Cookie{}
// save client's cookies (e.g. Authelia session) to use for sub-requests
for _, cookie := range ctx.Cookies() {
// ignore non-whitelisted client cookies
if _, exists := util.CookieWhitelist[cookie.Name]; exists {
util.SLogger.Debugf("Saving client cookie: %+v", cookie)
clientCookies[cookie.Name] = cookie
} else {
util.SLogger.Debugf("NOT saving client cookie: %+v", cookie)
}
}
return &ClientHandler{
ctx: ctx,
clientCookies: clientCookies,
proxyCookies: map[string]*http.Cookie{},
}
}
// Performs first factor authentication with Authelia and returns the JSON response status
func (a *ClientHandler) checkFirstFactor(credentials *Credentials) (int, error) {
return a.doStatusPost(&authelia.FirstFactorRequest{
Username: credentials.Username,
Password: credentials.Password,
KeepMeLoggedIn: false,
}, authelia.FirstFactorUrl, false)
}
// Performs TOTP second factor authentication with Authelia and returns the JSON response status
func (a *ClientHandler) checkTOTP(credentials *Credentials) (int, error) {
return a.doStatusPost(&authelia.TOTPRequest{
Token: credentials.TOTP,
}, authelia.TOTPUrl, false)
}
// Performs a POST request to an Authelia endpoint and returns the JSON response status
func (a *ClientHandler) doStatusPost(data interface{}, endpoint string, includeAuthorization bool) (int, error) {
jsonBody, err := json.Marshal(data)
if err != nil {
return 0, err
}
resp, err := a.doRequest(endpoint, "POST", jsonBody, includeAuthorization)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if util.IsBad(resp.StatusCode) {
return resp.StatusCode, nil
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
statusResponse := authelia.StatusResponse{}
if err = json.Unmarshal(bodyBytes, &statusResponse); err != nil {
return 0, err
}
if statusResponse.Status == "OK" {
return resp.StatusCode, nil
} else {
return 500, nil
}
}
// Adds whitelisted headers from the client's original request to a sub-request
func (a *ClientHandler) cloneHeaders(req *http.Request, includeAuthorization bool) {
// clone host, per
req.Host = a.ctx.Request().Host
// clone headers
for key, values := range a.ctx.Request().Header {
keyStr := strings.ToLower(key)
if keyStr == "authorization" && !includeAuthorization {
continue
}
if _, exists := util.HeaderClientWhitelist[keyStr]; exists {
util.SLogger.Debugf("Restoring header: %s, %v", key, values)
// Authelia expects Proxy-Authorization
// https://github.com/authelia/authelia/blob/829757d3bc8196d6520f24479370a9037fbdb4de/internal/handlers/handler_verify.go#L232
if keyStr == "authorization" {
key = "Proxy-Authorization"
}
for _, value := range values {
req.Header.Set(key, value)
}
} else {
util.SLogger.Debugf("NOT restoring header: %s, %v", key, values)
}
}
}
// Saves whitelisted response cookies to ClientHandler, overwriting old ones with same name
func (a *ClientHandler) saveCookies(resp *http.Response) {
for _, cookie := range resp.Cookies() {
if _, exists := util.CookieWhitelist[cookie.Name]; exists {
util.SLogger.Debugf("Saving proxy cookie: %+v", cookie)
a.proxyCookies[cookie.Name] = cookie
} else {
util.SLogger.Debugf("NOT saving proxy cookie: %+v", cookie)
}
}
}
// Adds saved ClientHandler cookies to a request
func (a *ClientHandler) restoreCookies(req *http.Request) {
for _, cookie := range a.clientCookies {
// allow proxyCookies to override clientCookies
if _, exists := a.proxyCookies[cookie.Name]; !exists {
util.SLogger.Debugf("Restoring client cookie: %+v", cookie)
req.AddCookie(cookie)
} else {
util.SLogger.Debugf("NOT restoring client cookie (proxy cookie override): %+v", cookie)
}
}
for _, cookie := range a.proxyCookies {
util.SLogger.Debugf("Restoring proxy cookie: %+v", cookie)
req.AddCookie(cookie)
}
}
// Performs a request to an Authelia endpoint. Don't forget to close the response body.
func (a *ClientHandler) doRequest(
requestUri string, requestMethod string, jsonBody []byte, includeAuthorization bool) (*http.Response, error) {
req, err := http.NewRequest(requestMethod, requestUri, bytes.NewReader(jsonBody))
if err != nil {
return nil, err
}
a.cloneHeaders(req, includeAuthorization)
a.restoreCookies(req)
if jsonBody != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
a.saveCookies(resp)
return resp, nil
}
// Checks if the client has valid Authorization
func (a *ClientHandler) checkAuthorization() (int, map[string]string, error) {
resp, err := a.doRequest(authelia.VerifyUrl, "GET", nil, true)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
returnHeaders := a.getServerReturnHeaders(resp)
return resp.StatusCode, returnHeaders, nil
}
// Checks if the client has a valid Authelia session
func (a *ClientHandler) checkSession() (int, map[string]string, error) {
resp, err := a.doRequest(authelia.VerifyUrl, "GET", nil, false)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
returnHeaders := a.getServerReturnHeaders(resp)
return resp.StatusCode, returnHeaders, nil
}
func (a *ClientHandler) getServerReturnHeaders(resp *http.Response) map[string]string {
returnHeaders := map[string]string{}
for key, values := range resp.Header {
if _, ok := util.HeaderServerWhitelist[strings.ToLower(key)]; ok {
returnHeaders[key] = values[0]
}
}
return returnHeaders
}