-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
168 lines (151 loc) · 4.42 KB
/
main.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
package main
import (
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
log "github.com/Sirupsen/logrus"
"github.com/olebedev/config"
)
// AppVersion is the global application version
var AppVersion string
// CommitID is the current git commit of this build
var CommitID string
func main() {
var (
inner net.Listener
serverAddr, remoteAddr string
serverTCPAddr *net.TCPAddr
remoteTLS *tls.Config
err error
shm *SigHandlerMux
)
cfg, err = getConfig()
if err != nil {
log.Fatal(err)
os.Exit(1)
}
flag.Usage = func() {
fmt.Println("Version: ", AppVersion, "| Commit", CommitID)
fmt.Println("Description: TLSpxy - Tiny TLS termination tool")
fmt.Println("Usage: tlspxy [OPTIONS]")
fmt.Println("Options:")
m, _ := cfg.Map("")
prettyPrintFlagMap(m)
fmt.Println("All options can be set via flags, environment variables, or configuration files.",
"\n -> See https://github.com/colebrumley/tlspxy/wiki/Configuration for details.")
}
// Load priority => Files < Env < Flag
cfg.Env().Flag()
// Create the SigHandlerMux and configure logging
shm = &SigHandlerMux{
do: map[os.Signal][]func(){},
}
go shm.WatchForSignals()
configLogging(cfg)
// Print the loaded config if debug is on
c, _ := config.RenderYaml(cfg.Root)
log.Debugln("Loaded config:\n", c)
// Parse the Server listener config
if serverAddr, err = cfg.String("server.addr"); err != nil {
log.Error("No server address defined!")
os.Exit(1)
}
if serverTCPAddr, err = net.ResolveTCPAddr("tcp", serverAddr); err != nil {
log.Error(err)
os.Exit(1)
}
// Create the base TCP listener. Both TCP and HTTP proxies will
// be based on this listener.
if inner, err = net.ListenTCP("tcp", serverTCPAddr); err != nil {
log.Error(err)
}
// Configure the server's TLS settings
listener := configServerTLS(inner, cfg)
// Load the remote config. This will depend on what kind of listener
// we have configured.
if remoteTLS, err = configRemoteTLS(cfg); err != nil {
log.Warningf("Skipping client TLS configuration: %v", err)
remoteTLS = nil
}
switch cfg.UString("server.type", "tcp") {
case "tcp":
// Pull remote.addr out of Config and convert to *net.TCPAddr
if remoteAddr, err = cfg.String("remote.addr"); err != nil {
log.Error("No remote address defined!")
os.Exit(1)
}
log.Infof("Opening proxy from %s to %s", serverAddr, remoteAddr)
ctr := ProxyCounter{}
shm.AddHandler(ctr.InterruptHandler, os.Interrupt, os.Kill)
connID := 0
for {
conn, err := listener.Accept()
if err != nil {
log.Errorf("Failed to accept connection '%s'", err)
continue
}
connID++
log.Infof("Accepted connection #%v from %s", connID, conn.RemoteAddr().String())
p := &TCPProxy{
Counter: &ctr,
ServerConn: conn,
ServerAddr: serverAddr,
RemoteAddr: remoteAddr,
RemoteTLSConf: remoteTLS,
ErrorState: false,
ErrorSignal: make(chan bool),
prefix: fmt.Sprintf("Connection #%03d ", connID),
showContent: cfg.UBool("log.contents", false),
}
go p.start()
}
case "http", "https":
var (
u *url.URL
rp *httputil.ReverseProxy
)
if u, err = url.Parse(cfg.UString("remote.addr")); err != nil {
log.Error(err)
}
myIP := GetOutboundIP()
director := func(req *http.Request) {
oldURL := req.URL.String()
req.Host = u.Host
req.URL.Scheme = u.Scheme
req.URL.Host = u.Host
req.URL.Path = singleJoiningSlash(u.Path, req.URL.Path)
req.RemoteAddr = myIP
if u.RawQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = u.RawQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = u.RawQuery + "&" + req.URL.RawQuery
}
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
log.Debugf("Rewrote request URL %s to %s", oldURL, req.URL.String())
}
proxy := &ProxyTransport{
ShowContent: cfg.UBool("log.contents", false),
RoundTripper: &http.Transport{
TLSClientConfig: remoteTLS,
},
}
shm.AddHandler(proxy.InterruptHandler, os.Interrupt, os.Kill)
rp = &httputil.ReverseProxy{
Director: director,
Transport: proxy,
}
log.Infof("Opening proxy from %s to %s", serverTCPAddr.String(), u.String())
http.Serve(listener, rp)
default:
log.Errorln("Unknown server type requested!")
os.Exit(1)
}
}