forked from louketo/louketo-proxy
-
Notifications
You must be signed in to change notification settings - Fork 43
/
utils.go
462 lines (376 loc) · 10.3 KB
/
utils.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
Copyright 2015 All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"bytes"
"crypto/hmac"
cryptorand "crypto/rand"
"crypto/sha256"
sha "crypto/sha512"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"github.com/gogatekeeper/gatekeeper/pkg/apperrors"
"github.com/gogatekeeper/gatekeeper/pkg/constant"
"github.com/urfave/cli/v2"
)
var (
AllHTTPMethods = []string{
http.MethodDelete,
http.MethodGet,
http.MethodHead,
http.MethodOptions,
http.MethodPatch,
http.MethodPost,
http.MethodPut,
http.MethodTrace,
}
)
var (
symbolsFilter = regexp.MustCompilePOSIX("[_$><\\[\\].,\\+-/'%^&*()!\\\\]+")
)
// getRequestHostURL returns the hostname from the request
func GetRequestHostURL(req *http.Request) string {
scheme := constant.UnsecureScheme
if req.TLS != nil {
scheme = constant.SecureScheme
}
redirect := fmt.Sprintf("%s://%s",
DefaultTo(req.Header.Get("X-Forwarded-Proto"), scheme),
DefaultTo(req.Header.Get("X-Forwarded-Host"), req.Host))
return redirect
}
// decodeKeyPairs converts a list of strings (key=pair) to a map
func DecodeKeyPairs(list []string) (map[string]string, error) {
keyPairs := make(map[string]string)
for _, pair := range list {
items := strings.Split(pair, "=")
if len(items) < 2 || items[0] == "" {
return keyPairs, fmt.Errorf("invalid tag '%s' should be key=pair", pair)
}
keyPairs[items[0]] = strings.Join(items[1:], "=")
}
return keyPairs, nil
}
// IsValidHTTPMethod ensure this is a valid http method type
func IsValidHTTPMethod(method string) bool {
for _, x := range AllHTTPMethods {
if method == x {
return true
}
}
return false
}
// defaultTo returns the value of the default
func DefaultTo(v, d string) string {
if v != "" {
return v
}
return d
}
// fileExists check if a file exists
func FileExists(filename string) bool {
if _, err := os.Stat(filename); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// hasAccess checks we have all or any of the needed items in the list
func HasAccess(need, have []string, all bool) bool {
if len(need) == 0 {
return true
}
var matched int
for _, x := range need {
found := ContainedIn(x, have)
switch found {
case true:
if !all {
return true
}
matched++
default:
if all {
return false
}
}
}
return matched > 0
}
// containedIn checks if a value in a list of a strings
func ContainedIn(value string, list []string) bool {
for _, x := range list {
if x == value {
return true
}
}
return false
}
// containsSubString checks if substring exists
func ContainsSubString(value string, list []string) bool {
for _, x := range list {
if strings.Contains(value, x) {
return true
}
}
return false
}
// tryDialEndpoint dials the upstream endpoint via plain HTTP
func TryDialEndpoint(location *url.URL) (net.Conn, error) {
switch dialAddress := DialAddress(location); location.Scheme {
case constant.UnsecureScheme:
return net.Dial("tcp", dialAddress)
default:
return tls.Dial("tcp", dialAddress, &tls.Config{
Rand: cryptorand.Reader,
//nolint:gas
InsecureSkipVerify: true,
})
}
}
// isUpgradedConnection checks to see if the request is requesting
func IsUpgradedConnection(req *http.Request) bool {
return req.Header.Get(constant.HeaderUpgrade) != ""
}
// transferBytes transfers bytes between the sink and source
func TransferBytes(src io.Reader, dest io.Writer, wg *sync.WaitGroup) (int64, error) {
defer wg.Done()
return io.Copy(dest, src)
}
// tryUpdateConnection attempt to upgrade the connection to a http pdy stream
func TryUpdateConnection(req *http.Request, writer http.ResponseWriter, endpoint *url.URL) error {
// step: dial the endpoint
server, err := TryDialEndpoint(endpoint)
if err != nil {
return err
}
defer server.Close()
// @check the response writer implements Hijack method
hijacker, assertOk := writer.(http.Hijacker)
if !assertOk {
return fmt.Errorf("writer does not implement http.Hijacker method")
}
// @step: get the client connection object
client, _, err := hijacker.Hijack()
if err != nil {
return err
}
defer client.Close()
// step: write the request to upstream
if err = req.Write(server); err != nil {
return err
}
// @step: copy the data between client and upstream endpoint
var wg sync.WaitGroup
wg.Add(2)
go func() { _, _ = TransferBytes(server, client, &wg) }()
go func() { _, _ = TransferBytes(client, server, &wg) }()
wg.Wait()
return nil
}
// dialAddress extracts the dial address from the url
func DialAddress(location *url.URL) string {
items := strings.Split(location.Host, ":")
if len(items) != 2 {
switch location.Scheme {
case constant.UnsecureScheme:
return location.Host + ":80"
default:
return location.Host + ":443"
}
}
return location.Host
}
// findCookie looks for a cookie in a list of cookies
func FindCookie(name string, cookies []*http.Cookie) *http.Cookie {
for _, cookie := range cookies {
if cookie.Name == name {
return cookie
}
}
return nil
}
// toHeader is a helper method to play nice in the headers
func ToHeader(v string) string {
symbols := symbolsFilter.Split(v, -1)
list := make([]string, 0, len(symbols))
// step: filter out any symbols and convert to dashes
for _, x := range symbols {
list = append(list, Capitalize(x))
}
return strings.Join(list, "-")
}
// capitalize capitalizes the first letter of a word
func Capitalize(word string) string {
if word == "" {
return ""
}
r, n := utf8.DecodeRuneInString(word)
return string(unicode.ToUpper(r)) + word[n:]
}
// mergeMaps simples copies the keys from source to destination
func MergeMaps(dest, source map[string]string) map[string]string {
for k, v := range source {
dest[k] = v
}
return dest
}
// getWithin calculates a duration of x percent of the time period, i.e. something
// expires in 1 hours, get me a duration within 80%
func GetWithin(expires time.Time, within float64) time.Duration {
left := expires.UTC().Sub(time.Now().UTC()).Seconds()
if left <= 0 {
return time.Duration(0)
}
seconds := int(left * within)
return time.Duration(seconds) * time.Second
}
// getHashKey returns a hash of the encodes jwt token
func GetHashKey(token string) string {
hash := sha.Sum512([]byte(token))
return base64.RawStdEncoding.EncodeToString(hash[:])
}
// printError display the command line usage and error
func PrintError(message string, args ...interface{}) cli.ExitCoder {
return cli.Exit(fmt.Sprintf("[error] "+message, args...), 1)
}
// realIP retrieves the client ip address from a http request
func RealIP(req *http.Request) string {
rAddr := req.RemoteAddr
if ip := req.Header.Get(constant.HeaderXForwardedFor); ip != "" {
rAddr = strings.Split(ip, ", ")[0]
} else if ip := req.Header.Get(constant.HeaderXRealIP); ip != "" {
rAddr = ip
} else {
rAddr, _, _ = net.SplitHostPort(rAddr)
}
return rAddr
}
// GetRefreshTokenFromCookie returns the refresh token from the cookie if any
func GetRefreshTokenFromCookie(req *http.Request, cookieName string) (string, error) {
token, err := GetTokenInCookie(req, cookieName)
if err != nil {
return "", err
}
return token, nil
}
// getTokenInRequest returns the token from the http request
//
//nolint:cyclop
func GetTokenInRequest(
req *http.Request,
name string,
skipAuthorizationHeaderIdentity bool,
tokenHeader string,
) (string, bool, error) {
bearer := true
token := ""
var err error
if tokenHeader == "" && !skipAuthorizationHeaderIdentity {
token, err = GetTokenInBearer(req)
if err != nil && err != apperrors.ErrSessionNotFound {
return "", false, err
}
}
if tokenHeader != "" {
token, err = GetTokenInHeader(req, tokenHeader)
if err != nil && err != apperrors.ErrSessionNotFound {
return "", false, err
}
}
// step: check for a token in the authorization header
if err != nil || (err == nil && skipAuthorizationHeaderIdentity) {
if token, err = GetTokenInCookie(req, name); err != nil {
return token, false, err
}
bearer = false
}
return token, bearer, nil
}
// getTokenInBearer retrieves a access token from the authorization header
func GetTokenInBearer(req *http.Request) (string, error) {
token := req.Header.Get(constant.AuthorizationHeader)
if token == "" {
return "", apperrors.ErrSessionNotFound
}
items := strings.Split(token, " ")
if len(items) != 2 {
return "", apperrors.ErrInvalidSession
}
if items[0] != constant.AuthorizationType {
return "", apperrors.ErrSessionNotFound
}
return items[1], nil
}
// getTokenInHeader retrieves a token from the header
func GetTokenInHeader(req *http.Request, headerName string) (string, error) {
token := req.Header.Get(headerName)
if token == "" {
return "", apperrors.ErrSessionNotFound
}
return token, nil
}
// getTokenInCookie retrieves the access token from the request cookies
func GetTokenInCookie(req *http.Request, name string) (string, error) {
var token bytes.Buffer
if cookie := FindCookie(name, req.Cookies()); cookie != nil {
token.WriteString(cookie.Value)
}
// add also divided cookies
for i := 1; i < 600; i++ {
cookie := FindCookie(name+"-"+strconv.Itoa(i), req.Cookies())
if cookie == nil {
break
}
token.WriteString(cookie.Value)
}
if token.Len() == 0 {
return "", apperrors.ErrSessionNotFound
}
return token.String(), nil
}
func GenerateHmac(req *http.Request, encKey string) (string, error) {
body, err := io.ReadAll(req.Body)
if err != nil {
return "", err
}
stringToSign := fmt.Sprintf(
"%s\n%s%s\n%s;%s;%s",
req.Method,
req.URL.Path,
req.URL.RawQuery,
req.Header.Get(constant.AuthorizationHeader),
req.Host,
sha256.Sum256(body),
)
mac := hmac.New(sha256.New, []byte(encKey))
mac.Write([]byte(stringToSign))
reqHmac := mac.Sum(nil)
hexHmac := hex.EncodeToString(reqHmac)
return hexHmac, nil
}