forked from nzlov/forwardingproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
160 lines (135 loc) · 4.59 KB
/
proxy.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
// Copyright (C) 2018 Betalo AB - All Rights Reserved
// Courtesy: https://medium.com/@mlowicki/http-s-proxy-in-golang-in-less-than-100-lines-of-code-6a51c2f2c38c
// $ openssl req -newkey rsa:2048 -nodes -keyout server.key -new -x509 -sha256 -days 3650 -out server.pem
package main
import (
"encoding/base64"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"strings"
"time"
"go.uber.org/zap"
)
// Proxy is a HTTPS forward proxy.
type Proxy struct {
Logger *zap.Logger
AuthUser string
AuthPass string
Avoid string
ForwardingHTTPProxy *httputil.ReverseProxy
DestDialTimeout time.Duration
DestReadTimeout time.Duration
DestWriteTimeout time.Duration
ClientReadTimeout time.Duration
ClientWriteTimeout time.Duration
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p.Logger.Info("Incoming request", zap.String("host", r.Host))
if p.AuthUser != "" && p.AuthPass != "" {
user, pass, ok := parseBasicProxyAuth(r.Header.Get("Proxy-Authorization"))
if !ok || user != p.AuthUser || pass != p.AuthPass {
p.Logger.Warn("Authorization attempt with invalid credentials")
http.Error(w, http.StatusText(http.StatusProxyAuthRequired), http.StatusProxyAuthRequired)
return
}
}
if r.URL.Scheme == "http" {
p.handleHTTP(w, r)
} else {
p.handleTunneling(w, r)
}
}
func (p *Proxy) handleHTTP(w http.ResponseWriter, r *http.Request) {
p.Logger.Debug("Got HTTP request", zap.String("host", r.Host))
if p.Avoid != "" && strings.Contains(r.Host, p.Avoid) == true {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusMethodNotAllowed)
return
}
p.ForwardingHTTPProxy.ServeHTTP(w, r)
}
func (p *Proxy) handleTunneling(w http.ResponseWriter, r *http.Request) {
if p.Avoid != "" && strings.Contains(r.Host, p.Avoid) == true {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusMethodNotAllowed)
return
}
if r.Method != http.MethodConnect {
p.Logger.Info("Method not allowed", zap.String("method", r.Method))
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
p.Logger.Debug("Connecting", zap.String("host", r.Host))
destConn, err := net.DialTimeout("tcp", r.Host, p.DestDialTimeout)
if err != nil {
p.Logger.Error("Destination dial failed", zap.Error(err))
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
p.Logger.Debug("Connected", zap.String("host", r.Host))
w.WriteHeader(http.StatusOK)
p.Logger.Debug("Hijacking", zap.String("host", r.Host))
hijacker, ok := w.(http.Hijacker)
if !ok {
p.Logger.Error("Hijacking not supported")
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
clientConn, _, err := hijacker.Hijack()
if err != nil {
p.Logger.Error("Hijacking failed", zap.Error(err))
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
p.Logger.Debug("Hijacked connection", zap.String("host", r.Host))
now := time.Now()
clientConn.SetReadDeadline(now.Add(p.ClientReadTimeout))
clientConn.SetWriteDeadline(now.Add(p.ClientWriteTimeout))
destConn.SetReadDeadline(now.Add(p.DestReadTimeout))
destConn.SetWriteDeadline(now.Add(p.DestWriteTimeout))
go transfer(destConn, clientConn)
go transfer(clientConn, destConn)
}
func transfer(dest io.WriteCloser, src io.ReadCloser) {
defer func() { _ = dest.Close() }()
defer func() { _ = src.Close() }()
_, _ = io.Copy(dest, src)
}
// parseBasicProxyAuth parses an HTTP Basic Authorization string.
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseBasicProxyAuth(authz string) (username, password string, ok bool) {
const prefix = "Basic "
if !strings.HasPrefix(authz, prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(authz[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
// NewForwardingHTTPProxy retuns a new reverse proxy that takes an incoming
// request and sends it to another server, proxying the response back to the
// client.
//
// See: https://golang.org/pkg/net/http/httputil/#ReverseProxy
func NewForwardingHTTPProxy(logger *log.Logger) *httputil.ReverseProxy {
director := func(req *http.Request) {
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
}
// TODO:(alesr) Use timeouts specified via flags to customize the default
// transport used by the reverse proxy.
return &httputil.ReverseProxy{
ErrorLog: logger,
Director: director,
}
}