forked from hsanjuan/go-captive
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathallowed_proxy.go
More file actions
51 lines (42 loc) · 1.18 KB
/
allowed_proxy.go
File metadata and controls
51 lines (42 loc) · 1.18 KB
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
package captive
import (
"fmt"
"log"
"net"
"github.com/google/tcpproxy"
)
// allowedProxy redirects non allowed TCP-HTTP(s) requests to
// a custom target while letting allowed requests through to their
// original destination
type allowedProxy struct {
whitelist *whitelist
port int
nonAllowedTarget *tcpproxy.TargetListener
}
func (pxy *allowedProxy) HandleConn(c net.Conn) {
tconn, ok := c.(*tcpproxy.Conn)
if !ok { // non proxied traffic gets dropped
return
}
ip := extractIP(c.RemoteAddr().String())
if pxy.whitelist.isAllowed(ip) {
if hn := tconn.HostName; hn != "" {
// proxy this connection
log.Printf("Redirect: Proxying allowed to %s:%d (%s)", hn, pxy.port, ip)
dp := tcpproxy.To(fmt.Sprintf("%s:%d", tconn.HostName, pxy.port))
dp.HandleConn(c)
return
}
// Hostname not set, do not proxy.
c.Close()
return
}
log.Printf("Proxying disallowed to %s:%d (%s)", tconn.HostName, pxy.port, ip)
// We cannot redirect HTTPs nicely, so we just close the connection.
if pxy.port == 443 && pxy.nonAllowedTarget == nil {
c.Close()
return
}
// For the rest, we can just use the nonAllowedTarget.
pxy.nonAllowedTarget.HandleConn(c)
}