forked from kost/revsocks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrserver.go
313 lines (282 loc) · 8.92 KB
/
rserver.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package main
import (
"crypto/tls"
"fmt"
"io"
"log"
"net"
"os"
"bufio"
"github.com/hashicorp/yamux"
"strconv"
"strings"
"time"
"context"
"net/http"
"nhooyr.io/websocket"
"sync"
"golang.org/x/crypto/acme/autocert"
"path/filepath"
)
var proxytout = time.Millisecond * 1000 //timeout for wait magicbytes
type agentHandler struct {
mu sync.Mutex
listenstr string // listen string for clients
portnext int // next port for listen
timeout time.Duration
sessions []*yamux.Session // all sessions
// agentstr string // connecting agent combo (IP:port)
}
func (h *agentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var session *yamux.Session
var erry error
agentstr := r.RemoteAddr
log.Printf("[%s] Got HTTP request (%s): %s", agentstr, r.Method, r.URL.String())
if r.Header.Get("Upgrade") != "websocket" {
w.Header().Set("Location", "https://www.microsoft.com/")
w.WriteHeader(http.StatusFound) // Use 302 status code for redirect
// fmt.Fprintf(w, "OK")
return
}
if r.Header.Get("Accept-Language") != agentpassword {
w.Header().Set("Location", "https://www.microsoft.com/")
w.WriteHeader(http.StatusFound) // Use 302 status code for redirect
// fmt.Fprintf(w, "OK")
return
}
c, err := websocket.Accept(w, r, nil)
if err != nil {
log.Printf("[%s] Error upgrading to socket (%s): %v", agentstr, r.RemoteAddr, err)
http.Error(w, "Bad request - Go away!", 500)
return
}
defer c.CloseNow()
if h.timeout > 0 {
_, cancel := context.WithTimeout(r.Context(), time.Second*60)
defer cancel()
}
nc_over_ws := websocket.NetConn(context.Background(), c, websocket.MessageBinary)
//Add connection to yamux
session, erry = yamux.Client(nc_over_ws, nil)
if erry != nil {
log.Printf("[%s] Error creating client in yamux for (%s): %v", agentstr, r.RemoteAddr, erry)
http.Error(w, "Bad request - Go away!", 500)
return
}
h.sessions = append(h.sessions, session)
h.mu.Lock()
listenport := h.portnext
h.portnext = h.portnext + 1
h.mu.Unlock()
listenForClients(agentstr, h.listenstr, listenport, session)
c.Close(websocket.StatusNormalClosure, "")
}
func listenForWebsocketAgents(tlslisten bool, address string, clients string, certificate string, autocertdomain string) error {
var cer tls.Certificate
var err error
log.Printf("Will start listening for clients on %s", clients)
var listenstr = strings.Split(clients, ":")
portnum, errc := strconv.Atoi(listenstr[1])
if errc != nil {
log.Printf("Error converting listen str %s: %v", clients, errc)
}
aHandler := &agentHandler{
portnext: portnum,
listenstr: listenstr[0],
}
server := &http.Server{
Addr: address, // e.g. ":8443"
Handler: aHandler,
}
if tlslisten {
if autocertdomain != "" {
log.Printf("Getting TLS certificate for %s", autocertdomain)
dirname, err := os.UserHomeDir()
if err != nil {
log.Printf("Error getting TLS certificate for %s: %v", autocertdomain, err)
}
cachepath := filepath.Join(dirname, ".revsocks-autocert")
m := &autocert.Manager{
Cache: autocert.DirCache(cachepath),
Prompt: autocert.AcceptTOS,
// Email: "[email protected]",
HostPolicy: autocert.HostWhitelist(autocertdomain),
}
server.TLSConfig = m.TLSConfig()
} else {
if certificate == "" {
cer, err = getRandomTLS(2048)
log.Println("No TLS certificate. Generated random one.")
} else {
cer, err = tls.LoadX509KeyPair(certificate+".crt", certificate+".key")
}
if err != nil {
log.Printf("Error creating/loading certificate file %s: %v", certificate, err)
return err
}
// config := &tls.Config{Certificates: []tls.Certificate{cer}}
server.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cer},
}
}
}
log.Printf("Listening for websocket agents on %s (TLS: %t)", address, tlslisten)
if tlslisten {
err = server.ListenAndServeTLS("", "")
} else {
err = server.ListenAndServe()
}
return nil
}
// listen for agents
func listenForAgents(tlslisten bool, address string, clients string, certificate string, autocertdomain string) error {
var err, erry error
var cer tls.Certificate
var session *yamux.Session
var sessions []*yamux.Session
var ln net.Listener
log.Printf("Will start listening for clients on %s and agents on %s (TLS: %t)", clients, address, tlslisten)
if tlslisten {
if autocertdomain != "" {
log.Printf("Getting TLS certificate for %s", autocertdomain)
dirname, err := os.UserHomeDir()
if err != nil {
log.Printf("Error getting TLS certificate for %s: %v", autocertdomain, err)
}
cachepath := filepath.Join(dirname, ".revsocks-autocert")
m := &autocert.Manager{
Cache: autocert.DirCache(cachepath),
Prompt: autocert.AcceptTOS,
// Email: "[email protected]",
HostPolicy: autocert.HostWhitelist(autocertdomain),
}
ln, err = tls.Listen("tcp", address, m.TLSConfig())
} else {
if certificate == "" {
cer, err = getRandomTLS(2048)
log.Println("No TLS certificate. Generated random one.")
} else {
cer, err = tls.LoadX509KeyPair(certificate+".crt", certificate+".key")
}
if err != nil {
log.Println(err)
return err
}
config := &tls.Config{Certificates: []tls.Certificate{cer}}
ln, err = tls.Listen("tcp", address, config)
}
} else {
ln, err = net.Listen("tcp", address)
}
if err != nil {
log.Printf("Error listening on %s: %v", address, err)
return err
}
var listenstr = strings.Split(clients, ":")
portnum, errc := strconv.Atoi(listenstr[1])
if errc != nil {
log.Printf("Error converting listen str %s: %v", clients, errc)
}
portinc := 0
for {
conn, err := ln.Accept()
conn.RemoteAddr()
agentstr := conn.RemoteAddr().String()
log.Printf("[%s] Got a connection from %v: ", agentstr, conn.RemoteAddr())
if err != nil {
fmt.Fprintf(os.Stderr, "Errors accepting!")
}
reader := bufio.NewReader(conn)
//read only 64 bytes with timeout=1-3 sec. So we haven't delay with browsers
conn.SetReadDeadline(time.Now().Add(proxytout))
statusb := make([]byte, 64)
_, _ = io.ReadFull(reader, statusb)
//Alternatively - read all bytes with timeout=1-3 sec. So we have delay with browsers, but get all GET request
//conn.SetReadDeadline(time.Now().Add(proxytout))
//statusb,_ := ioutil.ReadAll(magicBuf)
//log.Printf("magic bytes: %v",statusb[:6])
//if hex.EncodeToString(statusb) != magicbytes {
if string(statusb)[:len(agentpassword)] != agentpassword {
//do HTTP checks
log.Printf("Received request: %v", string(statusb[:64]))
status := string(statusb)
if strings.Contains(status, " HTTP/1.1") {
httpresonse := "HTTP/1.1 301 Moved Permanently" +
"\r\nContent-Type: text/html; charset=UTF-8" +
"\r\nLocation: https://www.microsoft.com/" +
"\r\nServer: Apache" +
"\r\nContent-Length: 0" +
"\r\nConnection: close" +
"\r\n\r\n"
conn.Write([]byte(httpresonse))
conn.Close()
} else {
conn.Close()
}
} else {
//magic bytes received.
//disable socket read timeouts
log.Printf("[%s] Got Client from %s", agentstr, conn.RemoteAddr())
conn.SetReadDeadline(time.Now().Add(100 * time.Hour))
//Add connection to yamux
session, erry = yamux.Client(conn, nil)
if erry != nil {
log.Printf("[%s] Error creating client in yamux for %s: %v", agentstr, conn.RemoteAddr(), erry)
continue
}
sessions = append(sessions, session)
go listenForClients(agentstr, listenstr[0], portnum+portinc, session)
portinc = portinc + 1
}
}
return nil
}
// Catches local clients and connects to yamux
func listenForClients(agentstr string, listen string, port int, session *yamux.Session) error {
var ln net.Listener
var address string
var err error
portinc := port
for {
address = fmt.Sprintf("%s:%d", listen, portinc)
log.Printf("[%s] Handshake recognized. Waiting for clients on %s", agentstr, address)
ln, err = net.Listen("tcp", address)
if err != nil {
log.Printf("[%s] Error listening on %s: %v", agentstr, address, err)
portinc = portinc + 1
} else {
break
}
}
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("[%s] Error accepting on %s: %v", agentstr, address, err)
return err
}
if session == nil {
log.Printf("[%s] Session on %s is nil", agentstr, address)
conn.Close()
continue
}
log.Printf("[%s] Got client. Opening stream for %s", agentstr, conn.RemoteAddr())
stream, err := session.Open()
if err != nil {
log.Printf("[%s] Error opening stream for %s: %v", agentstr, conn.RemoteAddr(), err)
return err
}
// connect both of conn and stream
go func() {
log.Printf("[%s] Starting to copy conn to stream for %s", agentstr, conn.RemoteAddr())
io.Copy(conn, stream)
conn.Close()
log.Printf("[%s] Done copying conn to stream for %s", agentstr, conn.RemoteAddr())
}()
go func() {
log.Printf("[%s] Starting to copy stream to conn for %s", agentstr, conn.RemoteAddr())
io.Copy(stream, conn)
stream.Close()
log.Printf("[%s] Done copying stream to conn for %s", agentstr, conn.RemoteAddr())
}()
}
}