-
Notifications
You must be signed in to change notification settings - Fork 10
/
gontlm-proxy.go
205 lines (175 loc) · 5.29 KB
/
gontlm-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
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
package ntlm_proxy
import (
"context"
"flag"
"net"
"net/http"
"net/url"
"os"
// "regexp"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/ReneKroon/ttlcache/v2"
"github.com/bdwyertech/proxyplease"
"github.com/elazarl/goproxy"
"golang.org/x/sync/singleflight"
// "github.com/bhendo/concord"
// "github.com/bhendo/concord/handshakers"
)
var ProxyBind string
var ProxyServer string
var ProxyVerbose bool
func init() {
flag.StringVar(&ProxyBind, "bind", getEnv("GONTLM_BIND", "http://0.0.0.0:3128"), "IP & Port to bind to")
flag.StringVar(&ProxyServer, "proxy", getEnv("GONTLM_PROXY", ""), "Forwarding proxy server")
flag.BoolVar(&ProxyVerbose, "verbose", false, "Enable verbose logging")
}
var ProxyUser = os.Getenv("GONTLM_USER")
var ProxyPass = os.Getenv("GONTLM_PASS")
var ProxyDomain = os.Getenv("GONTLM_DOMAIN")
var ProxyOverrides *map[string]*url.URL
var ProxyDialerCacheTimeout = 60 * time.Minute
func Run() {
proxy := goproxy.NewProxyHttpServer()
//
// Log Configuration
//
if _, verbose := os.LookupEnv("GONTLM_PROXY_VERBOSE"); log.IsLevelEnabled(log.DebugLevel) || ProxyVerbose || verbose {
if !log.IsLevelEnabled(log.DebugLevel) {
log.SetLevel(log.DebugLevel)
}
proxy.Verbose = true
}
// Override ProxyPlease Logger
proxyplease.SetDebugf(func(section string, msgs ...interface{}) {
log.Debugf("proxyplease."+section, msgs...)
})
if ProxyServer == "" {
ProxyServer = getProxyServer()
}
bind, err := url.Parse(ProxyBind)
if err != nil {
log.Fatal(err)
}
log.Infof("Listening on: %s", bind.Host)
var proxyUrl *url.URL
if ProxyServer != "" {
proxyUrl, err = url.Parse(ProxyServer)
if err != nil {
log.Fatal(err)
}
if isLocalHost(proxyUrl.Hostname()) {
if bind.Port() == proxyUrl.Port() {
log.WithFields(log.Fields{
"Bind": bind.Host,
"Proxy": proxyUrl.Host,
}).Fatal("Loop condition detected!")
}
}
log.Infof("Forwarding Proxy is: %s", proxyUrl.Redacted())
}
//
// LRU Cache: Memoize DialContexts for 60 minutes
//
dialerCache := ttlcache.NewCache()
dialerCache.SetTTL(ProxyDialerCacheTimeout)
dialerCacheGroup := singleflight.Group{}
proxyDialer := func(scheme, addr string, pxyUrl *url.URL) proxyplease.DialContext {
cacheKey := addr
if pxyUrl != nil && pxyUrl.Host != "" && ProxyOverrides == nil {
cacheKey = pxyUrl.Host
}
if dctx, err := dialerCache.Get(cacheKey); err == nil {
return dctx.(proxyplease.DialContext)
}
dctx, err, _ := dialerCacheGroup.Do(cacheKey, func() (pxyCtx interface{}, err error) {
if ProxyOverrides != nil {
for _, host := range []string{addr, strings.Split(addr, ":")[0]} {
if pxy, ok := (*ProxyOverrides)[strings.ToLower(host)]; ok {
if pxy == nil {
d := net.Dialer{}
return d.DialContext, nil
}
pxyUrl = pxy
}
}
}
pxyCtx = proxyplease.NewDialContext(proxyplease.Proxy{
URL: pxyUrl,
Username: ProxyUser,
Password: ProxyPass,
Domain: ProxyDomain,
TargetURL: &url.URL{Host: addr, Scheme: scheme},
})
err = dialerCache.Set(cacheKey, pxyCtx)
return
})
if err != nil {
log.Fatal(err)
}
return dctx.(proxyplease.DialContext)
}
//
// Proxy DialContexts
//
proxy.Tr.Proxy = nil
// HTTP
proxy.Tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return proxyDialer("http", addr, proxyUrl)(ctx, network, addr)
}
// HTTPS
proxy.ConnectDial = func(network, addr string) (net.Conn, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
return proxyDialer("https", addr, proxyUrl)(ctx, network, addr)
}
//
// HTTP Handler
//
// var HttpConnect goproxy.FuncHttpsHandler = func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
// HTTPConnect := &goproxy.ConnectAction{
// Action: goproxy.ConnectAccept,
// TLSConfig: goproxy.TLSConfigFromCA(&goproxy.GoproxyCa),
// }
//
// return HTTPConnect, host
// }
// proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(".*:80$|.*:8080$"))).HandleConnect(HttpConnect)
//
// Connect Handler
//
var AlwaysMitm goproxy.FuncHttpsHandler = func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
// HTTPSConnect := &goproxy.ConnectAction{
// // ConnectMitm enables SSL Interception, required for request filtering over HTTPS.
// // Action: goproxy.ConnectMitm,
// // ConnectAccept preserves upstream SSL Certificates, etc. TCP tunneling basically.
// Action: goproxy.ConnectAccept,
// TLSConfig: goproxy.TLSConfigFromCA(&goproxy.GoproxyCa),
// }
// return HTTPSConnect, host
return goproxy.OkConnect, host
}
proxy.OnRequest().HandleConnect(AlwaysMitm)
//
// Request Handling
//
// MITM Action is required for HTTPS Requests (e.g. goproxy.ConnectMitm instead of goproxy.ConnectAccept)
//
// proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
// log.Fatal(req.URL.String())
// return req, nil
// })
srv := &http.Server{
Addr: bind.Host,
Handler: proxy,
IdleTimeout: time.Second * 60,
}
log.Fatal(srv.ListenAndServe())
}
// Check if it is a WebSocketUpgrade
// func IsWebSocketUpgrade() goproxy.ReqConditionFunc {
// return func(req *http.Request, ctx *goproxy.ProxyCtx) bool {
// return websocket.IsWebSocketUpgrade(req)
// }
// }