-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathauth.go
58 lines (47 loc) · 1.81 KB
/
auth.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
package gomitmproxy
import (
"encoding/base64"
"net/http"
"strings"
"github.com/AdguardTeam/gomitmproxy/proxyutil"
)
// basicAuth returns an HTTP authorization header value according to RFC2617.
// See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt:
// "To receive authorization, the client sends the userid and password,
// separated by a single colon (":") character, within a base64 encoded string
// in the credentials."
// It is not meant to be urlencoded.
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
// newNotAuthorizedResponse creates a new "407 (Proxy Authentication Required)"
// response.
func newNotAuthorizedResponse(session *Session) *http.Response {
res := proxyutil.NewResponse(http.StatusProxyAuthRequired, nil, session.req)
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authenticate.
res.Header.Set("Proxy-Authenticate", "Basic")
return res
}
// authorize checks the "Proxy-Authorization" header and returns true if the
// request is authorized. If it returns false, it also returns the response that
// should be written to the client.
func (p *Proxy) authorize(session *Session) (bool, *http.Response) {
if session.ctx.parent != nil {
// If we're here, it means the connection is authorized already.
return true, nil
}
if p.Username == "" {
return true, nil
}
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization.
proxyAuth := session.req.Header.Get("Proxy-Authorization")
if strings.Index(proxyAuth, "Basic ") != 0 {
return false, newNotAuthorizedResponse(session)
}
authHeader := proxyAuth[len("Basic "):]
if authHeader != basicAuth(p.Username, p.Password) {
return false, newNotAuthorizedResponse(session)
}
return true, nil
}